Pagini recente » Cod sursa (job #1979638) | Cod sursa (job #2484844) | Cod sursa (job #1142314) | Profil MocanVlad | Cod sursa (job #1648874)
#include <stdio.h>
#include <iostream>
#include <vector>
#include <stack>
#include <string.h>
using namespace std;
const int N = 100001;
stack <int> st;
vector<int> g[N],gt[N],sol[N];
int n,m,nrsol;
bool viz[N];
void dfs(int x)
{
int i;
viz[x]=1;
for(i=0;i<g[x].size();i++)
if(!viz[g[x][i]])
dfs(g[x][i]);
st.push(x);
}
void dfst(int x)
{
int i;
viz[x]=1;
for(i=0;i<gt[x].size();i++)
if(!viz[gt[x][i]])
dfst(gt[x][i]);
sol[nrsol].push_back(x);
}
int main()
{
freopen("ctc.in","r",stdin);
freopen("ctc.out","w",stdout);
int i,x,y,j,nod;
scanf("%d %d",&n,&m);
for(i=1;i<=m;i++)
{
scanf("%d %d",&x,&y);
g[x].push_back(y);
gt[y].push_back(x);
}
for(i=1;i<=n;i++)
if(!viz[i])
dfs(i);
memset(viz,0,sizeof viz);
while(!st.empty())
{
nod=st.top();
st.pop();
if(!viz[nod])
{
nrsol++;
dfst(nod);
}
}
printf("%d\n",nrsol);
for(i=1;i<=nrsol;i++)
{
for(j=0;j<sol[i].size();j++)
printf("%d ",sol[i][j]);
printf("\n");
}
return 0;
}