-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSCC kosaraju.cpp
94 lines (79 loc) · 2.05 KB
/
SCC kosaraju.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
#include <bits/stdc++.h>
using namespace std;
#define pb(x) push_back(x)
#define MAXN 100005
// graph and it's trandpose:
vector<vector<int> >adj, rdj;
// nodes[x] is a list of nodes that belong to scc x:
vector<vector<int> >nodes;
// the adjList of the result SCC DAG:
vector<set<int> > sccAdj;
// dfs visited:
int v[MAXN];
// comp[x] is the number of SCC that node x belong to:
int comp[MAXN];
// ncmp is the total number of scc:
int ncmp;
int n, m;
stack<int> s;
void dfs1( int x ) {
v[x] = 1;
for( int i = 0; i < adj[x].size(); ++i ) {
int nx = adj[x][i];
if( !v[nx] ) dfs1( nx );
}
s.push( x );
}
void rdfs( int x, int cmp ) {
comp[x] = cmp;
nodes[cmp].pb( x );
v[x] = 1;
for( int i = 0; i < rdj[x].size(); ++i ) {
int nx = rdj[x][i];
if( !v[nx] ) {
rdfs( nx, cmp );
} else if( comp[nx] != comp[x] ) {
sccAdj[comp[nx]].insert( comp[x] );
}
}
}
int main() {
int T;
scanf( "%d", &T );
for( int tc = 1; tc <= T; ++tc ) {
scanf( "%d%d", &n, &m );
// clear the global variables:
adj.assign( n + 1, vector<int>() );
rdj.assign( n + 1, vector<int>() );
sccAdj.clear();
nodes.clear();
memset( v, 0, sizeof v );
ncmp = 0;
// read the graph:
for( int i = 1; i <= m; ++i ) {
int a, b;
scanf( "%d%d", &a, &b );
adj[a].pb( b );
rdj[b].pb( a );
}
// do the first dfs:
for( int i = 1; i <= n; ++i ) {
if( !v[i] ) {
dfs1( i );
}
}
// do the second dfs to find the SCCs:
memset( v, 0, sizeof v );
while( !s.empty() ) {
int x = s.top();
s.pop();
if( !v[x] ) {
// printf( "component #%d:\n", ncmp + 1 );
sccAdj.push_back( set<int>() );
nodes.push_back( vector<int>() );
rdfs( x, ncmp++ );
}
}
}
return 0;
}