-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bellman_ford.cpp
76 lines (65 loc) · 1.67 KB
/
Bellman_ford.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
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;
}
}
}
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;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N, m;
cin >> N >> m;
vector<vector<int>> edges;
for (int i = 0; i < m; ++i) {
vector<int> temp;
for (int j = 0; j < 3; ++j) {
int x;
cin >> x;
temp.push_back(x);
}
edges.push_back(temp);
}
int src;
cin >> src;
Solution obj;
vector<int> res = obj.bellman_ford(N, edges, src);
for (auto x : res) {
cout << x << " ";
}
cout << "\n";
}
return 0;
}
// } Driver Code Ends