-
Notifications
You must be signed in to change notification settings - Fork 0
/
kosaraju.cpp
91 lines (71 loc) · 1.72 KB
/
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
// BOJ 2150 Strongly Connected Component
#include <bits/stdc++.h>
#define sz size()
#define bk back()
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
void dfs1(int cur, vector<int> &v, vector<bool> &vst, vector<vector<int>> &graph) {
for (int nxt : graph[cur]) {
if (!vst[nxt]) {
vst[nxt] = true;
dfs1(nxt, v, vst, graph);
}
}
v.push_back(cur);
}
void dfs2(int cur, vector<int> &w, vector<bool> &vst, vector<vector<int>> &reversed) {
for (int nxt : reversed[cur]) {
if (!vst[nxt]) {
vst[nxt] = true;
dfs2(nxt, w, vst, reversed);
}
}
w.push_back(cur);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
vector<vector<int>> graph(n + 1), reversed(n + 1);
while (m--) {
int x, y;
cin >> x >> y;
graph[x].push_back(y);
reversed[y].push_back(x);
}
vector<int> v;
vector<bool> vst(n + 1);
for (int i = 1; i <= n; i++) {
if (!vst[i]) {
vst[i] = true;
dfs1(i, v, vst, graph);
}
}
vector<int> w;
vector<vector<int>> scc;
fill(vst.begin(), vst.end(), false);
while (v.sz) {
int i = v.bk;
v.pop_back();
if (!vst[i]) {
vst[i] = true;
w.clear();
dfs2(i, w, vst, reversed);
scc.push_back(w);
}
}
for (auto &w : scc)
sort(w.begin(), w.end());
sort(scc.begin(), scc.end());
cout << scc.sz << '\n';
for (auto &w : scc) {
for (int x : w)
cout << x << ' ';
cout << -1 << '\n';
}
}