Bellman-ford算法 无向图

 1 // 单源最短路问题
 2 // Bellman-Ford算法
 3 // 复杂度O(V*E)
 4 
 5 //! 可以判断负圈
 6 
 7 
 8 #include <cstdio>
 9 #include <iostream>
10 
11 // 最大边数
12 const int max_E=10000+2;
13 // 最大定点数
14 const int max_N=1000+2;
15 const int INF=1e9;
16 
17 using namespace std;
18 // 定义边结构体edge
19 struct edge
20 {
21     int from,to,cost;
22 };
23 
24 edge es[max_E*2];
25 
26 int d[max_N];
27 int N,E;
28 
29 void shortest_path(int s)
30 {
31     for(int i=0;i<=N;++i)
32     {
33         d[i]=INF;
34     }
35     d[s]=0;
36 
37     while(true)
38     {
39         bool update=false;
40         // 每次更新都要遍历所有的边
41         // 这里是无向图,实现上稍加注意
42         for(int i=0;i<2*E;++i)
43         {
44             edge e=es[i];
45             if(d[e.from]!=INF && d[e.to]>d[e.from]+e.cost)
46             {
47                 d[e.to]=d[e.from]+e.cost;
48                 update=true;
49             }
50         }
51         if(update==false)
52         {
53             break;
54         }
55     }
56 }
57 
58 
59 int main()
60 {
61     scanf("%d %d",&N,&E);
62     // 求解无向图
63     for(int i=0;i<E;++i)
64     {
65         scanf("%d %d %d",&es[i].from,&es[i].to,&es[i].cost);
66         // 无向图
67         es[i+E].from=es[i].to;
68         es[i+E].to=es[i].from;
69         es[i+E].cost=es[i].cost;
70     }
71     shortest_path(0);
72     for(int i=0;i<N;++i)
73     {
74         printf("%d ",d[i]);
75     }
76     return 0;
77 }
78 
79 /*
80 7 10
81 0 1 2
82 0 2 5
83 1 2 4
84 1 3 6
85 1 4 10
86 2 3 2
87 3 5 1
88 4 5 3
89 4 6 5
90 5 6 9
91 
92 
93 */

猜你喜欢

转载自www.cnblogs.com/jishuren/p/12315767.html
今日推荐