Cod sursa(job #2079481)

Utilizator TherevengerkingSurani Adrian Therevengerking Data 1 decembrie 2017 14:11:40
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
#define pb push_back
#define pii pair<int ,int>
#define x first
#define y second
const int Nmax = 100000 + 5;
const int Mmax = 500000 + 5;
int n, m, g[Nmax];
bool fol[Nmax], viz[Nmax];
vector<pii>v[Nmax];
stack<int>st;
void dfs(int nod)
{
    viz[nod] = 1;
    for(auto i : v[nod])
        if(!viz[i.x])dfs(i.x);
}
int main()
{
    fin >> n >> m;
    for(int i = 1, a, b; i <= m; ++i)
    {
        fin >> a >> b;
        v[a].pb({b, i});
        v[b].pb({a, i});
        g[a]++;
        g[b]++;
    }
    dfs(1);
    for(int i = 1; i <= n; ++i)
        if(g[i] % 2 || !viz[i])
        {
            fout << -1;
            return 0;
        }

    st.push(1);

    bool ft = 0;
    while(!st.empty())
    {
        int nod = st.top();

        if(g[nod] == 0)
        {
            if(!ft)ft = 1;
            else fout << nod << " ";
            st.pop();
        }
        else
        {
            while(fol[v[nod].back().y])
                v[nod].pop_back();
            int fiu = v[nod].back().x;
            g[nod]--; g[fiu]--;
            fol[v[nod].back().y] = 1;
            v[nod].pop_back();
            st.push(fiu);
        }
    }
    return 0;
}