-
Notifications
You must be signed in to change notification settings - Fork 0
/
Negative Cycles in Directed Graph.cpp
101 lines (89 loc) · 1.69 KB
/
Negative Cycles in Directed Graph.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
100
101
SPFA:
int n, m;
int dist[N], cnt[N];
bool inqueue[N];
vector<pair<int, int> > g[N];
bool negativeCycle() //Returns true if there is a negative cycle
{
queue<int> q;
for(int i=1;i<=n;i++)
{
dist[i]=cnt[i]=0;
q.push(i), inqueue[i]=true;
}
while(!q.empty())
{
int v=q.front();
q.pop();
inqueue[v]=false;
for(auto &edge:g[v])
{
int to=edge.first;
int w=edge.second;
if(dist[v] + w < dist[to])
{
dist[to] = dist[v] + w;
dist[to] = max(dist[to], INF);
if(!inqueue[to])
{
q.push(to);
inqueue[to]=true;
cnt[to]++;
if(cnt[to]>n)
return true;
}
}
}
}
return false;
}
-----------------------------------------------------------------------------------------------------------------------------------------
Bellman Ford (with Path Printing of the negative cycle):
const int INF=1e9;
struct Edge
{
int u, v, cost;
};
int n, m;
vector<Edge> edges;
bool negativeCycle() //Return true if there is a negative cycle in the graph
{
vector<int> dist(n+1, 0);
vector<int> par(n, -1);
int x;
for(int i=1;i<=n;i++)
{
x=-1;
for(auto &e:edges)
{
if(dist[e.u] + e.cost < dist[e.v])
{
dist[e.v] = dist[e.u] + e.cost;
par[e.v] = e.u;
x = e.v;
}
}
}
if(x==-1)
return 0;
else
{
for(int i=1;i<=n;i++)
x=par[x];
vector<int> cycle;
for(int v=x;;v=par[v])
{
cycle.push_back(v);
if(v==x && cycle.size()>1)
break;
}
reverse(cycle.begin(), cycle.end());
cout<<"Negative cycle: ";
for(auto &it:cycle)
cout<<it<<" ";
cout<<endl;
return 1;
}
}
//Question 1: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2031
//Solution 1: http://p.ip.fi/muBP