Cod sursa(job #2551460)

Utilizator MarcGrecMarc Grec MarcGrec Data 19 februarie 2020 20:56:26
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#define MAX_N 100000
#define MAX_M 500000

#include <fstream>
#include <list>
#include <tuple>
#include <stack>
#include <bitset>
using namespace std;

ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");

int n, m, R[MAX_M + 2];
tuple<int, int> E[MAX_M + 1];
tuple<list<int>, list<int>::iterator> G[MAX_N + 1];
stack<int> Stk;
bitset<MAX_M + 1> F;

int main()
{
	fin >> n >> m;
	
	for (int i = 0, x, y; i < m; ++i)
	{
		fin >> x >> y;
		get<0>(G[x]).push_back(i);
		get<0>(G[y]).push_back(i);
		E[i] = { x, y };
	}
	
	bool ok = true;
	for (int i = 1; i <= n; ++i)
	{
		if (get<0>(G[i]).size() & 1) { ok = false; break; }
		get<1>(G[i]) = get<0>(G[i]).begin();
	}
	
	if (ok)
	{
		int l = 0;
		Stk.push(1);
		while (!Stk.empty())
		{
			int nod = Stk.top();
			for (auto& it = get<1>(G[nod]); it != get<0>(G[nod]).end(); ++it)
			{
				if (!F[*it])
				{
					F[*it] = true;
					Stk.push((get<0>(E[*it]) == nod) ? get<1>(E[*it]) : get<0>(E[*it]));
					break;
				}
			}
			
			if (Stk.top() == nod)
			{
				R[++l] = nod;
				Stk.pop();
			}
		}
		
		for (int i = 1; i < l; ++i)
		{
			fout << R[i] << ' ';
		}
	}
	else
	{
		fout << "-1";
	}
	fin.close();
	fout.close();
	return 0;
}