forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strongly Connected Component.cpp
62 lines (52 loc) · 1.08 KB
/
Strongly Connected Component.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
vector<int> g[N], newg[N], rg[N], todo;
int comp[N], indeg[N];
bool vis[N];
vector<int> gr[N];
void dfs(int k)
{
vis[k]=1;
for(auto it:g[k])
{
if(!vis[it])
dfs(it);
}
todo.push_back(k);
}
void dfs2(int k, int val)
{
comp[k]=val;
for(auto it:rg[k])
{
if(comp[it]==-1)
dfs2(it, val);
}
}
void sccAddEdge(int from, int to)
{
g[from].push_back(to);
rg[to].push_back(from);
}
void scc()
{
for(int i=1;i<=n;i++)
comp[i]=-1;
for(int i=1;i<=n;i++)
{
if(!vis[i])
dfs(i);
}
reverse(todo.begin(), todo.end());
for(auto it:todo)
{
if(comp[it]==-1)
{
dfs2(it, ++grp);
}
}
}
//Sample Problem 1 (SCC Compression): http://codeforces.com/contest/999/problem/E
//Sample Solution 1: http://codeforces.com/contest/999/submission/39489910
//Sample Problem 2 (Detection of Directed Cycle in a connected component): http://codeforces.com/contest/505/problem/D
//Sample Solution 2: http://codeforces.com/contest/505/submission/39885530
//Sample Problem 3: https://codeforces.com/contest/118/problem/E
//Sample Solution 3: https://codeforces.com/contest/118/submission/39888563