forked from anishpatil31/CP-Templates-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStrongly Connected Components and Condensation Graph.cpp
98 lines (78 loc) · 1.62 KB
/
Strongly Connected Components and Condensation 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
// Code for finding strongly connected components and building condensation graph.
// Time Complexity - O(n + m) where n is the number of vertices and m is the number of edges in the graph.
vi adj[LIM], adjReverse[LIM], adjSCC[LIM], order, component, rootNodes;
int root[LIM];
bool visited[LIM];
void dfs1(int u)
{
visited[u] = true;
for(int x : adj[u])
{
if(!visited[x])
dfs1(x);
}
order.push_back(u);
}
void dfs2(int u)
{
visited[u] = true;
component.pb(u);
for(int x : adjReverse[u])
{
if(!visited[x])
dfs2(x);
}
}
void findSCC()
{
for(int i=0; i<LIM; i++)
{
visited[i] = false;
adj[i].clear();
adjReverse[i].clear();
adjSCC[i].clear();
}
order.clear();
component.clear();
rootNodes.clear();
int n, m;
cin >> n >> m;
for(int i=0; i<m; i++)
{
int u, v;
cin >> u >> v;
adj[u].pb(v);
adjReverse[v].pb(u);
}
for(int i=1; i<=n; i++)
{
if(!visited[i])
dfs1(i);
}
for(int i=0; i<LIM; i++)
visited[i] = false;
Rev(order);
for(auto x : order)
{
if(!visited[x])
{
component.clear();
dfs2(x);
int r = component[0];
rootNodes.pb(r);
for(auto x : component)
{
root[x] = r;
}
}
}
for(int i=1; i<=n; i++)
{
for(auto x : adj[i])
{
int r1 = root[i], r2 = root[x];
if(r1 != r2)
adjSCC[r1].pb(r2);
}
}
}