Cod sursa(job #1756871)

Utilizator preda.andreiPreda Andrei preda.andrei Data 13 septembrie 2016 19:37:42
Problema Ciclu Eulerian Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <map>

using namespace std;

#define NMAX 100001

map<int, int> vecini[NMAX];
int grade[NMAX];
vector<int> stiva;

int main()
{
    ifstream fin("ciclueuler.in");
    ofstream fout("ciclueuler.out");

    int n, m;
    fin >> n >> m;

    while (m--) {
        int x, y;
        fin >> x >> y;

        auto it = vecini[x].find(y);
        if (it == vecini[x].end()) {
            vecini[x].insert(make_pair(y, 1));
            vecini[y].insert(make_pair(x, 1));
        }
        else {
            ++it->second;
            it = vecini[y].find(x);
            ++it->second;
        }
        ++grade[x];
        ++grade[y];
    }

    bool valid = true;
    for (int i = 1; i <= n && valid; ++i) {
        if (grade[i] % 2 != 0) {
            valid = false;
        }
    }

    if (!valid) {
        fout << -1;
        return 0;
    }

    stiva.push_back(1);

    while (!stiva.empty()) {
        int curent = stiva.back();

        auto it = vecini[curent].begin();
        while (it != vecini[curent].end() && it->second == 0) {
            ++it;
        }

        if (it != vecini[curent].end()) {
            int vecin = it->first;
            --it->second;
            if (it->first != curent) {
                --vecini[vecin].find(curent)->second;
            }

            stiva.push_back(vecin);
        }
        else {
            if (stiva.size() > 1) {
                fout << curent << " ";
            }
            stiva.pop_back();
        }
    }

    return 0;
}