hdu3790 最短路径问题 (dijkstra,双关键值最短路)

时间:2022-02-19 13:10:58

最短路径问题

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 19606    Accepted Submission(s): 5837


Problem Description
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
 

Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
 

Output
输出 一行有两个数, 最短距离及其花费。
 

Sample Input
 
 
3 2 1 2 5 6 2 3 4 5 1 3 0 0
 

Sample Output
 
 
9 11
 

Source
 

Recommend
notonlysuccess   |   We have carefully selected several similar problems for you:   1142  1548  1598  1596  1162 
 


代码:

#include<cstdio>
#include<cstring>
using namespace std;

const int maxn=1e3;
struct tnode{
	int point;
	int distance;
	int price;
	tnode *next;
}*h[maxn+5];
int n,s,e,dist[maxn+5],cost[maxn+5];
bool used[maxn+5];

void add(int a,int b,int d,int p)
{
  tnode *q=new tnode;
  (*q).point=b;
  (*q).distance=d;
  (*q).price=p;
  (*q).next=h[a],h[a]=q;
}

void dijkstra()
{
  memset(dist,10,sizeof(dist)),dist[s]=0;
  memset(cost,10,sizeof(cost)),cost[s]=0;
  memset(used,0,sizeof(used));
  
  int i,j,k,x;tnode *p;
  for(i=1;i<n;i++)
    {
      for(k=0,j=1;j<=n;j++)
        {
          if(used[j] || dist[j]>dist[k])continue;
          if(dist[j]<dist[k])goto d1;
          if(cost[j]<cost[k])d1:k=j;
		}
	  if(k==e)return;
	  used[k]=1;
	  for(p=h[k];p;p=(*p).next)
	    {
	      x=dist[k]+(*p).distance;
	      if(dist[(*p).point]<x)continue;
	      if(dist[(*p).point]>x)
		    {
			  dist[(*p).point]=x;
			  cost[(*p).point]=cost[k]+(*p).price;
			  continue;  
			}
	      x=cost[k]+(*p).price;
	      if(cost[(*p).point]>x)cost[(*p).point]=x;
		}
	}
}

int main()
{
  //freopen("1.in","r",stdin);
  
  int m,i,a,b,d,p;
  while(scanf("%d%d",&n,&m),n)
    {
      for(i=1;i<=n;i++)h[i]=NULL;
      while(m--)
        {
          scanf("%d%d%d%d",&a,&b,&d,&p);
          add(a,b,d,p),add(b,a,d,p);
		}
	  scanf("%d%d",&s,&e),dijkstra();
	  printf("%d %d\n",dist[e],cost[e]);
	}
  return 0;
}