Cod sursa(job #2509342)

Utilizator altcontnoualt cont altcontnou Data 14 decembrie 2019 10:02:19
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<int>graf[100005];
stack<int>s;
int n, m, from, to, ind_muchie, marime, grade[100005];
bool viz[500005];
pair<int,int>muchii[500005];

void solve(int ind)
{
//    marime=graf[ind].size();
//    s.push(ind);
//    for (int i=marime-1; i>=0; --i)
//    {
//        if (viz[graf[ind][i]]==1)
//            graf[ind].pop_back(), marime--;
//        else
//            break;
//    }
//    if (graf[ind].empty())
//    {
//        cout << ind <<' ';
//        s.pop();
//        return;
//    }
//    int indice;
//    for (int i=marime-1; i>=0; --i)
//    {
//        viz[graf[ind][i]]=1;
//        graf[ind].pop_back();
//        if (muchii[graf[ind][i]].first==ind)
//            {
//                indice=muchii[graf[ind][i]].second;
//                solve(indice);
//            }
//        else
//            {
//                indice=muchii[graf[ind][i]].first;
//                solve(indice);
//            }
//    }
    s.push(ind);
    while (!graf[ind].empty() && viz[graf[ind].back()]==1)
        graf[ind].pop_back();
    while (!s.empty())
    {
        if (graf[s.top()].empty())
        {
            from=s.top();
            s.pop();
            if (!s.empty())
                g << from <<' ';
        }
        else
            {
                while (!graf[s.top()].empty() && viz[graf[s.top()].back()]==1)
                    graf[s.top()].pop_back();
                int indice=s.top();
                if (!graf[indice].empty()){
                viz[graf[indice].back()]=1;
                pair<int,int>pereche=muchii[graf[indice].back()];
                graf[indice].pop_back();
                if (pereche.first==indice)
                    solve(pereche.second);
                else
                    solve(pereche.first);
                }
            }

    }

}

int main()
{
    f >> n >> m;
    for (int i=1; i<=m; ++i)
    {
        f >> from >> to;
        muchii[++ind_muchie]= {from,to};
        graf[from].push_back(ind_muchie);
        graf[to].push_back(ind_muchie);
        grade[from]++;
        grade[to]++;
    }
    for (int i=1; i<=n; ++i)
    {
        if (grade[i]%2==1)
        {
            g << -1;
            return 0;
        }
    }
    solve(1);
    return 0;
}