Cod sursa(job #971872)

Utilizator tudorv96Tudor Varan tudorv96 Data 10 iulie 2013 14:09:06
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <vector>
#include <list>
#include <fstream>
#include <queue>
using namespace std;

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

vector <bool> viz;
vector <list <int> > g;
vector <int> st;
queue <int> Q;
int n, m;

void bfs(int x) {
	Q.push(x);
	viz[x] = 1;
	while (Q.size()) {
		x = Q.front();
		Q.pop();
		for (list <int> :: iterator it = g[x].begin(); it != g[x].end(); ++it)
			if (!viz[*it]) {
				viz[*it] = 1;
				Q.push(*it);
			}
	}
}

bool verif() {
	for (int i = 1; i <= n; ++i)
		if (g[i].size() & 1 || (!viz[i] && g[i].size()))
			return 0;
	return 1;
}

int main() {
	fin >> n >> m;
	viz.resize(n+1);
	g.resize(n+1);
	st.reserve(n+1);
	while (m--) {
		int x, y;
		fin >> x >> y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	bfs(1);
	if (!verif()) {
		fout << -1;
		return 0;
	}
	st.push_back(*g[1].begin());
	int y = st.back();
	g[1].erase(g[1].begin());
	list <int> :: iterator it = g[y].begin();
	while (*it != 1)
		it++;
	g[y].erase(it);
	while (st.size()) {
		int x = st.back();
		if (!g[x].size()) {
			fout << x << " ";
			st.pop_back();
			continue;
		}
		int y = *g[x].begin();
		g[x].erase(g[x].begin());
		st.push_back(y);
		it = g[y].begin();
		while (*it != x)
			it++;
		g[y].erase(it);
	}
	fout.close();
}