Cod sursa(job #2435088)

Utilizator DRLDRLRaul Ronald Galea DRLDRL Data 2 iulie 2019 22:51:52
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#pragma once


#include<iostream>
#include<vector>
#include<fstream>
#include<queue>
#include<algorithm>
#include<unordered_map>


using namespace std;

ifstream fin("graf.in.txt");
ofstream fout("graf.out.txt");

int V, E;


class Node {
public:

	unordered_map<int, int> adj; // map pentru ca va trebui sa stergem muchii si se admit bucle si muchii paralele

	void add(int id) {
		adj[id]++;
	}
	
};

vector<Node> nodes;
vector<int> deg;

int checkEulerian() {
	for (int i = 1; i < deg.size(); i++) {
		if (deg[i] % 2 != 0)
			return 0;
	}
	return 1;
}

void HierholzerIterativ() {
	vector<int> DFSstacc;
	int c, id, nrEdges;


	DFSstacc.push_back(1); // can start anywhere

	while (!DFSstacc.empty()) {
		c = DFSstacc.back();

		if (deg[c] == 0) {
			DFSstacc.pop_back(); // am gasit pozitia lui c in soluti => aici il scoatem din dfsStac
			fout << c << " ";// am ajuns undeva de unde nu se poate merge nicaieri => toate nodurile succesoare s-au pus deja => se pune asta 
			continue;
		}

		auto x = nodes[c].adj.begin();
		while (x != nodes[c].adj.end()) { 
									  

			nrEdges = (*x).second;
			if (!nrEdges) {
				x++;
				continue; // if no edges to this node check the next
			}

			id = (*x).first;

			nodes[c].adj[id] --;
			deg[c]--;
			deg[id]--;

			if (id != c) {
				nodes[id].adj[c]--;
			}

			DFSstacc.push_back(id);

			break;

		}


	}

}

int main() {
	int x, y, w;
	fin >> V >> E;

	nodes.resize(V+1);
	deg.resize(V + 1, 0);

	for (int i = 0; i < E; i++) {
		fin >> x >> y;
		nodes[x].add(y);
		if (x != y)
			nodes[y].add(x);
		deg[x]++;
		deg[y]++;
	}

	if (checkEulerian()) {
		HierholzerIterativ();
	}
	else
		fout << -1;

	return 0;
}