HDOJ 2544 - 最短路 SPFA算法

因为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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值