Cod sursa(job #3286998)

Utilizator VespaOlaru Amelia Vespa Data 14 martie 2025 21:46:07
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
// biperm_2013.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <fstream>
#include <vector>
#include <algorithm>
#define NMAX 100001
#define MMAX 500001
using namespace std;
ifstream cin("ciclueuler.in");
ofstream cout("ciclueuler.out");

vector<int>G[NMAX];
int from[MMAX], to[MMAX];
vector<int>sol,stk;///the cycle and the manually implemented stack
int usededge[MMAX];
void euler(int start)
{
    stk.push_back(start);
    //sol.push_back(start);
    while (!stk.empty())
    {
        int nod = stk.back(); //stk.pop_back();
        //for (auto& i : G[nod])
        if (!G[nod].empty())
        {
            int edgeToCheck = G[nod].back(); G[nod].pop_back();
            if (usededge[edgeToCheck] == 0)
            {
                usededge[edgeToCheck] = 1;
                int next;
                if (nod == from[edgeToCheck])next = to[edgeToCheck];
                else next = from[edgeToCheck];//G here is undirected but the cycle will be directed
                stk.push_back(next);
            }
        }
            else
            {
                stk.pop_back(); sol.push_back(nod);
            }
    }
}



int main()
{
    int n, m; cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y; cin >> x >> y;
        G[x].push_back(i);
        G[y].push_back(i);
        from[i] = x; to[i] = y;//the edge with number i goes from node x to node y
    }
    ///verify if the there is any odd grade
    for (int i = 1; i <= n; i++)
    {
        if (G[i].size() & 1) { cout << -1; return 0; }
    }
    //run smth like a bfs to detect cycles
    euler(1);

    //print the cycle
    int l = sol.size();
    for(int i=0;i<l-1;i++)
    //for (auto& i : sol)
        cout << sol[i] << " ";


    return 0;
}