Cod sursa(job #1724011)

Utilizator theo.stoicanTheodor Stoican theo.stoican Data 2 iulie 2016 00:16:50
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;

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

int n, m;
vector<vector<int> > graph;
stack<int> s;
vector<int> eulerList;
bool check_connectivity (int x)
{
	vector<bool> visited (n+1, false);
	queue<int> q;
	q.push(x);
	while (!q.empty())
	{
		int y = q.front(); q.pop();
		visited[y] = true;
		for (int i = 0; i < graph[y].size(); ++i)
		{
			if (!visited[graph[y][i]])
			{
				q.push(graph[y][i]);
			}
		}
	}
	for (int i = 1; i <= n; i++)
		if (!visited[i])
			return false;
	return true;
}

void sterge (int v, int w)
{
	vector<int>::iterator it;
	for (it = graph[v].begin(); it != graph[v].end(); it++)
	{
		if ((*it) == w)
		{
			graph[v].erase(it);
			break;
		}
	}
	for (it = graph[w].begin(); it != graph[w].end(); it++)
	{
		if ((*it) == v)
		{
			graph[w].erase(it);
			break;
		}
	}
}

void euler (int v)
{
	while (true)
	{
		if (graph[v].empty())
			break;
		int w = graph[v].front();
		//cout<<"v: "<<v<<endl;
		s.push(v);
		sterge (v, w);
		v = w;
	}
}	

void algo(int v)
{
	do{
		euler(v);
		v = s.top();s.pop();
		//cout<<"v: "<<v<<endl;
		eulerList.push_back(v);
	}while (!s.empty());
}
int main()
{
	fin >> n >> m;
	graph.resize(n+1);
	int u, v;
	vector<int> degree(n+1, 0);
	for (int i = 0; i < m; i++)
	{
		fin>>u>>v;
		graph[u].push_back(v);
		graph[v].push_back(u);
		degree[u]++;
		degree[v]++;
	}
	for (int i = 1; i <= n; i++)
		if (degree[i] % 2 == 1)
		{
			fout<<"-1"; 
			return 0;
		}
	if (check_connectivity(1) == false)
	{
		fout<<"-1";
		return 0;
	}
	algo(1);
	//cout<<eulerList.size();
	for (int i = 0; i < eulerList.size(); i++)
	{
		fout<<eulerList[i]<<" ";
	}
	return 0;
}