Cod sursa(job #2814858)

Utilizator stevejobsMihail Popescu stevejobs Data 8 decembrie 2021 18:19:07
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <functional> 
#include <unordered_map> 
#include <unordered_set> 
#include <queue> 
 

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

int n, m;

struct pair_hash {
    std::size_t operator () (const std::pair<int, int>& p) const {
        auto h1 = std::hash<int>{}(p.first);
        auto h2 = std::hash<int>{}(p.second);
        return h1 ^ h2;
    }
};

typedef std::pair<int, int> iPair;

std::vector<std::vector<int> > la;
std::unordered_map<iPair, int, pair_hash> edges;
std::vector<int> cycle;
std::vector<int> deg;

void dfs(int x) {
    for (int i : la[x]) {
        int p1 = std::min(x, i);
        int p2 = std::max(x, i);
        if (edges[{p1, p2}] > 0) {
            edges[{p1, p2}]--;
            dfs(i);
        }
    }
    cycle.push_back(x);
}


bool checkEuler() {
    for (int i = 1; i <= n; ++i)
        if (deg[i] & 1) return false;

    std::queue<int> q;
    q.push(1);
    std::vector<bool>used(n + 1);
    used[1] = 1;

    while (!q.empty()) {
        int t = q.front();
        q.pop();
        for(int i : la[t])
            if (!used[i]) {
                used[i] = 1;
                q.push(i);
            }
    }

    for (int i = 1; i <= n; ++i)
        if (!used[i])return false;

    return true;
}

int main() {
    f >> n >> m;
    la.resize(n + 1);
    deg.resize(n + 1);
    for (int i = 0; i < m; ++i) {
        int x, y;
        f >> x >> y;
        deg[x]++;
        deg[y]++;
        edges[{x, y}]++;
        if (edges[{x, y}] == 1) {
            la[x].push_back(y);
            if(y != x)
                la[y].push_back(x);
        }
    }
 
    if (!checkEuler()) {
        g << -1;
    }
    else {
        dfs(1);
        cycle.pop_back();
        for (int i : cycle)
            g << i << ' ';
    }
}