Cod sursa(job #1204230)

Utilizator legionarulCorneliu Zelea Codreanu legionarul Data 2 iulie 2014 13:40:26
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

const int MAXN = 100005;
const int MAXM = 500005;
int n, m;
int x[MAXM], y[MAXM];
vector<int> g[MAXN], res;
bool vis[MAXN];
stack<int> sk;

void read() {
	fin >> n >> m;
	for (int i = 1; i <= m; ++i) {
		fin >> x[i] >> y[i];
		g[x[i]].push_back(i);
		g[y[i]].push_back(i);
	}
}

void solve() {
	for (int i = 1; i <= n; ++i)
		if ((int)g[i].size() % 2) {
			cout << "-1\n";
			return ;
		}
	sk.push(1);
	while (sk.size()) {
		int node = sk.top(); bool ok = true;
		while ((int)g[node].size() && ok) {
			int edge = g[node].back();
			g[node].pop_back();
			if (!vis[edge]) {
				vis[edge] = true;
				sk.push(x[edge] + y[edge] - node);
				ok = false;
			}
		}
		if (ok) {
			res.push_back(node);
			sk.pop();
		}
	}
}

void write() {
	res.pop_back();
	for (int i = 0; i < (int)res.size(); ++i)
		fout << res[i] << ' ';
}

int main() {
	read();
	solve();
	write();
}