Cod sursa(job #2080548)

Utilizator ice_creamIce Cream ice_cream Data 3 decembrie 2017 11:07:11
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

ifstream f ("ciclueuler.in");
ofstream g ("ciclueuler.out");

const int NMAX = 100000;
const int MMAX = 500000;

int n;
int grad[NMAX + 1];
bool vizitat[NMAX + 1];
bool pus[MMAX + 1];
vector <int> graf[NMAX + 1];
vector <int> nr_muchie[NMAX + 1];
stack <int> stiva;

void citeste() {
	int e, a, b;
	f >> n >> e;
	for (int i = 1; i <= e; i++) {
		f >> a >> b;
		graf[a].push_back(b);
		graf[b].push_back(a);
		nr_muchie[a].push_back(i);
		nr_muchie[b].push_back(i);
		grad[a]++;
		grad[b]++;
	}
}

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

void DFS(int nod) {
	if (vizitat[nod]) return;
	vizitat[nod] = true;
	int l = graf[nod].size();
	for (int i = 0; i < l; i++)
		DFS(graf[nod][i]);
}

bool e_conex() {
	DFS(1);
	for (int i = 1; i <= n; i++)
		if (!vizitat[i]) return false;
	return true;
}

void euler() {
	int nod, l, fiu;
	stiva.push(1);

	while (!stiva.empty()) {
		nod = stiva.top();
		l = graf[nod].size();

		while(l > 0 && pus[nr_muchie[nod][l - 1]]) {
			graf[nod].pop_back();
			nr_muchie[nod].pop_back();
			l--;
		}
		
		if (l == 0) {
			g << nod << ' ';
			stiva.pop();
			continue;
		}

		fiu = graf[nod][l - 1];
		pus[nr_muchie[nod][l - 1]] = true;
		graf[nod].pop_back();
		stiva.push(fiu);
	}
}

int main() {
	citeste();
	if (sunt_grade_pare() && e_conex()) {
		euler();
		g << '\n';
	}
	else {
		g << "-1\n";
	}
	return 0;
}