Cod sursa(job #2259745)

Utilizator manutrutaEmanuel Truta manutruta Data 13 octombrie 2018 18:46:57
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 kb
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>

#define MAX 100010
#define MAXM 500010
#define x first
#define y second

using namespace std;

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

vector< pair<int, int> > G[MAX];
vector<int> sol;
stack<int> s;
bitset<MAXM> viz;

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())
    {
        here:
        int node = s.top();

        while (!G[node].empty())
        {
            int nnode = G[node][G[node].size() - 1].x;
            if (viz[G[node][G[node].size() - 1].y])
            {
                G[node].pop_back();
                continue;
            }
            viz[G[node][G[node].size() - 1].y] = 1;
            G[node].pop_back();

            s.push(nnode);
            goto here;
        }
        sol.push_back(node);

        s.pop();
    }
}

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

    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;
}