Cod sursa(job #3284757)

Utilizator BledeaAlexBledea Alexandru BledeaAlex Data 12 martie 2025 10:05:21
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;

const int N_MAX = 1e5 + 5, M_MAX = 5e5 + 5;
int N, M;
bool visited[M_MAX];

struct Edge
{
    int v;
    int id;

    Edge(int _v, int _id) :
        v(_v), id(_id) { }
};

vector<Edge> G[N_MAX];
vector<int> Ans;

void SetInput(string name)
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    (void)!freopen((name + ".in").c_str(), "r", stdin);
    (void)!freopen((name + ".out").c_str(), "w", stdout);
}

void ReadInput()
{
    cin >> N >> M;
    for(int i = 1, u, v; i <= M; i++)
    {
        cin >> u >> v;

        G[u].emplace_back(v, i);
        G[v].emplace_back(u, i);
    }
}

bool HasEulerianCycle() /// OBS: we know the graph is conex already. Otherwise you have to check that too
{
    for(int i = 1; i <= N; i++)
        if(G[i].size() % 2 == 1)
            return false;

    return true;
}

void FindEulerianCycle(int v)
{
    while(not G[v].empty())
    {
        auto [u, id] = G[v].back();

        G[v].pop_back();

        if(not visited[id])
        {
            visited[id] = true;
            FindEulerianCycle(u);
        }
    }

    Ans.push_back(v);
}

void Solve()
{
    if(HasEulerianCycle())
    {
        FindEulerianCycle(1);
        Ans.pop_back(); /// We don't need to write the last edge, which finishes the cycle
        for(const int& v : Ans)
            cout << v << ' ';
    }
    else
        cout << "-1\n";
}

int main()
{
    SetInput("ciclueuler");

    ReadInput();
    Solve();

    return 0;
}