Cod sursa(job #2701240)

Utilizator FredyLup Lucia Fredy Data 30 ianuarie 2021 10:55:34
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>
#include <fstream>

using namespace std;

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

#define limn 100001
int n, m;
int nod, dr, nodVec;
list <int> G[limn];
int st[5*limn]; ///stiva pt a simula recursivitatea

int main()
{
    int x, y;

    /// citire graf
    fin>>n>>m;
    for(int i=0; i<m; i++)
    {
        fin>>x>>y;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    /// graduri impare pt noduri => graful nu poate avea ciclu eulerian
    for(int i=1; i<=n; i++)
        if(G[i].size() == 0 || G[i].size()%2)
        {
            fout<<-1;
            return 0;
        }


    /// verificam daca graful are ciclu eulerian
    dr = 0;
    st[++dr] = 1; /// incepem din nodul 1
    while(dr)
    {
        nod = st[dr];
        while(!G[nod].empty())
        {
            nodVec = G[nod].front(); /// selectam un vecin aleator al lui nod, stergem muchia nod-nodVec
            G[nod].pop_front();
            G[nodVec].erase( find(G[nodVec].begin(), G[nodVec].end(), nod) );
            st[++dr] = nodVec; /// adaugam vecinul in stiva
            nod = nodVec;
        }
        fout<<st[dr]<<' ';
        dr--;
    }


    fin.close();
    return 0;
}