Cod sursa(job #554829)

Utilizator BitOneSAlexandru BitOne Data 15 martie 2011 09:45:20
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <queue>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#define N_MAX 100011
#define oo 1<<20

using namespace std;
int d[N_MAX];
bool was[N_MAX];
queue< int > Q;
vector< int > S, r;
vector< int > G[N_MAX];
vector< int >::iterator it, iend;
void Euler( int x )
{
	int y;
	while( !G[x].empty() )
	{
		y=G[x].back();
		G[x].pop_back();
		G[y].erase( find( G[y].begin(), G[y].end(), x ) );
		S.push_back(x);
		x=y;
	}
}
int main( void )
{
	int N, M, x, y, countSeen;
	ifstream in( "ciclueuler.in" );
	for( in>>N>>M; M; --M )
	{
		in>>x>>y;
		G[x].push_back(y);
		G[y].push_back(x);	
		++d[x]; ++d[y];
	}
	for( x=1; x <= N; ++x )
		if( d[x]%2 )
		{
			ofstream out( "ciclueuler.out" );
			out<<"-1\n";
			return EXIT_SUCCESS;
		}
	was[1]=true;
	for( Q.push(1), countSeen=N-1; countSeen && !Q.empty(); )
	{
		x=Q.front(); Q.pop();
		for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
			if( false == was[*it] )
			{
				--countSeen;
				was[*it]=false;
				if( 0 == countSeen )
					break;
				Q.push(*it);
			}
	}
	if( countSeen )
	{
		ofstream out( "ciclueuler.out" );
		out<<"-1\n";
		return EXIT_SUCCESS;
	}
	x=1;
	do
	{
		Euler(x);
		r.push_back( x=S.back() ); S.pop_back();
	}while( !S.empty() );
	ofstream out( "ciclueuler.out" );
	copy( r.rbegin(), r.rend(), ostream_iterator<int>( out, " " ) );
	out<<'\n';
	return EXIT_SUCCESS;
}