-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSCC.cpp
More file actions
69 lines (52 loc) · 1.41 KB
/
SCC.cpp
File metadata and controls
69 lines (52 loc) · 1.41 KB
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
/*
-> Kosaraju's algorithm to find SCCs
-> A directed graph is strongly connected if there is a directed path from any vertex to every other vertex.
-> Similar to connected components, a directed graph can be broken down into Strongly Connected Components.
-> ref:
1. https://www.hackerearth.com/practice/algorithms/graphs/strongly-connected-components/tutorial/
2. https://cp-algorithms.com/graph/strongly-connected-components.html
*/
vector<int> adj[N], rev_adj[N];
bool vis[N];
stack<int> stk;
vector<int> component;
void dfs1(int x) {
vis[x] = true;
for (auto c : adj[x]) {
if (!vis[c])
dfs1(c);
}
stk.push(x);
}
void dfs2(int x) {
vis[x] = true;
component.pb(x);
for (auto c : rev_adj[x]) {
if (!vis[c])
dfs2(c);
}
}
void transpose(int n) {
for (int x = 1; x <= n; ++x) {
for (auto u : adj[x])
rev_adj[u].pb(x);
}
}
void findSCC(int n) {
for (int i = 1; i <= n; ++i) {
if (!vis[i])
dfs1(i);
}
transpose(n);
for (int i = 1; i <= n; ++i)
vis[i] = false;
while (!stk.empty()) {
int x = stk.top();
stk.pop();
if (vis[x])
continue;
component.clear();
dfs2(x);
// vertices in current SCC stored in component[]
}
}