1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <queue>
 5 
 6 using namespace std;
 7 
 8 const int maxn = 105, maxm = maxn * maxn * 2, inf = 1e9;
 9 
10 int n, m, kase, T, tot;
11 
12 int h[maxn], inqueue[maxn];
13 
14 int dis[maxn];
15 
16 struct edge
17 {
18     int v, next;
19     int w;
20 }a[maxm];
21 
22 void add(int x, int y, int z)
23 {
24     a[tot].v = y;
25     a[tot].w = z;
26     a[tot].next = h[x];
27     h[x] = tot++;
28 }
29 
30 void init()
31 {
32     memset(h, -1, sizeof h); tot = 0;
33     memset(inqueue, 0, sizeof inqueue);
34     for (int i = 1; i <= n; i++)
35     {
36         dis[i] = inf;
37     } 
38     dis[1] = 0; inqueue[1] = 1;
39 }
40 
41 int main()
42 {
43     freopen("SPFA.in","r",stdin);
44     while (scanf("%d%d", &n, &m) && n && m)
45     {
46         init();
47         for (int i = 1; i <= m; i++)
48         {
49             int x, y, z;
50             scanf("%d%d%d", &x, &y, &z);
51             add(x, y, z); add(y, x, z);
52         }
53         queue<int> q;
54         q.push(1);
55         while (!q.empty())
56         {
57             int u = q.front(); q.pop(); inqueue[u] = 0;
58             for (int i = h[u]; ~i; i = a[i].next)
59             {
60                 int v = a[i].v;
61                 if (dis[u] + a[i].w < dis[v])
62                 {
63                     dis[v] = dis[u] + a[i].w;
64                     if (!inqueue[v])
65                     {
66                         q.push(v);
67                         inqueue[v] = 1;
68                     }
69                 }
70             }
71         }
72         for (int i = 1; i <= n; i++)
73         {
74             printf("%d:%d\n", i, dis[i]);
75         }
76         printf("\n");
77     }            
78     return 0;
79 }
SPFA

相关文章:

  • 2022-12-23
  • 2021-06-08
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2021-05-05
  • 2021-09-28
  • 2021-12-17
猜你喜欢
  • 2021-08-06
  • 2022-12-23
  • 2021-06-05
  • 2022-12-23
  • 2021-06-28
  • 2021-08-27
  • 2022-12-23
相关资源
相似解决方案