Pagini recente » Cod sursa (job #2584646) | Cod sursa (job #501409) | Cod sursa (job #3277267) | Cod sursa (job #984099) | Cod sursa (job #2314342)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
const int NMAX=100005;
stack <int> S,S2;
vector <int> v[NMAX],v2[NMAX];
int viz[NMAX],viz2[NMAX];
int n,m;
int nr;
void read()
{
int i,x,y;
fin>>n>>m;
for(i=1;i<=m;++i)
{
fin>>x>>y;
v[x].push_back(y);
v2[y].push_back(x);
}
fin.close();
}
void DFS(int x)
{
int w;
viz[x]=1;
for(int i=0;i<v[x].size();++i)
{
w=v[x][i];
if(viz[w]==0) DFS(w);
}
S.push(x);
S2.push(x);
}
void nebunie()
{
for(int i=1;i<=n;++i)
{
if(viz[i]==0) DFS(i);
}
}
void DFS2(int u, int mama)
{
int w;
viz2[u]=1;
if(mama==1) fout<<u<<" ";
for(int i=0;i<v2[u].size();++i)
{
w=v2[u][i];
if(viz2[w]==0) DFS2(w,mama);
}
}
void stesh()
{
int top;
while(S.size()>0)
{
top=S.top(); S.pop();
if(viz2[top]==0) {DFS2(top,0); nr++;}
}
for(int i=1;i<=n;++i) viz2[i]=0;
fout<<nr<<" ";
while(S2.size()>0)
{
top=S2.top(); S2.pop();
if(viz2[top]==0) {fout<<"\n"; DFS2(top,1);}
}
}
int main()
{
read();
nebunie();
stesh();
return 0;
}