Cod sursa(job #3204152)

Utilizator AlbertPavPavalache Albert AlbertPav Data 15 februarie 2024 19:16:04
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
const int NMAX = 100001;

struct muchie
{
    int x, y;
};

vector<int>G[NMAX], L;
vector<muchie>M;
vector<bool>elim;
stack<int>S;

int n, m;

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

void citire()
{
    int x, y;
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> y;
        M.push_back({x, y});
        elim.push_back(0);
        G[x].push_back(M.size() - 1);
        G[y].push_back(M.size() - 1);
    }
}

void Euler()
{
    int v, x, p;
    S.push(1);
    while(!S.empty())
    {
        v = S.top();
        if(G[v].size() > 0)
        {
            x = G[v].back();
            G[v].pop_back();
            if(!elim[x])
            {
                elim[x] = 1;
                p = M[x].y;
                if(p == v)
                    p = M[x].x;
                S.push(p);
            }
        }
        else
        {
            L.push_back(v);
            S.pop();
        }
    }
}

int main()
{
    bool ok = 1;
    citire();
    for(int i = 1; i <= n && ok; i++)
        if(G[i].size() & 1)
            ok = 0;
    if(ok)
    {
        Euler();
        for(int i = L.size() - 1; i >= 1; i--)
            g << L[i] << ' ';
    }
    else
        g << "-1\n";
    f.close();
    g.close();
    return 0;
}