-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellman-Ford.cpp
More file actions
105 lines (93 loc) · 2.77 KB
/
Bellman-Ford.cpp
File metadata and controls
105 lines (93 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*********************************************************************************
*@copyright (C) 2018 san All Rights Reserved
*@file Bellman-Ford.cpp
*@date Sep 2018
*@author san
*@CMAKE_CXX_STANDARD 17
*@IDE: Clion 2018.3
*@OS: macOS High Sierra 10.13.6
*
*@brief:
*@function_lists:
* 1.
*@ Time complexity: O(NM)
*@warning:
*@history:
1.Date:
Author:
Modification: 在未大道n-1轮松弛前就已经计算出最段路,so add an array to store array dis.
如果新一轮的松弛中数组dis没有发生变化,则可以提前跳出循环
**********************************************************************************/
#include <iostream>
#include <cstdio>
using namespace std;
const int inf = 99999999; // use inf(infinity)to store a value which we consider positive infinity. 两个正无穷相加也小于2147483647(the max of int)
int main() {
int dis[10],bak[10],i,k,n,m,u[10],v[10],w[10],check = 0,flag = 0;
// read n and m, N represents the number of vertices and M represents the number of edges.
cin >> n >> m;
// Read the edge
for (i = 1; i <= m ; i++) {
cin >> u[i] >> v[i] >> w[i];
}
// Initialization of dis array,This is the initial distance from vertex 1 to the rest of the vertices.
for(i = 1; i <= n; i++){
dis[i] = inf;
}
dis[1] = 0;
/*
// core code of Bellman-Ford
for (k = 1; k <= n-1 ; k++) {
for (i = 1; i <= m ; i++) {
if(dis[v[i]] > dis[u[i]] + w[i])
dis[v[i]] = dis[u[i]] + w[i];
}
}
// output the result
for (i = 1; i <= n ; i++) {
cout << dis[i] << " ";
}
*/
// modify improve
for (k = 1; k <= n-1 ; k++) {
// 就dis数组备份至bak数组
for(i = 1; i <= n; i++) bak[i] = dis[i];
// 进行一轮松弛
for (i = 1; i <= m ; i++) {
if(dis[v[i]] > dis[u[i]] + w[i])
dis[v[i]] = dis[u[i]] + w[i];
}
// 松弛完毕后检测dis数组是否有更新
check = 0;
for (i = 1; i <= n ; i++) {
if(bak[i] != dis[i]){
check = 1;
break;
}
if(check == 0){
break; // 如果新一轮的松弛中数组dis没有发生变化,则可以提前跳出循环
}
}
}
// 检测负权回路
flag = 0;
for (i = 1; i <= m; i++) {
if(dis[v[i]] > dis[u[i]] + w[i])
flag = 1;
}
if(flag == 1) cout << "This graph contains a negative weight loop. " << endl;
else { // output the result
for (i = 1; i <= n ; i++) {
cout << dis[i] << " ";
}
}
}
Input:
5 5
2 3 2
1 2 -3
1 5 5
4 5 2
3 4 3
Output:
0 -3 -1 2 4