Cod sursa(job #2814996)

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

using namespace std;

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

vector<pair<int, int>> la[100005];
int n, m;
int rang[100005];
int edge_used[500005];

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

node* current_node = nullptr;

void dfs(int from)
{
    for (auto& per: la[from])
    {
        int to = per.first;
        // daca mai avem muchii de la from la to
        if (edge_used[per.second])
            continue;

        edge_used[per.second] = 1;

        // foloseste muchia
        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, m});
        if (x != y)
            la[y].push_back({x, m});
        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;
}