Cod sursa(job #1366626)

Utilizator MarronMarron Marron Data 1 martie 2015 12:17:00
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>


typedef std::vector< std::pair< int, int > >::iterator iter;


const int MAXN = 100005;
const int MAXM = 500005;
std::ifstream f("ciclueuler.in");
std::ofstream g("ciclueuler.out");
int n, m;
std::vector<int> G[MAXN];
std::stack<int> st;
std::vector<int> sol;


bool iseuler()
{
	for (int i = 1; i <= n; i++) {
		if (G[i].size() % 2 != 0) {
			return false;
		}
	}
	return true;
}


void euler()
{
	st.push(1);
	while (!st.empty()) {
		int node = st.top();

		if (!G[node].empty()) {
			int newnode = G[node].back();
			st.push(newnode);

			G[node].pop_back();
			G[newnode].erase(std::find(G[newnode].begin(), G[newnode].end(), node));
		}
		else {
			sol.push_back(node);
			st.pop();
		}
	}
}


int main()
{
	f >> n >> m;
	for (int i = 1, x, y; i <= m; i++) {
		f >> x >> y;
		G[x].push_back(y);
		G[y].push_back(x);
	}

	if (!iseuler()) {
		g << -1 << std::endl;
		f.close();
		g.close();
		return 0;
	}


	euler();
	for (int i = 1; i < sol.size(); i++) {
		g << sol[i] << ' ';
	}
	g << std::endl;


	//system("pause");
	f.close();
	g.close();
	return 0;
}