-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_BellmanFord_NegativeCycle.cpp
99 lines (80 loc) · 2.34 KB
/
GFG_BellmanFord_NegativeCycle.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
/*
Negative weight cycle
https://practice.geeksforgeeks.org/problems/negative-weight-cycle3504/1
Distance from the Source (Bellman-Ford Algorithm)
https://practice.geeksforgeeks.org/problems/distance-from-the-source-bellman-ford-algorithm/1/
*/
// Negative Cycle
// } Driver Code Ends
class Solution {
public:
int isNegativeWeightCycle(int n, vector<vector<int>>edges){
// Code here
const int INF = 1e8;
vector<int> dist (n, INF);
bool negativeCycle = false;
dist[0]=0;
int u,v,dt;
for(int i=1; i<=n-1; i++)
{
for(auto x: edges)
{
u = x[0];
v = x[1];
dt = x[2];
if(dist[u]+dt < dist[v]) // dist[u] != INT_MAX &&
dist[v] = dist[u] + dt;
}
}
// Run for last iteration to check if it contains negative cycle or not
for(auto x: edges)
{
u = x[0];
v = x[1];
dt = x[2];
if(dist[u]+dt < dist[v])
{
negativeCycle= true;
break;
}
}
return negativeCycle;
}
};
// Distance
class Solution{
public:
/* Function to implement Dijkstra
* adj: 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>> adj, int S) {
const int INF = 1e8;
vector<int> dist (V, INF);
bool negativeCycle = false;
dist[S]=0;
int u,v,dt;
for(int i=1; i<=V-1; i++)
{
for(auto x: adj)
{
u = x[0];
v = x[1];
dt = x[2];
if(dist[u] != INT_MAX && dist[u]+dt < dist[v])
dist[v] = dist[u] + dt;
}
}
// Run for last iteration to check if it contains negative cycle or not
for(auto x: adj)
{
u = x[0];
v = x[1];
dt = x[2];
if(dist[u]+dt < dist[v])
negativeCycle= true;
}
return dist;
}//end
};