HDOJ 2544 - 最短路 SPFA算法

自闭症网瘾萝莉.ら 提交于 2019-11-26 17:41:14

因为QM混乱的原因,白白WA了好几次

 

AC     0MS    228K

 1 #include <queue>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <memory.h>
 5 using namespace std;
 6 
 7 const int maxn = 101;
 8 const int INF = 0x3F3F3F3F;
 9 
10 int a, b, c, nNum, mNum;
11 int g[maxn][maxn], QM[maxn], dist[maxn];
12 
13 int SPFA()
14 {
15     int x;
16     queue <int> q;
17     
18     q.push(1);
19     QM[1] = 1, dist[1] = 0;
20     
21     while (!q.empty())
22     {
23         x = q.front();
24         q.pop();
25         QM[x] = 0; /* Took Away*/
26         
27         for (int i=1; i<=nNum; ++i)
28         {
29             if (dist[i] > dist[x]+g[x][i])
30             {
31                 dist[i] = dist[x] + g[x][i]; /* change the weight */
32                 
33                 /* push into queue if vertex i is QM of queue */
34                 if (QM[i] == 0)
35                 {
36                     QM[i] = 1;
37                     q.push(i);
38                 }
39             }    
40         }/* End of For */
41     }/* End of While */
42     
43     return dist[nNum];
44 }/* SPFA */
45 
46 int main()
47 {
48     while (~scanf("%d %d", &nNum, &mNum), nNum+mNum!=0)
49     {
50         memset(g, INF, sizeof(g));
51         memset(QM, 0, sizeof(QM));
52         memset(dist, INF, sizeof(dist));
53         
54         for (int i=1; i<=mNum; ++i)
55         {
56             scanf("%d %d %d", &a, &b, &c);
57             g[a][b] = g[b][a] = c; /* Adjcent Matrix */
58         }/* End of For */
59         
60         printf("%d\n", SPFA());    /* Solve with spfa algorithm */
61     }/* End of While */
62     
63     return 0;
64 }

 

转载于:https://www.cnblogs.com/yewei/archive/2012/04/09/2439506.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!