Cod sursa(job #1743571)

Utilizator mouse_wirelessMouse Wireless mouse_wireless Data 18 august 2016 13:40:10
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <cstdio>
#include <vector>
#include <list>
#include <stack>
using namespace std;

struct edge {
	int vertex;
	int eID;
};

vector< vector<edge> > G;
vector<int> deg;
stack<int> S;
vector<char> viz;

#define CLEAR_STACK(s) { \
	while (!s.empty()) \
	s.pop(); \
}

int curEID;

void addEdge(int x, int y) {
	G[x].push_back({ y, curEID });
	G[y].push_back({ x, curEID });
	curEID++;
	++deg[x], ++deg[y];
}

char isConnected() {
	CLEAR_STACK(S);
	S.push(0);
	memset(&viz[0], 0, sizeof(viz[0]) * viz.size());
	while (!S.empty()) {
		int t = S.top();
		S.pop();
		if (viz[t]) continue;
		viz[t] = 1;
		for (vector<edge>::iterator i = G[t].begin(), end = G[t].end(); i != end; ++i)
		if (!viz[i->vertex])
			S.push(i->vertex);
	}
	for (vector<char>::iterator i = viz.begin(), end = viz.end(); i != end; ++i)
	if (!(*i))
		return 0;
	return 1;
}

char isEuler() {
	if (!isConnected())
		return 0;
	for (vector<int>::iterator i = deg.begin(), end = deg.end(); i != end; ++i)
	if ((*i) & 1)
		return 0;
	return 1;
}

void visitOneCycle(int t) {
	char flag = 1;
	while (flag) {
		flag = 0;
		for (vector<edge>::reverse_iterator i = G[t].rbegin(), end = G[t].rend(); i != end; ++i)
		if (!viz[i->eID]) {
			viz[i->eID] = 1;
			S.push(t);
			t = i->vertex;
			flag = 1;
			break;
		}
	}
}

void printEulerCycle() {
	CLEAR_STACK(S);
	memset(&viz[0], 0, sizeof(viz[0]) * viz.size());
	int t = 0;
	do {
		visitOneCycle(t);
		t = S.top(); S.pop();
		printf("%d ", t + 1);
	} while (!S.empty());
	putchar('\n');
}

int main() {
#ifdef INFOARENA
	freopen("ciclueuler.in", "r", stdin);
	freopen("ciclueuler.out", "w", stdout);
#endif
	int N, M;
	scanf("%d%d", &N, &M);
	G.resize(N);
	deg.resize(N, 0);
	viz.reserve(M);
	viz.resize(N);
	for (int i = 0; i < M; i++) {
		int x, y;
		scanf("%d%d", &x, &y);
		--x, --y;
		addEdge(x, y);
	}
	if (!isEuler()) {
		printf("%d\n", -1);
		return 0;
	}
	viz.resize(M);
	printEulerCycle();
	return 0;
}