Cod sursa(job #960232)

Utilizator lucky1992Ion Ion lucky1992 Data 9 iunie 2013 22:12:28
Problema Componente biconexe Scor 46
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <stack>
#include <fstream>
#include <iostream>
#include <algorithm>

#define NMAX 100005

using namespace std;


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

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

}

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




int main(){
	
		freopen("biconex.in", "r", stdin );
		freopen("biconex.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);		
			neigh[y].push_back(x);	
		}

		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;
}