-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBellman-Ford.cpp
More file actions
72 lines (66 loc) · 1.18 KB
/
Bellman-Ford.cpp
File metadata and controls
72 lines (66 loc) · 1.18 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
//complexity: O(E*V)
#include <iostream>
#include <vector>
using namespace std;
#define MAX 105
const int INF = 1e9;
struct Edge
{
int source;
int target;
int weight;
};
vector<int> dist(MAX, INF);
vector<Edge>graph;
int n, m;
int path[MAX];
bool BellmanFord(int s)
{
int u, v, w;
dist[s] = 0;
for(int i=1;i<=n-1;i++)
for (int j = 0; j < m; j++)
{
u = graph[j].source;
v = graph[j].target;
w = graph[j].weight;
if (dist[u] != INF && (dist[u] + w < dist[v]))
{
dist[v] = dist[u] + w;
path[v] = u;
}
}
for (int i = 0; i < m; i++)
{
u = graph[i].source;
v = graph[i].target;
w = graph[i].weight;
if (dist[u] != INF && (dist[u] + w < dist[v]))
{
return false;
}
}
return true;
}
int main()
{
int s, t, u, v, w;
cin >> n >> m;
dist = vector<int>(n, INF);
for (int i = 0; i < m; i++)
{
Edge temp;
cin >> u >> v >> w;
temp.source = u;
temp.target = v;
temp.weight = w;
graph.push_back(temp);
}
s = 0; t = 4;
bool res = BellmanFord(s);
if (res == false)
cout << "Graph contains negative weight cycle" << endl;
else
cout << dist[t] << endl;
return 0;
}