-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCycle_in_Directed_graph.cpp
138 lines (118 loc) · 2.17 KB
/
Cycle_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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
maneesh(maik)
*/
// Cycles in Directed graph using DFS
// Four types of edges in DFS tree
// 1. Tree edges, 2. Forward edges, 3. Backward edges, 4. Cross edges
//**** If any back edges exist then it must form a cycle****
// in Back edges for any edge (u-->v)
// Interval [Pre(v),Post(v)] contains [Pre(u),Post(u)].
// in Forward and tree edges for any edge (u-->v)
// Interval [Pre(u),Post(u)] contains [Pre(v),Post(v)]
// in Cross edges for any edge (u-->v)
// Interval [Pre(u),Post(u)] and [Pre(v),Post(v)] are Disjoint
#include<iostream>
#include<algorithm>
#include<string>
#include<bitset>
#include<deque>
#include<iterator>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<vector>
using namespace std;
#define ll long long int
#define pb push_back
#define pf push_front
#define M 1000000007
vector<ll>G[1000000];
ll cnt=0;
struct data
{
ll u,v;
};
void DFS(ll s, ll vis[], ll start[], ll end[])
{
vis[s]=1;
for(ll i=0; i<G[s].size(); i++)
{
ll it=G[s][i];
if(vis[it]==0)
{
start[it]=cnt; cnt++;
DFS(it, vis, start, end);
}
}
end[s]=cnt; cnt++;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n,m;
cin>>n>>m;
ll start[n+1],end[n+1];
ll i,x,y;
vector<data>edge;
data z;
for(i=0; i<m; i++)
{
cin>>x>>y;
z.u=x; z.v=y;
edge.pb(z);
G[x].pb(y);
}
/* for(i=1; i<=n; i++)
{
cout<<i<<"-->";
for(ll j=0; j<G[i].size(); j++)
{
cout<<G[i][j]<<" ";
}
cout<<endl;
} */
ll vis[n+1];
for(i=1; i<=n; i++)
{
vis[i]=0;
}
cnt=0;
for(i=1; i<=n; i++)
{
if(vis[i]==0)
{
start[i]=cnt; cnt++;
DFS(i, vis, start, end);
}
}
// pre(start) and post(end) time of DFS
for(i=1; i<=n; i++)
cout<<start[i]<<" ";
cout<<endl;
for(i=1; i<=n; i++)
cout<<end[i]<<" ";
cout<<"\n\n";
ll flag=0,tx1,tx2,ty1,ty2;
for(i=0; i<m; i++)
{
x=edge[i].u; y=edge[i].v;
tx1=start[x]; ty1=start[y];
tx2=end[x]; ty2=end[y];
// check back edges
if(ty1<tx1 && ty2>tx2)
{
flag=1;
break;
}
}
if(flag==0)
cout<<"NO cycle in the graph"<<endl;
else
cout<<"Cycle exist in the graph"<<endl;
return 0;
}