-
Notifications
You must be signed in to change notification settings - Fork 0
/
bellmanFord.cpp
77 lines (67 loc) · 1.42 KB
/
bellmanFord.cpp
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
#include <iostream>
#include <vector>
using namespace std;
const int N = 1000+21;
const int INF = 1000000000+21;
int n, m, a, b, c;
int dist[N];
vector<pair<pair<int, int>, int> > edges;
bool bellmanFord(int v)
{
dist[v] = 0;
// update the distances
for (int i=1; i<=n-1; i++)
{
for (int j=0; j<m; j++)
{
int u, v, weight;
u = edges[j].first.first;
v = edges[j].first.second;
weight = edges[j].second;
if (dist[u] != INF && dist[u] + weight < dist[v])
{
dist[v] = dist[u] + weight;
}
}
}
// check for negative cycles
for (int j=0; j<m; j++)
{
int u, v, weight;
u = edges[j].first.first;
v = edges[j].first.second;
weight = edges[j].second;
if (dist[u] != INF && dist[u] + weight < dist[v])
{
return false;
}
}
return true;
}
int main()
{
cin>>n>>m;
for (int i=1; i<=n; i++)
dist[i] = INF;
for (int i=0; i<m; i++)
{
cin>>a>>b>>c;
edges.push_back({{a, b}, c});
}
bool ans = bellmanFord(1);
if (ans)
{
for (int i=1; i<=n; i++)
{
if (dist[i] == INF)
cout<<"INF ";
else
cout<<dist[i]<<" ";
}
cout<<endl;
}
else
{
cout<<"Contains negative cycle\n";
}
}