Cod sursa(job #1221111)

Utilizator Luncasu_VictorVictor Luncasu Luncasu_Victor Data 19 august 2014 15:42:08
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
#define MAX 100010

struct Node{
	int X;
	struct Node * Edge, * Next, * Prev;
	Node(){
		Edge = Next = Prev = NULL;
		X = 0;
	}
	Node(int X) {
		Edge = Next = Prev = NULL;
		this->X = X;
	}
} *Gr[MAX];

stack<int> S;
vector<int> Sol;

int N, M, Grade[MAX];

void AddNeighbor(Node *A, int X) {
	if (Gr[X] == NULL) {
		Gr[X] = A;
	} else {
		Gr[X]->Next = A;
		A->Prev = Gr[X];
		Gr[X] = A;
	}
}

void RemoveNeighbor(Node *A, int X) {
	if (A->Next != NULL) {
		if (A->Prev == NULL) {
			A->Next->Prev = NULL;
		} else {
			A->Next->Prev = A->Prev;
			A->Prev->Next = A->Next;
		}
	} else {
		if (A->Prev == NULL) {
			Gr[X] = NULL;	
		} else {
			Gr[X] = A->Prev;
			Gr[X]->Next = NULL;
		}
	}
}

void DFS() {
	int X;
	S.push(1);
	while (S.size()) {
		X = S.top();
		if (Gr[X] == NULL) {	    // if no more neighbors
			Sol.push_back(X);		// then add to cycle
			S.pop();				// and extract from stack
		} else {
			S.push(Gr[X]->X);		// otherwise put that neighbor to stack
			RemoveNeighbor(Gr[X]->Edge, Gr[X]->X);	// and remove edge from both sides
			RemoveNeighbor(Gr[X], X);				
		}
	}
}

bool Eulerian() {
	for (int i = 1; i <= N; i++)
		if (Grade[i] % 2) return 0;
	return 1;
}

int main() {
	int X, Y;
	Node *A, *B;
	
	freopen("ciclueuler.in","r",stdin);
	freopen("ciclueuler.out","w",stdout);
	
	memset(Gr, 0, sizeof(Gr));
	
	scanf("%d %d", &N, &M);
	for (int i = 1; i <= M; i++) {
		scanf("%d %d", &X, &Y);
		Grade[X]++;
		Grade[Y]++;
		A = new Node(Y);
		B = new Node(X);
		AddNeighbor(A, X);
		AddNeighbor(B, Y);
		A->Edge = B;
		B->Edge = A;
	}
		
	if (Eulerian()){	
		DFS();
	
		for (int i = 0; i < Sol.size() - 1; i++) {
			printf("%d ", Sol[i]);
		}
	} else {
		printf("-1\n");
	}
	
	return 0;
}