-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbellman ford(TFU).cpp
70 lines (62 loc) · 1.57 KB
/
bellman ford(TFU).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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
/* Function to implement Bellman Ford
* edges: vector of vectors which represents the graph
* S: source vertex to start traversing graph with
* V: number of vertices
*/
vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S)
{
vector<int> dist(V, 1e8);
dist[S] = 0;
for (int i = 0; i < V - 1; i++)
{
for (auto it : edges)
{
int u = it[0];
int v = it[1];
int wt = it[2];
if (dist[u] != 1e8 && dist[u] + wt < dist[v])
{
dist[v] = dist[u] + wt;
}
}
}
// Nth relaxation to check negative cycle
for (auto it : edges)
{
int u = it[0];
int v = it[1];
int wt = it[2];
if (dist[u] != 1e8 && dist[u] + wt < dist[v])
{
return { -1};
}
}
return dist;
}
};
int main()
{
int V = 6;
vector<vector<int>> edges(7, vector<int>(3));
edges[0] = {3, 2, 6};
edges[1] = {5, 3, 1};
edges[2] = {0, 1, 5};
edges[3] = {1, 5, -3};
edges[4] = {1, 2, -2};
edges[5] = {3, 4, -2};
edges[6] = {2, 4, 3};
int S = 0;
Solution obj;
vector<int> dist = obj.bellman_ford(V, edges, S);
for (auto d : dist)
{
cout << d << " ";
}
cout << endl;
return 0;
}