Cod sursa(job #2814947)

Utilizator stevejobsMihail Popescu stevejobs Data 8 decembrie 2021 20:43:52
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.81 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <functional> 
#include <unordered_map> 
#include <unordered_set> 
#include <queue> 
#include <stack> 
 

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 {
        return (p.first * 1LL * 42894574067ULL) ^ (p.second * 1ll * 92746384501ULL);
    }
};

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) {
//
//    struct stackInfo {
//        int currentNode;
//        int currentIndex;
//    };
//
//    std::stack<stackInfo> s;
//
//    s.push({ 1,0 });
//
//    while (!s.empty()) {
//        auto top = s.top();
//        s.pop();
//
//        int n = top.currentNode;
//        int i = top.currentIndex;
//
//        if (i == la[n].size()) {
//            cycle.push_back(n);
//            continue;
//        }
//
//        s.push({ n, i + 1 });
//
//        int vecin = la[n][i];
//        
//        int p1 = std::min(n, vecin);
//        int p2 = std::max(n, vecin);
//
//        if (edges[{p1, p2}]) {
//            edges[{p1, p2}]--;
//            s.push({ vecin, 0 });
//        }
//    }
//  
//}

void dfs(int x) {
    if (deg[x]) {
        for (const int& i : la[x]) {
            if (deg[i] == 0)continue;
            if (edges[{std::min(x, i), std::max(x, i)}]) {
                edges[{std::min(x, i), std::max(x, i)}]--;
                deg[x]--;
                deg[i]--;
                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]++;

        if (x > y)
            std::swap(x, 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 << ' ';
    }
 
}