-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNegativeWeightCycle.cpp
53 lines (49 loc) · 999 Bytes
/
NegativeWeightCycle.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
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int isNegativeWeightCycle(int n, vector<vector<int>>edges) {
vector<int> dist(n, INT_MAX);
dist[0] = 0;
for (int i = 0; i < n - 1; i++) {
for (auto ele : edges) {
int u = ele[0];
int v = ele[1];
int wt = ele[2];
if (dist[u] != INT_MAX && dist[u] + wt < dist[v]) {
dist[v] = dist[u] + wt;
}
}
}
for (auto ele : edges) {
int u = ele[0];
int v = ele[1];
int wt = ele[2];
if (dist[u] != INT_MAX && dist[u] + wt < dist[v]) {
return 1;
}
}
return 0;
}
};
// { Driver Code Starts.
int main() {
int tc;
cin >> tc;
while (tc--) {
int n, m;
cin >> n >> m;
vector<vector<int>>edges;
for (int i = 0; i < m; i++) {
int x, y, z;
cin >> x >> y >> z;
edges.push_back({x, y, z});
}
Solution obj;
int ans = obj.isNegativeWeightCycle(n, edges);
cout << ans << "\n";
}
return 0;
} // } Driver Code Ends