Cod sursa(job #959918)

Utilizator lucky1992Ion Ion lucky1992 Data 9 iunie 2013 13:31:31
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <stack>
#include <fstream>
#include <iostream>

#define NMAX 100005

using namespace std;

int N,M,x,y, timp = 0, t = -1;
vector<int> neigh[NMAX];
vector<int> idx( NMAX, -1);
vector<int> b( NMAX, -1);
vector<int> inStack( NMAX, 0 );
vector<int> components[NMAX];
stack<int> s;

void explorare( int i ){
	
		timp++;
		idx[i] = timp;
		b[i] = timp;
		s.push(i);
		inStack[i] = 1;
		
		for( unsigned k = 0; k < neigh[i].size(); k++ ){
			if( idx[ neigh[i][k] ] == -1 ){ // nu a mai fost vizitat
				explorare( neigh[i][k] );
				if( b[i] > b[ neigh[i][k] ] )
					b[i] = b[ neigh[i][k] ]; // extrag minimul dintre low[i] si low[neigh[i][k]]
			}
			else{
				if( inStack[neigh[i][k]] == 1 ) // daca a fost vizitat si nodul e si in stiva
					b[i] = ( b[i] > idx[ neigh[i][k] ] ? idx[neigh[i][k]] : b[i] ); // iau min dintre idx[neigh[i][k]] si b[i]
					
			}
		}
		
		if( idx[i] == b[i] ){
			int nod;
			++t;
			do{
				nod = s.top();
				components[t].push_back( nod );
				s.pop();
				inStack[nod] = 0;
			}while( nod != i );
		}
}

void dfs(){
	
		for( int i = 1; i <= N; i++ )
			if( idx[i] == -1 ){ // nu a fost vizitat
				explorare( i );
			}
}




int main(){
	
		freopen("ctc.in", "r", stdin );
		freopen("ctc.out", "w", stdout );

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

		dfs();
		printf("%d\n", t+1);
		for( int i = 0; i <= t; i++){
			for( unsigned k = 0; k < components[i].size(); k++ )
				printf("%d ", components[i][k]);
			printf("\n");
		}
		

		return 0;
}