Cod sursa(job #616107)

Utilizator BitOneSAlexandru BitOne Data 11 octombrie 2011 19:20:56
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <stack>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#define N_MAX 100011

using namespace std;
int idx, countSCC;
int lowLink[N_MAX], dfsIdx[N_MAX];
bool was[N_MAX], isInStack[N_MAX];
stack< int > S;
vector< int > G[N_MAX], SConectedC[N_MAX];
inline int _min( int x, int y ) { return x <= y ? x : y; }
inline void DFS( int x )
{
	was[x]=true;
	lowLink[x]=dfsIdx[x]=++idx;
	S.push( x );
	isInStack[x]=true;
	vector< int >::const_iterator it=G[x].begin(), iend=G[x].end();
	for( ; it < iend; ++it )
	{
		if( false == was[*it] )
		{
			DFS(*it);
			lowLink[x]=_min( lowLink[x], lowLink[*it] );
		}
		else if( isInStack[*it] )
				lowLink[x]=_min( lowLink[x], dfsIdx[*it] );
	}
	if( lowLink[x] == dfsIdx[x] )
	{
		int y;
		do
		{
			y=S.top(); S.pop();
			isInStack[y]=false;
			SConectedC[countSCC].push_back(y);
		}while( x != y );
		++countSCC;
	}	
}
int main( void )
{
	int N, M, x, y, i;
	ifstream in( "ctc.in" );
	for( in>>N>>M; M; --M )
	{
		in>>x>>y;
		G[x].push_back( y );
	}
	for( i=1; i <= N; ++i )
		if( false == was[i] )
			DFS(i);
	ofstream out( "ctc.out" );
	out<<countSCC<<'\n';
	for( i=0; i < countSCC; ++i )
	{
		copy( SConectedC[i].begin(), SConectedC[i].end(), ostream_iterator<int>( out, " " ) );
		out<<'\n';
	}
	return EXIT_SUCCESS;
}