Pagini recente » Cod sursa (job #83020) | Cod sursa (job #834587) | Cod sursa (job #3133128) | Cod sursa (job #1656753) | Cod sursa (job #3225668)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1e5 + 5;
bool viz[NMAX];
int n, m, nrcomp;
vector<int> v[NMAX], rev[NMAX], comp[NMAX];
stack<int> ord;
void dfs (int x)
{
viz[x] = true;
for (auto u : v[x])
if (!viz[u])
dfs(u);
ord.push(x);
}
void dfs2 (int x)
{
comp[nrcomp].push_back(x);
viz[x] = true;
for (auto u : rev[x])
if (!viz[u])
dfs2(u);
}
signed main ()
{
freopen("ctc.in", "r", stdin);
freopen("ctc.out", "w", stdout);
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> m;
while (m--)
{
int x, y; cin >> x >> y;
v[x].push_back(y);
rev[y].push_back(x);
}
for (int i = 1; i <= n; i++)
if (!viz[i])
dfs(i);
memset(viz, false, sizeof(viz));
while (ord.size())
{
int x = ord.top();
ord.pop();
if (viz[x])
continue;
++nrcomp;
dfs2(x);
}
cout << nrcomp << '\n';
for (int i = 1; i <= nrcomp; i++, cout << '\n')
for (auto x : comp[i])
cout << x << ' ';
}