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
| int n, m, comp[N];
vi g[N], rg[N];
bool vis[N];
vi s;
void dfs(int u) {
vis[u] = true;
for (auto v : g[u])
if (!vis[v]) dfs(v);
s.push_back(u);
}
void rdfs(int u, int k) {
comp[u] = k;
for (auto v : rg[u])
if (!comp[v]) rdfs(v, k);
}
void kosaraju() {
for (int i = 1; i <= n; i++)
if (!vis[i]) dfs(i);
int cnt = 0;
for (int i = s.size() - 1; i >= 0; i--)
if (!comp[s[i]]) rdfs(s[i], ++cnt);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data/in.txt", "r", stdin);
freopen("data/out.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
rg[v].push_back(u);
}
kosaraju();
for (int i = 1; i <= n; i++) cout << comp[i] << " ";
return 0;
}
|