Cod sursa(job #532028)

Utilizator andreitheo87Teodorescu Andrei-Marius andreitheo87 Data 10 februarie 2011 18:29:16
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
struct Node {
	Node* next;
	int val;
	bool used;
	Node(int x) {
		next = 0;
		val = x;
		used = false;
	}
	Node *simetric;
};
Node* lista[100001];
int solu[500000];
int stack[500000];
int num = 0;

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

Node* bagaNod(int x, int y) {
	Node* newNode = new Node(y);
	newNode->next = lista[x];
	lista[x] = newNode;
	return newNode;
}

void find_euler_cycle() {
	int top = 0;
	stack[0] = 0;
	while (top>=0) {
		int cn = stack[top];
		while (lista[cn] && lista[cn]->used) {
			lista[cn] = lista[cn]->next;
		}
		if (lista[cn]) {
			stack[++top] = lista[cn]->val;
			// lista[cn]->used = true; useless
			lista[cn]->simetric->used = true;
			lista[cn] = lista[cn]->next;
		} else {
		  top--;
		  solu[num++] = cn;
		}
	}
}

int main() {
	memset(lista, 0, sizeof(lista));
	int n, m;
	fin >> n >> m;
	for (int i=0; i < m; i++) {
		int x, y;
		fin >> x >> y;
		--x; --y;
		Node* nod1 = bagaNod(x, y);
		Node* nod2 = bagaNod(y, x);
		nod1->simetric = nod2;
		nod2->simetric = nod1;
	}
	for (int i=0; i<n; i++) {
	  int grad = 0;
	  Node* nod = lista[i];
	  while (nod) {
	    grad++;
	    nod = nod->next;
	  }
	  if (grad%2==1) {
	    fout << -1 << endl;
	    fout.close();
	    return 0;
	  }
	}
	find_euler_cycle();
	for(int i=0; i<num-1; i++) {
	  fout << solu[i] + 1 << " ";
	}
	fout << endl;
	fout.close();
	return 0;
}