Cod sursa(job #812355)

Utilizator MtkMarianHagrSnaf MtkMarian Data 13 noiembrie 2012 19:53:50
Problema Ciclu Eulerian Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include<cstdio>
#include<list>
#include<queue>
#include<stack>
using namespace std ;

#define NMAX 100005
list < int > g[NMAX],ciclueuler;
queue< int > que;
stack< int > st;

int n , m , grad[NMAX]={0},viz[NMAX] ={0} ,x ,y;

void citeste()
{
	scanf("%d %d",&n,&m);
	for( int i = 1 ; i <= m ; ++i )
	{
		scanf("%d %d",&x,&y) ;
		g[x].push_back(y);
		g[y].push_back(x);

		++grad[x];
		++grad[y];
	}


}

void bfs(int val)
{
	list< int > ::iterator it ;
	que.push(val);
	viz[val]=1;
	while( que.size() )
	{
		val = que.front();
		que.pop();

		for( it = g[val].begin() ; it != g[val].end() ; ++it )
		{
			if( !viz[*it])
			{
				que.push( *it );
				viz[*it]=1;
			}

		}
	}
}

int este_conex()
{
	bfs(1) ;
	for(int i = 2 ; i <= n; ++i )
		if(viz[i] == 0 )return 0 ;

	return 1;
}

int este_eulerian()
{
 if( este_conex()==0 )return 0;

	for(int i = 1 ; i <= n; ++i )
		if ( grad[i]%2  == 1 ) return 0;
	return 1 ;
}
void sterge(int v , int w)
{
	list< int > ::iterator it ;
	--grad[v];
	--grad[w];
	g[v].pop_front();

	for( it = g[w].begin() ; it != g[w].end(); ++it)
	{
		if( *it == v )
		{
			g[w].erase( it );
			break;
		}
	}
}
void euler(int v)
{
	while(true)
	{
		if ( !g[ v ].size() )
			break;
		int w = g[v].front();
		st.push( v);
		sterge( v , w );
		v = w;
	}

}
int rezolva()
{
	int v = este_eulerian() ;
	if( v == 0 )return 0;
		do
			{
				euler(v) ;
				v=st.top();
				st.pop();
				ciclueuler.push_back(v);

			} while(!st.empty()) ;

	

	return 1 ;




}
void scrie()
{
	list< int > ::iterator it ;
	for( it = ciclueuler.begin() ; it != ciclueuler.end(); ++it)
		printf("%d ", *it ) ;
	
}
int main()
{
	freopen( "ciclueuler.in" , "r" , stdin);
	freopen( "ciclueuler.out" , "w" , stdout);
	citeste();
	int g = rezolva();
	if( g ) scrie() ;
	else printf("-1");
}