Cod sursa(job #3253465)

Utilizator StefanStratonStefan StefanStraton Data 2 noiembrie 2024 19:00:11
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 100005, MMAX = 500005;

vector<int> lista[NMAX];
int from[MMAX], to[MMAX];
bool usedEdge[MMAX];

int main() {
    int n, m;
    in >> n >> m;

    for (int i = 1; i <= m; ++i) {
        int nod1, nod2;
        in >> nod1 >> nod2;
        lista[nod1].push_back(i);
        lista[nod2].push_back(i);
        from[i] = nod1;
        to[i] = nod2;
    }

    for (int i = 1; i <= n; ++i) {
        if (lista[i].size() % 2 != 0) {
            out << "-1";
            return 0;
        }
    }

    vector<int> ans;
    vector<int> stack;
    stack.push_back(1); // nod de plecare

    while (!stack.empty()) {
        int node = stack.back();

        while (!lista[node].empty() && usedEdge[lista[node].back()]) {
            lista[node].pop_back(); // scot muchiile folosite din lista de adiacenta (nodurile corespunzatoare capetelor muchiei)
        }

        if (!lista[node].empty()) {
            int edge = lista[node].back();
            lista[node].pop_back();
            if (!usedEdge[edge]) {
                usedEdge[edge] = true;
                int Vecin = from[edge] ^ to[edge] ^ node;
                /*
                Daca node este egal cu from[edge], atunci Vecin devine to[edge].
                Daca node este egal cu to[edge], atunci Vecin devine from[edge].

                Operatorul XOR:
                a ^ a = 0 pentru orice a.
                a ^ 0 = a.
                */
                stack.push_back(Vecin);
            }
        } else {
            // scot nodul din stiva si il pun in vectorul ans
            stack.pop_back();
            ans.push_back(node);
        }
    }

    for (int i = ans.size() - 1; i >= 1; --i) {
        out << ans[i] << ' ';
    }
    /*for (int i = 1; i <= ans.size() - 1; i++) {
        out << ans[i] << ' ';
    }*/
    out << "\n";

    return 0;
}