Cod sursa(job #2961653)

Utilizator radubuzas08Buzas Radu radubuzas08 Data 6 ianuarie 2023 20:11:45
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

#define NMAX    100001
#define MMAX    500001

vector<int> graph[NMAX];

bool usedEdgraphe[MMAX];
int from[MMAX], to[MMAX];

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

    int n, m;
    in >> n >> m;

    for (int i = 0; i < m; ++i) {
        int x, y;
        in >> x >> y;
        graph[x].push_back(i);
        graph[y].push_back(i);
        from[i] = x;
        to[i] = y;
    }
    in.close();

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

    vector<int> cycle;
    vector<int> s;
    s.push_back(1);
    while (!s.empty()) {
        int node = s.back();
        if (!graph[node].empty()) {
            int e = graph[node].back();
            graph[node].pop_back();
            if (!usedEdgraphe[e]) {
                usedEdgraphe[e] = true;
                int to = ::from[e] ^ ::to[e] ^ node;
                s.push_back(to);
            }
        } else {
            s.pop_back();
            cycle.push_back(node);
        }
    }

    for (int i = 0; i < cycle.size() - 1; ++i) {
        out << cycle[i] << ' ';
    }
    out << '\n';

    out.close();
}