Cod sursa(job #416909)

Utilizator ooctavTuchila Octavian ooctav Data 13 martie 2010 17:39:32
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#define in "ctc.in"
#define out "ctc.out"
#define NMAX 100001
using namespace std;
int N;
vector<int> A[NMAX];
vector<int> AT[NMAX];
int postord[NMAX], viz[NMAX];
int NR = 0;
int LIN = 0;
vector<int> COM[NMAX];


void citire()
{
	int M, x, y;
	scanf("%d%d",&N, &M);
	
	for(int i = 1 ; i <= M ; i++)
	{
		scanf("%d%d",&x,&y);
		
		A[x].push_back(y);
		AT[y].push_back(x);
	}
}

void DFS(int x)
{
	viz[x] = 1;
	for(int i = 0 ; i < A[x].size() ; i++)
		if(!viz[A[x][i]])
			DFS(A[x][i]);
	postord[++NR] = x;
}

void DFST(int x)
{
	viz[x] = 0;
	COM[LIN].push_back(x);
	for(int i = 0 ; i < AT[x].size() ; i++)
		if(viz[AT[x][i]])
			DFST(AT[x][i]);
}

void scrie()
{
	printf("%d\n",LIN);
	for(int i = 1 ; i <= LIN ; i++)
	{
		for(int j = 0 ; j < COM[i].size() ; j++)
			printf("%d ",COM[i][j]);
		printf("\n");
	}
}

int main()
{
	freopen(in,"r",stdin);
	freopen(out,"w",stdout);
	citire();
	for(int i = 1 ; i <= N ; i++)
		if(!viz[i])
			DFS(i);
		
	for(int i = N ; i ; i--)
	{
		LIN++;
		DFST(postord[i]);
		if(COM[LIN].size() == 1)
		{
			COM[LIN].pop_back();
			LIN--;
		}
	}
	scrie();
	
	return 0;
}