Cod sursa(job #524400)

Utilizator popoiu.georgeGeorge Popoiu popoiu.george Data 21 ianuarie 2011 10:22:58
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include<fstream>
#include<list>
#include<stack>
#include<queue>
#define inf "ciclueuler.in"
#define outf "ciclueuler.out"
#define NMax 100100
#define MMax 500100
using namespace std;

fstream f(inf,ios::in), g(outf,ios::out);

int N, M, deg[NMax], viz[NMax];
list<int> LA[NMax], L;
stack<int> S; queue<int> Q;

void read()
{
	f>>N>>M; int a, b;
	for(int i=1; i<=M; i++)
	{
		f>>a>>b;
		LA[a].push_back(b); LA[b].push_back(a);
		deg[a]++; deg[b]++;
	}
}

void BFS(int nod)
{
	Q.push(nod); viz[nod] = 1;
	while( !Q.empty() )
	{
		nod = Q.front(); Q.pop();
		for( list<int>::iterator it=LA[nod].begin(); it!=LA[nod].end(); it++ )
			if( viz[ *it ] == 0 ) { viz[*it]=1; Q.push(*it); }
	}
}

bool graf_eulerian()
{
	BFS(1);
	for(int i=1; i<=N; i++)
		if( !viz[i] ) return false;
	for(int i=1; i<=N; i++)
		if( deg[i]%2 == 1 ) return false;
	return true;
}

void sterge(int v, int w)
{
	deg[v]--; deg[w]--;
	LA[v].pop_front();
	for(list<int>::iterator it=LA[w].begin(); it!=LA[w].end(); it++)
		if( (*it)==v ) { LA[w].erase( it ); return; }
}

void euler(int v)
{
	while(true)
	{
		if( LA[v].empty() ) return;
		int w = LA[v].front();
		S.push(v);
		sterge(v,w);
		v = w;
	}
}

void solve()
{
	if( !graf_eulerian() ) { g<<"-1"; return; }
	int v = 1;
	do
	{
		euler(v);
		v = S.top(); S.pop();
		L.push_back(v);
	}
	while( !S.empty() );
	for(list<int>::iterator it=L.begin(); it!=L.end(); it++) g<< *it <<" ";
}

int main()
{
	read(); solve();
	f.close(); g.close();
	return 0;
}