Cod sursa(job #2259728)

Utilizator manutrutaEmanuel Truta manutruta Data 13 octombrie 2018 18:04:30
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

#define MAX 100010

using namespace std;

ofstream g("ciclueuler.out");
#define cout g

vector<int> G[MAX];
vector<int> sol;
stack<int> s;

FILE *f = fopen("ciclueuler.in", "r");
#define maxb 8192
char buf[maxb];
int ptr = maxb - 1;
int getInt()
{
    int nr = 0;
    while (buf[ptr] < '0' || '9' < buf[ptr])
    {
        if (++ptr >= maxb)
        {
            fread(buf, maxb, 1, f);
            ptr = 0;
        }
    }

    while ('0' <= buf[ptr] && buf[ptr] <= '9')
    {
        nr = nr * 10 + buf[ptr] - '0';
        if (++ptr >= maxb)
        {
            fread(buf, maxb, 1, f);
            ptr = 0;
        }
    }
    return nr;
}

void euler(int node_arg)
{
    s.push(node_arg);
    while (!s.empty())
    {
        int node = s.top();

        if (!G[node].empty())
        {
            int nnode = G[node][0];
            G[node].erase(G[node].begin());
            G[nnode].erase(find(G[nnode].begin(), G[nnode].end(), node));
            s.push(nnode);
            continue;
        }
        sol.push_back(node);

        s.pop();
    }
}

int main()
{
    int n, m;
    n = getInt();
    m = getInt();
    for (int i = 0; i < m; ++i)
    {
        int x, y;
        x = getInt();
        y = getInt();
        G[x].push_back(y);
        G[y].push_back(x);
    }

    bool eulerian = true;
    for (int i = 1; i <= n; ++i)
    {
        if (G[i].size() % 2 != 0)
        {
            eulerian = false;
        }
    }

    if (eulerian)
    {
        euler(1);
        if (sol.size() - 1 == m)
        {
            for (int i = 0; i < sol.size() - 1; ++i)
            {
                cout << sol[i] << ' ';
            }
        }
        else
        {
            cout << -1 << '\n';
        }
    }
    else
    {
        cout << -1 << '\n';
    }

    return 0;
}