Cod sursa(job #3320380)

Utilizator PaulTPaul Tirlisan PaulT Data 5 noiembrie 2025 17:02:40
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
#include <unordered_set>
using namespace std;

using VP = vector<pair<int, int>>;
using VVP = vector<VP>;

int n, m;
VVP G;
stack<int> stk;

void Read();
vector<int> Cycle(int x);

int main()
{
    Read();
    
    ofstream fout("ciclueuler.out");
    for (int x = 1; x <= n; ++x)
        if (G[x].size() & 1)
        {
            fout << -1;
            return 0;
        }

    const vector<int> result = Cycle(1);
    
    if ((int)result.size() <= m)
        fout << -1;
    else
        for (size_t i = 0u; i + 1 < result.size(); ++i)
            fout << result[i] << ' ';
}

vector<int> Cycle(int x)
{
    vector<int> result;
    vector<VP::iterator> edges(n + 1);
    unordered_set<int> seenEdges;
    result.reserve(m);

    for (int i = 1; i <= n; ++i)
        edges[i] = G[i].begin();

    stk.push(x);
    while (!stk.empty())
    {
        x = stk.top();
        if (edges[x] == G[x].end())
        {
            stk.pop();
            result.push_back(x);
        }
        else
        {
            const auto [y, e] = *edges[x];
            edges[x]++;
            if (seenEdges.find(e) != seenEdges.end())
                continue;
            seenEdges.insert(e);
            stk.push(y);
        }
    }
    
    return result;
}

void Read()
{
    ifstream fin("ciclueuler.in");
    fin >> n >> m;
    G = VVP(n + 1);
    
    int x, y;
    for (int i = 0; i < m; ++i)
    {
        fin >> x >> y;
        G[x].emplace_back(y, i);
        G[y].emplace_back(x, i);
    }
    
    fin.close();
}