-
Notifications
You must be signed in to change notification settings - Fork 0
/
Strongly Connected Components.cpp
70 lines (62 loc) · 1.09 KB
/
Strongly Connected Components.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
/*
input:
5 5
1 0
0 2
2 1
0 3
3 4
output:
graph 1: 0 1 2
graph 2: 3
graph 3: 4
*/
#include <bits/stdc++.h>
using namespace std;
const int mx = 1e5+7;
vector<int> adj[mx], rev_adj[mx];
vector<int> q;
bool visit[mx];
int start_t[mx], end_t[mx];
int tc = 0;
int n, e;
int x = 0;
void dfs(int u) {
if (visit[u]) return;
visit[u] = 1;
start_t[u] = ++tc;
for (auto v: adj[u] ) {
dfs(v);
}
end_t[u] = ++tc;
q.push_back(u);
}
void dfs2(int u) {
if (!visit[u]) return;
visit[u] = false;
cout << u << " ";
for (auto v:rev_adj[u]) {
dfs2(v);
}
}
int main() {
//freopen( "in.txt", "r", stdin );
//freopen( "out.txt", "w", stdout);
cin >> n >> e;
for (int i = 0; i<e; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
rev_adj[v].push_back(u);
}
for (int i = 0; i<n; i++) dfs(i);
for (int i = q.size()-1; i>=0; i--) {
int u = q[i];
if (visit[u]) {
cout << "graph " << ++x << ": ";
dfs2(u);
cout << endl;
}
}
return 0;
}