-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStronglyConnectedComponent.cpp
More file actions
69 lines (67 loc) · 1.89 KB
/
StronglyConnectedComponent.cpp
File metadata and controls
69 lines (67 loc) · 1.89 KB
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
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
struct StronglyConnectedComponent {
int n;
vector<bool> used;
vector<int> order, cmp;
vector<vector<int>> g, rg;
StronglyConnectedComponent(int x) {
n = x;
g.resize(x);
rg.resize(x);
used.resize(x);
cmp.resize(x);
}
void add_edge(int from, int to) {
g[from].push_back(to);
rg[to].push_back(from);
}
void dfs(int u) {
used[u] = true;
for (auto v : g[u]) if (!used[v]) {
dfs(v);
}
order.push_back(u);
}
void rdfs(int u, int k) {
used[u] = true;
cmp[u] = k;
for (auto v : rg[u]) if (!used[v]) {
rdfs(v, k);
}
}
int init() {
used.assign(n, false);
for (int u = 0; u < n; u ++) {
if (!used[u]) {
dfs(u);
}
}
used.assign(n, false);
int k = 0;
for (int i = order.size() - 1; i >= 0; i --) {
if (!used[order[i]]) {
rdfs(order[i], k ++);
}
}
return k;
}
};
int main() {
int n, m;
scanf("%d %d", &n, &m);
StronglyConnectedComponent scc(n);
for (int i = 0; i < m; i ++) {
int a, b;
scanf("%d %d", &a, &b);
a --, b --;
scc.add_edge(a, b);
}
scc.init();
for (int i = 0; i < n; i ++) {
cerr << scc.cmp[i] << endl;
}
return 0;
}