Cod sursa(job #2814955)

Utilizator stevejobsMihail Popescu stevejobs Data 8 decembrie 2021 21:07:51
Problema Ciclu Eulerian Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.42 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;
 
typedef unsigned long long ULL;

std::vector<std::vector<int> > la;
std::unordered_map<ULL, int> 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 });

        if (edges[(std::min(n, la[n][i]) << 18) | std::max(n, la[n][i])]) {
            edges[(std::min(n, la[n][i]) << 18) | std::max(n, la[n][i])]--;
            s.push({ la[n][i], 0 });
        }
    }
  
}

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