dijkstra 与 spfa

Posted yohanlong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了dijkstra 与 spfa相关的知识,希望对你有一定的参考价值。

技术分享
 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
技术分享
 1 priority_queue<node> q;
 2 
 3 void dijk(int s)
 4 {
 5     for (int i = 1; i <= n; i++)
 6         dis[i] = inf;
 7     memset(done, 0, sizeof done);
 8     dis[s] = 0;
 9     q.push((node){s, 0});
10     while (!q.empty())
11     {
12         node x = q.top(); q.pop();
13         int u = x.u;
14         if (done[u]) continue;
15         done[u] = 1;
16         for (int i = h[u]; ~i; i = a[i].next)
17         {
18             int v = a[i].v;
19             if (dis[u] + a[i].w < dis[v])
20             {
21                 dis[v] = dis[u] + a[i].w;
22                 p[s][v] = u;
23                 q.push((node){v, dis[v]});
24             }
25         }
26     }
dijkstra

 区别在于,SPFA是先松弛再看看该点能否重复利用。

dijkstra是先看看该点能否重复利用,再松弛。

以上是关于dijkstra 与 spfa的主要内容,如果未能解决你的问题,请参考以下文章

算法描述》关于SPFA和Dijkstra算法的两三事

hdoj2544 最短路(Dijkstra || Floyd || SPFA)

最短路(Dijkstra,Floyd,Bellman_Ford,SPFA)

dijkstra和spfa相比,那个更好一些

最短路 P1144 最短路计数Dijkstra堆优化/SPFA

最短路 P1144 最短路计数Dijkstra堆优化/SPFA