HDOJ 3790 最短路径问题 SPFA

因为没有对边判重,白白WA了好几次,注意输入时必须要对边判重

 

AC   187MS    8100K

 1 #include <queue>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <memory.h>
 5 using namespace std;
 6 
 7 const int maxn = 1001;
 8 const int INF = 0x3F3F3F3F;
 9 
10 int a, b, d, p, nNum, mNum;
11 int dist[maxn], px[maxn], QM[maxn];
12 int cost[maxn][maxn], g[maxn][maxn];
13 
14 void spfa(int sx, int tx)
15 {
16     int   xx;
17     queue <int> q;
18     
19     q.push(sx);
20     QM[sx]=1, dist[sx]=0, px[sx]=0;
21     
22     while (!q.empty())
23     {
24         xx = q.front();
25         q.pop();
26         QM[xx] = 0; /* Took Away */
27         
28         for (int i=1; i<=nNum; ++i)
29         {
30             if (dist[i] > dist[xx]+g[xx][i])
31             {
32                 dist[i] = dist[xx] + g[xx][i];
33                 px[i] = px[xx] + cost[xx][i];
34                 
35                 if (QM[i] == 0)
36                 {
37                     QM[i] = 1;
38                     q.push(i);
39                 }
40             }/* End of if */
41             else if (dist[i]==dist[xx]+g[xx][i]
42                     && px[i]>px[xx]+cost[xx][i])
43             {
44                 px[i] = px[xx] + cost[xx][i];
45             }
46         }/* End of For */
47     }/* End of While */
48     
49     printf("%d %d\n", dist[tx], px[tx]);
50 }/* spfa */
51 
52 int main()
53 {
54     while (~scanf("%d %d", &nNum, &mNum), nNum+mNum!=0)
55     {        
56         for (int i=1; i<=nNum; ++i)
57         {
58             QM[i] = 0;
59             px[i] = dist[i] = INF;
60             
61             for (int j=1; j<=nNum; ++j)
62                 g[i][j] = cost[i][j] = INF;
63         }/* End of For */
64         
65         for (int i=1; i<=mNum; ++i)
66         {
67             scanf("%d %d %d %d", &a, &b, &d, &p);
68             
69             if (d < g[a][b])  /* 判重 */ 
70             {
71                 g[a][b] = g[b][a] = d;
72                 cost[a][b] = cost[b][a] = p;
73             }    
74         }/* End of For */
75         
76         int sx, tx;
77         
78         scanf("%d %d", &sx, &tx);
79         spfa(sx, tx);
80     }/* End of While */
81     
82     return 0;
83 }

 

posted @ 2012-08-09 14:50  Maxwell:My Blog  阅读(521)  评论(0编辑  收藏  举报