Cod sursa(job #777244)

Utilizator danalex97Dan H Alexandru danalex97 Data 11 august 2012 16:45:59
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <vector>
#include <queue>
#include <list>
using namespace std;

const int Nmax = 100011;
const int Mmax = 500011;
const int oo = 1<<30;
const int null = -1;

list< int > Leg[Nmax] , L;
vector< int > Stiva;
queue< int > Q;

int N,M,Grad[Nmax];
int Marked[Nmax];

ifstream F("ciclueuler.in");
ofstream G("ciclueuler.out");

void BFS( int v ) 
{
    Q.push( v ); 
	Marked[v] = 1;
    
	while( Q.size() ) 
	{
        v = Q.front();
		Q.pop();
		
		for( typeof( Leg[v].begin() ) w = Leg[v].begin(); w != Leg[v].end(); ++w )
            if( Marked[ *w ] == 0 )
                Q.push( *w ), Marked[ *w ] = 1;
    }
}

void Erase( int v, int w ) 
{
    Grad[v]--;
	Grad[w]--;
  
	Leg[v].pop_front();
	
	for( typeof( Leg[w].begin() ) it = Leg[w].begin(); it != Leg[w].end(); ++it )
        if( *it == v )
		{
            Leg[w].erase( it );
            break;
        }
}

void Euler( int v ) 
{
    while (1) 
	{
        if( Leg[v].empty() ) break;
		
        int w = Leg[v].front();
        
		Stiva.push_back( v );
        Erase( v, w );
        
		v = w;
    }
}

int main()
{
	F>>N>>M;
	for (int i=1;i<=M;++i) 
	{
		int x,y;
		F>>x>>y;
		Leg[x].push_back( y );
		Leg[y].push_back( x );
		++Grad[x];
		++Grad[y];
	}
	
	BFS( 1 );
	
	for (int i=1;i<=N;++i)
		if ( !Marked[ i ] )
		{
			G<<null<<'\n';
			return 0;
		}
	for (int i=1;i<=N;++i)
		if ( Grad[ i ]%2==1 )
		{
			G<<null<<'\n';
			return 0;
		}
	
	int v=1;
	
	do{	Euler( v );
        
		v = Stiva.back(); 
		Stiva.pop_back();
        
		L.push_back( v );
    } while( !Stiva.empty() );
	
	for( typeof(L.begin()) it = L.begin(); it != L.end(); it++ )
        G<< *it <<' ';
    G<<'\n';
}