Cod sursa(job #956065)

Utilizator gabrieligabrieli gabrieli Data 2 iunie 2013 04:47:53
Problema Ciclu Eulerian Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

const int MAXN = 100010;
ifstream fin ("ciclueuler.in");
ofstream fout ("ciclueuler.out");

void erase (int v, int w, vector< vector<int>> &G)
{
	G[v].pop_back();
	for (auto it = G[w].begin(); it != G[w].end(); ++it)
		if (*it == v) 
		{
			G[w].erase (it);
			break;
		}
}

int main()
{
	int N, m;
	fin >> N >> m;

	vector <vector <int>> G (N+1);
	vector <int> degree (N+1, 0);
	for (int i = m; i; --i)
	{
		int x, y;
		fin >> x >> y;
		G[x].push_back (y);
		G[y].push_back (x);
		degree[x]++;
		degree[y]++;
	}

	for (int v = 1; v <= N; ++v)
		if (degree[v] == 0 || degree[v] % 2 == 1)
		{
			fout << "-1\n";
			fout.close();
			return 0;
		}

	stack <int> vst;
	vst.push (1);
    while (!vst.empty())
	{
		int v = vst.top();

		if (G[v].size() == 0)
			do
			{
				vst.pop();
				if (!vst.empty())
				{
					fout << v << ' ';
					v = vst.top();
				}
			} while (G[v].size() != 0);
		else
		{
			vst.push (G[v].back());

			erase (v, G[v].back(), G);
		}
	}

	fout << '\n';
	fout.close();
	return EXIT_SUCCESS;
}