hdoj 1874最短路之最短路径问题

最短路径问题

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


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
 
 
这次又是因为没判重边 贡献了两次WA  又被坑了 
这次绝对是教训啊  我错了
View Code
 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace  std;
 4 const int MAXINT =1<<29;
 5 #define Max 1005 
 6 struct pp
 7 {
 8     int lenth,cost;
 9 }f[Max][Max];
10 int s[Max],dist[Max];
11 int n,v;
12 int flag[Max];
13 
14 void dj()
15 {
16     int i;
17     for(i=1;i<=n;i++)
18     {
19         s[i]=0;
20         dist[i]=f[v][i].lenth;
21         flag[i]=f[v][i].cost;
22     }
23     s[v]=1;
24     dist[v]=0;
25     int min,u,j;
26     for(i=1;i<=n;i++)
27     {
28         min=MAXINT;
29         u=v;
30         for(j=1;j<=n;j++)
31             if(!s[j]&&min>dist[j])  min=dist[u=j];
32             s[u]=1;
33             for(j=1;j<=n;j++)
34             {
35                 if(!s[j]&&dist[u]+f[u][j].lenth<dist[j])
36                 {
37                 dist[j]=dist[u]+f[u][j].lenth;
38                 flag[j]=flag[u]+f[u][j].cost;
39                 }
40                 else 
41                     if(!s[j]&&dist[u]+f[u][j].lenth==dist[j]&&flag[u]+f[u][j].cost<flag[j])
42                     flag[j]=flag[u]+f[u][j].cost;
43             }
44     }
45 }
46 
47 int main()
48 {
49     int m;
50     int a,b,d,p,star,end,i,j;
51     while(cin>>n>>m,m+n)
52     {
53         for(i=1;i<=n;i++)
54         {
55             for(j=1;j<=n;j++)
56                 f[i][j].lenth=MAXINT;
57             flag[i]=0;
58         }
59             for (i=0;i<m;i++)
60             {
61                 scanf("%d%d%d%d",&a,&b,&d,&p);
62                 if (f[a][b].lenth>d)
63                 {//判重边  又一次被坑了
64                     f[a][b].lenth= f[b][a].lenth=d;
65                      f[a][b].cost=f[b][a].cost=p;
66                 }
67             
68             }
69             cin>>v>>end;
70             dj();            
71             cout<<dist[end]<<" "<<flag[end]<<endl;
72     }
73     
74     return 0;
75 }
原文地址:https://www.cnblogs.com/wujianwei/p/2588810.html