Cod sursa(job #1985509)

Utilizator rares96cheseliRares Cheseli rares96cheseli Data 28 mai 2017 00:28:47
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 100005

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

int N, M;
vector <int> G[NMAX], sol;
stack <int> st;

void euler(int node) {
    st.push(node);

    while (!st.empty()) {
        int currentNode = st.top();

        if (!G[currentNode].empty()) {
            int last = G[currentNode].back();
            G[currentNode].pop_back();

            for (auto &it : G[last]) {
                if (it == currentNode) {
                    it = G[last].back();
                    G[last].pop_back();
                    break;
                }
            }

            st.push(last);
        } else {
            sol.push_back(currentNode);
            st.pop();
        }
    }
}

int main() {
    f >> N >> M;
    for (int i = 1; i <= M; ++i) {
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    for (int i = 1; i <= N; ++i) {
        if (G[i].size() & 1) {
            g << -1 << '\n';
            return 0;
        }
    }

    euler(1);
    for (int i = 0; i < (int)sol.size(); ++i) {
        g << sol[i] << ' ';
    }
    return 0;
}