BellmanFord

0
2
4
7
-2
Single source shorted path from vetex 0 exist? yes

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
//O(V*E)
bool bellman_ford(int n, vector<vector<int>> &edges) {
vector<int> distance(n, INT_MAX);

distance[0] = 0;
for (int i = 0; i < n; i++) {
for (auto &edge : edges) {
int u = edge[0];
int v = edge[1];
int w = edge[2];

distance[v] = min(distance[v], distance[u] + w);
}
}

for (auto &edge : edges) {
int u = edge[0];
int v = edge[1];
int w = edge[2];

if (distance[v] > distance[u] + w)
return false;
}

for (int d : distance)
cout << d << endl;

return true;
}

int main()
{
int n = 5;
vector<vector<int>> edges = {{0,1,6},{0,3,7},{1,2,5},{1,3,8},{1,4,-4},
{2,1,-2},{3,2,-3},{3,4,9},{4,0,2},{4,2,7}};
bool ret = bellman_ford(n, edges);
printf("Single source shorted path from vetex 0 exist? %s\n", ret ? "yes" : "no");

return 0;
}