Cod sursa(job #3005483)

Utilizator pifaDumitru Andrei Denis pifa Data 17 martie 2023 00:21:15
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

int n, m;

const int N = 5e5 + 5;

vector <pair <int, int>> g[N];

int vis[N];

vector <int> cycle;

stack <int> st;

void euler(int node)
{
    st.push(node);
    for(int i = 1; i <= m; i++)
    {
        int node = st.top();
        while(g[node].size())
        {
            pair <int, int> curr = g[node].back();
            g[node].pop_back();
            if(vis[curr.second] == 0)
            {
                vis[curr.second] = 1;
                node = curr.first;
                st.push(node);
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        in >> x >> y;
        g[x].push_back({y, i});
        g[y].push_back({x, i});
    }
    for(int i = 1; i <= n; i++)
    {
        if(g[i].size() % 2 == 1)
        {
            out << -1;
            return 0;
        }
    }
    euler(1);
    vector <int> cycle;
    while(st.size())
    {
        cycle.push_back(st.top());
        st.pop();
    }
    cycle.pop_back();
    for(auto x:cycle)
        out << x << ' ';
    return 0;
}