Cod sursa(job #2167271)

Utilizator theodor.vladTheodor Vlad theodor.vlad Data 13 martie 2018 20:54:11
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <stack>
#include <vector>

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

struct node
{
	int x;
	node * next;
};

void citire();
bool isEulerian();
void euler();
void deleteNode(node * &, int);
void insertNode(node * &, int);

int n, m;
int d[100005];
node * G[100005];
stack<int> s;
vector<int> cycle;

int main()
{
	citire();
	if (isEulerian())
	{
		euler();
		for (unsigned i = 0; i < cycle.size() - 1; i++)
			fout << cycle[i] << ' ';
		fout << '\n';
	}
	else fout << -1 << '\n';
	return 0;
}

void deleteNode(node * & list, int x)
{
	node * p;
	if (list->x == x)
	{
		p = list;
		list = list->next;
		delete p;
	}
	else
	{
		for (p = list; p->next->x != x; p = p->next);
		node * q = p->next;
		p->next = q->next;
		delete q;
	}
}

void euler()
{
	int x, y;

	s.push(1);
	while (!s.empty())
	{
		x = s.top();
		if (G[x])
		{
			y = G[x]->x;
			deleteNode(G[x], y);
			deleteNode(G[y], x);
			s.push(y);
		}
		else
		{
			s.pop();
			cycle.push_back(x);
		}
	}
}

bool isEulerian()
{
	for (int i = 1; i <= n; i++)
		if (d[i] % 2)
			return false;
	return true;
}

void insertNode(node * & list, int x)
{
	node * p = new node;
	p->x = x;
	p->next = list;
	list = p;
}

void citire()
{
	int x, y;
	fin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		fin >> x >> y;
		insertNode(G[x], y); d[x]++;
		insertNode(G[y], x); d[y]++;
	}
}