Cod sursa(job #2551519)

Utilizator Alin_StanciuStanciu Alin Alin_Stanciu Data 19 februarie 2020 21:40:04
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

int n, m, I[100001];
vector<int> G[100001], R;
vector<pair<int, int>> M;
stack<int> S;
bool V[500001];

void Dfs()
{
    S.push(1);
    while (!S.empty())
    {
        int x = S.top();
        bool gasit = false;
        for (int i = I[x]; i < G[x].size(); ++i)
        {
            int ind = G[x][i];
            if (!V[ind])
            {
                V[ind] = true;
                S.push(M[ind].first == x ? M[ind].second : M[ind].first);
                I[x] = i + 1;
                gasit = true;
                break;
            }
        }
        if (!gasit)
        {
            S.pop();
            R.push_back(x);
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 0; i < m; ++i)
    {
        int x, y;
        fin >> x >> y;
        M.emplace_back(x, y);
        G[x].push_back(i);
        G[y].push_back(i);
    }
    for (int i = 1; i <= n; ++i)
    {
        if (G[i].size() == 0 || G[i].size() % 2 == 1)
        {
            fout << -1;
            return 0;
        }
    }
    Dfs();
    for (int i = 1; i < R.size(); ++i)
        fout << R[i] << " ";

    return 0;
}