forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strongly Connected Component.cpp
75 lines (59 loc) · 1.35 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
63
64
65
66
67
68
69
70
71
72
73
74
int grp = 0;
vector<int> g[N], newg[N], rg[N], todo;
int comp[N], indeg[N], sz[N];
bool vis[N];
set<int> gr[N];
void dfs(int u)
{
vis[u] = 1;
for(auto &it:g[u])
{
if(!vis[it])
dfs(it);
}
todo.push_back(u);
}
void dfs2(int u, int val)
{
comp[u] = val;
sz[val]++;
for(auto &it:rg[u])
{
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);
}
/*Uncomment if SCC Tree is reqd
for(int i = 1; i <= n; i++)
for(auto &it:g[i])
if(comp[i] != comp[it])
gr[i].insert(it);
*/
}
//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
//Problem 4 (Weakly connected component): https://codeforces.com/problemset/problem/505/D