Cod sursa(job #2988082)

Utilizator AndreiBadAndrei Badulescu AndreiBad Data 3 martie 2023 16:04:39
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
//
//  main.cpp
//  Ciclu Eulerian (infoarena)
//
//  Created by Andrei Bădulescu on 03.03.23.
//

#include <fstream>
#include <bitset>
#include <vector>
#include <stack>

using namespace std;

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

const int N = 1e5;
const int M = 5e5;

struct edge {
    int x, y;
};

bitset <M> deleted;
vector <int> edges[N + 1];
vector <int> solution;
stack <int> calls;

edge e[M];
int last[N + 1];

int n, m;

bool degCheck() {
    for (auto i = 1; i <= n; i++) {
        if ((edges[i].size() & 1)) {
            return false;
        }
    }

    return true;
}

int other(edge m, int current) {
    return (m.x + m.y - current);
}

void euler() {
    calls.push(e[0].x);

    while (!calls.empty()) {
        int current = calls.top();
        int index = -1;

        while (last[current] < edges[current].size() && index == -1) {
            if (!deleted[edges[current][last[current]]]) {
                index = last[current];
            }

            last[current]++;
        }

        if (index != -1) {
            int next = other(e[index], current);
            deleted[index] = true;
            calls.push(next);
        } else {
            calls.pop();
            solution.push_back(current);
        }
    }
}

int main() {
    cin >> n >> m;

    for (auto i = 0; i < m; i++) {
        cin >> e[i].x >> e[i].y;

        edges[e[i].x].push_back(e[i].y);
        edges[e[i].y].push_back(e[i].x);
    }

    euler();

    if ((int)solution.size() != m + 1 || !degCheck()) {
        cout << -1;
    } else {
        for (int i = 0; i < solution.size() - 1; i++) {
            cout << solution[i] << ' ';
        }
    }

    return 0;
}