Cod sursa(job #751039)

Utilizator ChallengeMurtaza Alexandru Challenge Data 23 mai 2012 23:20:05
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

const char InFile[]="ciclueuler.in";
const char OutFile[]="ciclueuler.out";
const int MaxN=100111;
const int MaxM=500111;

ifstream fin(InFile);
ofstream fout(OutFile);

struct Edge
{
	Edge(int to=0, int index=0):to(to),index(index){}
	int to,index;
};

int N,M,x,y,viz[MaxM],D[MaxN],vizN[MaxN];
vector<Edge> G[MaxN];
vector<int> sol;
stack<int> S;

inline bool Euler()
{
	for(register int i=1;i<=N;++i)
	{
		if(D[i]&1)
		{
			return false;
		}
	}
	
	S.push(1);
	while(!S.empty())
	{
		int nod=S.top();
		if(G[nod].size()==0)
		{
			S.pop();
			sol.push_back(nod);
		}
		else
		{
			Edge e=G[nod][G[nod].size()-1];
			if(!viz[e.index])
			{
				S.push(e.to);
				viz[e.index]=1;
			}
			G[nod].pop_back();
		}
	}
	
	return true;
}

int main()
{
	fin>>N>>M;
	for(register int i=1;i<=M;++i)
	{
		fin>>x>>y;
		G[x].push_back(Edge(y,i));
		G[y].push_back(Edge(x,i));
		++D[x];
		++D[y];
	}
	fin.close();
	
	if(!Euler())
	{
		fout<<"-1";
	}
	else
	{
		vector<int>::iterator last=sol.end();
		--last;
		for(vector<int>::iterator it=sol.begin();it!=last;++it)
		{
			fout<<*it<<" ";
		}
	}
	fout.close();
	return 0;
}