Pagini recente » Cod sursa (job #1085106) | Cod sursa (job #2703384) | Cod sursa (job #1780302) | Cod sursa (job #1196498) | Cod sursa (job #2869932)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, viz[100005], nrcc, st[100005], top;
vector <int> h[100005], g[100005], ctc[100005];
void Citire()
{
int m, x, y;
fin >> n >> m;
while (m--)
{
fin >> x >> y;
h[x].push_back(y);
g[y].push_back(x);
}
fin.close();
}
void Afisare()
{
fout << nrcc << "\n";
for (int i = 1; i <= nrcc; i++)
{
for (int w : ctc[i])
fout << w << " ";
fout << "\n";
}
fout.close();
}
void DFS(int k)
{
viz[k] = 1;
for (int w : h[k])
if (!viz[w]) DFS(w);
st[++top] = k;
}
void DFS_g(int k)
{
viz[k] = 0;
for (int w : g[k])
if (viz[w]) DFS_g(w);
ctc[nrcc].push_back(k);
}
void SortTop()
{
for (int i = 1; i <= n; i++)
if (!viz[i]) DFS(i);
}
void ConstrCTC()
{
SortTop();
for (int i = n; i > 0; i--)
if (viz[st[i]])
{
nrcc++;
DFS_g(st[i]);
}
}
int main()
{
Citire();
ConstrCTC();
Afisare();
return 0;
}