Cod sursa(job #2814980)

Utilizator realmeabefirhuja petru realmeabefir Data 8 decembrie 2021 22:03:46
Problema Ciclu Eulerian Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

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

struct hash_pair {
    template <class T1, class T2>
    size_t operator()(const pair<T1, T2>& p) const
    {
        auto hash1 = hash<T1>{}(p.first);
        auto hash2 = hash<T2>{}(p.second);
        return hash1 ^ hash2;
    }
};

vector<int> la[100005];
int n, m;
int rang[100005];
unordered_map<pair<int,int>, int, hash_pair> edge_map;

struct node
{
    node* prev = nullptr;
    node* next = nullptr;
    int val;
};

node* current_node = nullptr;

void dfs(int from)
{
    for (auto& to: la[from])
    {
        // daca mai avem muchii de la from la to
        if (edge_map[{min(from,to), max(from,to)}] == 0)
            continue;


        // foloseste muchia
        edge_map[{min(from,to), max(from,to)}] --;
        node* new_node = new node({current_node, current_node->next, to});
        current_node->next = new_node;
        current_node = new_node;
        dfs(to);
    }

    current_node = current_node->prev;
}

int main()
{
    in >> n >> m;
    while (m --)
    {
        int x, y;
        in >> x >> y;
        la[x].push_back(y);
        if (x != y)
            la[y].push_back(x);
        edge_map[{min(x,y), max(x,y)}] ++;
        rang[x] ++;
        rang[y] ++;
    }
    int impare = 0;
    int impar;
    for (int i = 1; i <= n; i++)
    {
        if (rang[i] % 2 == 1)
        {
            impare ++;
            impar = i;
        }
    }
    int s = 1;
    if (impare == 2)
        s = impar;
    else if (impare == 0)
        s = 1;
    else
    {
        out << -1;
        return 0;
    }

    node* start = new node({nullptr, nullptr, s});
    current_node = start;

    dfs(s);

    current_node = start;
    while (current_node->next != nullptr)
    {
        out << current_node->val << ' ';
        current_node = current_node->next;
    }

    return 0;
}