Cod sursa(job #530058)

Utilizator feelshiftFeelshift feelshift Data 6 februarie 2011 19:18:36
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
// http://infoarena.ro/problema/ciclueuler
#include <fstream>
#include <list>
using namespace std;

#define maxSize 100002

int nodes;
list<int> graph[maxSize];
list<int> nodeList;

void read();
bool eulerianCycle();
void euler(int currentNode);
void write(bool status);

int main() {
	read();

	if(eulerianCycle()) {
		euler(1);
		write(true);
	}
	else
		write(false);

	return (0);
}

void read() {
	ifstream in("ciclueuler.in");
	int edges,from,to;

	in >> nodes >> edges;
	for(int i=1;i<=edges;i++) {
		in >> from >> to;

		// graf neorientat
		graph[from].push_back(to);
		graph[to].push_back(from);
	}

	in.close();
}

// un multigraf este Eulerian (admite un ciclu Eulerian) daca si numai daca este conex si toate nodurile sale au grad par
bool eulerianCycle() {
	for(int currentNode=1;currentNode<=nodes;currentNode++)
		if(graph[currentNode].size() % 2)
			return false;
	
	return true;
}

void euler(int currentNode) {
	int next;
	list<int>::iterator neighbour;
	list<int>::iterator neighbourOfNeighbour;

	neighbour = graph[currentNode].begin();

	while(graph[currentNode].size()) {
		neighbour = graph[currentNode].begin();
		next = *neighbour;

		for(neighbourOfNeighbour=graph[next].begin();neighbourOfNeighbour!=graph[next].end();neighbourOfNeighbour++)
			if(*neighbourOfNeighbour == currentNode) {
				graph[next].erase(neighbourOfNeighbour);
				break;
			}

		graph[currentNode].pop_front();
		euler(next);
	}

	nodeList.push_back(currentNode);
}

void write(bool status) {
	ofstream out("ciclueuler.out");
	list<int>::iterator currentNode;
	nodeList.pop_front();

	if(status)
		for(currentNode=nodeList.begin();currentNode!=nodeList.end();currentNode++)
			out << *currentNode << " ";
	else
		out << "-1";

	out.close();
}