Pagini recente » Cod sursa (job #971724) | Cod sursa (job #265559) | Cod sursa (job #2711713) | Cod sursa (job #1266268) | Cod sursa (job #2147750)
#include <bits/stdc++.h>
using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
vector < int > v[100005], vv[100005];
stack < int > s;
bool viz[100005];
int n,m,k;
void read()
{
in >> n >> m;
int a,b;
for(int i=1; i<=m; i++)
{
in >> a >> b;
v[a].push_back(b);
vv[b].push_back(a);
}
}
void topsort( int head)
{
viz[head] = 1;
for(int i=0; i<v[head].size(); i++)
if( !viz[ v[head][i] ] ) topsort( v[head][i] );
s.push(head);
}
void dfs( int head )
{
viz[head] = 0;
v[k].push_back(head);
for(int i=0; i<vv[head].size(); i++)
if( viz[ vv[head][i]] ) dfs( vv[head][i]);
}
int main()
{
read();
for(int i=1; i<=n; i++)
if( !viz[i]) topsort(i);
for(int i=1; i<=n; i++) v[i].clear();
while( !s.empty() )
{
int head = s.top();
s.pop();
if( viz[head] ) k++, dfs(head);
}
out << k << '\n';
for(int i=1; i<=k; i++)
{
for(int j=0; j<v[i].size(); j++)
out << v[i][j] << ' ';
out << '\n';
}
return 0;
}