Pagini recente » Cod sursa (job #2518215) | Cod sursa (job #2060125) | Cod sursa (job #3214117) | Cod sursa (job #2138723) | Cod sursa (job #1558227)
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int dmax = 100000;
const int dim = 200000;
struct MUCHIE
{
int a, b;
};
MUCHIE m[dim + 1];
int inc[dmax + 1];
int viz[dmax + 1];
int post_ord[dmax + 1];
int nr;
int N,M;
int NR;
void DFS(int x)
{
viz[x] = true;
//PARCURG LISTA VECINILOR LUI x
for(int i = inc[x]; m[i].a == x; i++)
if(!viz[ m[i].b ]) DFS( m[i].b );
post_ord[++nr] = x;
}
void DFST(int x)
{
viz[x] = true;
//PARCURG LISTA VECINILOR LUI x
for(int i = inc[x]; m[i].a == x; i++)
if(!viz[ m[i].b ]) DFST( m[i].b );
}
void DFS_T(int x)
{
viz[x] = true;
printf("%d ", x);
//PARCURG LISTA VECINILOR LUI x
for(int i = inc[x]; m[i].a == x; i++)
if(!viz[ m[i].b ]) DFS_T( m[i].b );
}
bool exc(MUCHIE e1, MUCHIE e2)
{
if(e1.a == e2.a) return e1.b < e2.b;
else
return e1.a < e2.a;
}
int main()
{
freopen("ctc.in", "r", stdin);
freopen("ctc.out", "w", stdout);
int i, x, y;
scanf("%d %d", &N, &M);
for(i = 1; i <= M; i++)
{
scanf("%d %d", &x, &y);
//GRAF ORIENTAT
m[i].a = x;
m[i].b = y;
}
sort(m+1, m+M+1, exc);
inc[ m[1].a ] = 1;
for(i = 2; i <= M; i++)
if(m[i].a != m[i-1].a)
inc[ m[i].a ] = i;
for(i = 1; i <= N; i++)
if(!viz[i]) DFS(i);
//DETERMINAM GRAFUL TRANSPUS
for(i = 1; i <= M; i++) swap(m[i].a, m[i].b);
sort(m+1, m+M+1, exc);
inc[ m[1].a ] = 1;
for(i = 2; i <= M; i++)
if(m[i].a != m[i-1].a)
inc[ m[i].a ] = i;
for(i = 1; i <= N; i++) viz[i] = false;
for(i = N; i >= 1; i--)
if(!viz[ post_ord[i] ])
{
NR++;
DFST( post_ord[i] );
}
printf("%d\n", NR);
for(i = 1; i <= N; i++) viz[i] = false;
for(i = N; i >= 1; i--)
if(!viz[ post_ord[i] ])
{
DFS_T( post_ord[i] );
printf("\n");
}
return 0;
}