Pagini recente » Clasament alexei_lr1 | Istoria paginii runda/amigoodenoughforojigim | Arhiva de probleme | Istoria paginii runda/preoji-10 | Cod sursa (job #2247707)
#include <bits/stdc++.h>
using namespace std;
const int kNmax = 1e5+5;
int n, m;
vector<int> g[kNmax];
int lowlink[kNmax];
int self[kNmax];
vector<int> cc[kNmax];
int cc_of_node[kNmax];
int cnt = 1;
int current = 1;
int seen[kNmax];
vector<int> seen_stack;
void tarjan(int x) {
lowlink[x] = self[x] = current;
seen[x] = true;
seen_stack.push_back(x);
current++;
for (int y : g[x]) {
if (!self[y]) {
tarjan(y);
lowlink[x] = min(lowlink[x], lowlink[y]);
} else if (seen[y]) lowlink[x] = min(lowlink[x], lowlink[y]);
}
if (self[x] == lowlink[x]) {
int node;
do {
node = seen_stack.back();
cc_of_node[node] = cnt;
cc[cnt].push_back(node);
seen_stack.pop_back();
seen[node] = false;
} while (node != x);
cnt++;
}
}
int main() {
#ifdef INFOARENA
freopen("ctc.in", "r", stdin);
freopen("ctc.out", "w", stdout);
#endif
cin >> n >> m;
for (int x, y, i = 1; i <= m; i++) {
cin >> x >> y;
g[x].push_back(y);
}
for (int i = 1; i <= n; i++) {
if (self[i]) continue;
tarjan(i);
}
--cnt;
cout << cnt << '\n';
for (int i = 1; i <= cnt; i++) {
for (int node : cc[i])
cout << node << ' ';
cout << '\n';
}
return 0;
}