-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbellmanFord.cpp
99 lines (81 loc) · 1.57 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
using namespace std;
#define inf 1e9
/*
5 8
0 1 -1
0 2 4
1 2 3
3 2 5
4 3 -3
1 4 2
1 3 2
3 1 1
*/
class Edge {
public:
int src, dest, weight;
};
class Graph {
public:
int v, e;
Edge *edge;
Graph(int v, int e) {
this->v = v;
this->e = e;
edge = new Edge[e];
}
void addEdge(int u, int v, int w, int count) {
edge[count].src = u;
edge[count].dest = v;
edge[count].weight = w;
}
void bellmanFord(int src) {
int distance[v];
for(int i=0; i<v; i++) {
distance[i] = inf;
}
distance[src] = 0;
// Relaxation code
for(int i=1; i<=v-1; i++) {
for(int j=0; j<e; j++) {
int src= edge[j].src;
int dest = edge[j].dest;
int weight = edge[j].weight;
// Relaxation check
if (distance[src] != inf and distance[src] + weight < distance[dest]) {
distance[dest] = distance[src] + weight;
}
}
}
// Check for -ve weight cycles
for(int j=0; j<e; j++) {
int src= edge[j].src;
int dest = edge[j].dest;
int weight = edge[j].weight;
// Relaxation check
if (distance[src] != inf and distance[src] + weight < distance[dest]) {
cout<<"Graph has negative weight cycle";
return;
}
}
// Print the distance array
for(int i=0; i<v; i++) {
cout<<i<<" -> "<<distance[i]<<endl;
}
return;
}
};
int main() {
int v, e;
cin>>v>>e;
Graph g(v, e);
for(int i=0; i<e; i++) {
int u, v, w;
cin>>u>>v>>w;
g.addEdge(u, v, w, i);
}
int src= 0;
g.bellmanFord(src);
return 0;
}