Cod sursa(job #2473623)

Utilizator gabbie02Thomits Gabriel gabbie02 Data 13 octombrie 2019 21:58:21
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <set>
#include <stack>

using namespace std;

ofstream fout("ciclueuler.out");
multiset<unsigned int> adjlist[100001];
unsigned int v;

void rd()
{
	ifstream fin("ciclueuler.in");
	unsigned int i, j;
	fin >> v >> i;
	while(fin >> i >> j){
		adjlist[i].insert(j);
		adjlist[j].insert(i);
	}
	fin.close();
}

bool isEuler()
{
	for(unsigned int i = 1; i <= v; i++){
		if(adjlist[i].size() & 1){
			return false;
		}
	}
	return true;
}

unsigned int next(unsigned int vert)
{
    unsigned int n = 0;
    if(adjlist[vert].size()){
        n = *adjlist[vert].begin();
        adjlist[n].erase(adjlist[n].find(vert));
        adjlist[vert].erase(adjlist[vert].begin());
    }
    return n;
}

void eulerCycle(unsigned int vert)
{
    stack<unsigned int> nodes;
    stack<unsigned int> cycle;
    nodes.push(vert);
    while(!nodes.empty()){
        vert = next(nodes.top());
        if(vert){
            nodes.push(vert);
        } else {
            cycle.push(nodes.top());
            nodes.pop();
        }
    }
    while(cycle.size() > 1){
        fout << cycle.top() << " ";
        cycle.pop();
    }
}

int main()
{
	rd();
	if(isEuler()){
        eulerCycle(1);
	} else {
		fout << -1;
	}
	return 0;
}