Cod sursa(job #2073161)

Utilizator FrequeAlex Iordachescu Freque Data 22 noiembrie 2017 19:19:50
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>

using namespace std;

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

const int NMAX = 100000 + 5;
const int MMAX = 500000 + 5;

vector <int> graph[NMAX];
stack <int> aux;
queue <int> ans;
int n, m;
int st[MMAX], dr[MMAX];
bool vis_edge[MMAX], vis_node[NMAX];

bool eulerian()
{
    for (int i = 1; i <= n; ++i)
        if (graph[i].size() % 2)
            return 0;
    return 1;
}

bool connected()
{
    for (int i = 1; i <= n; ++i)
        if (!vis_node[i])
            return 0;
    return 1;
}

bool complete()
{
    for (int i = 1; i <= m; ++i)
        if (!vis_edge[i])
            return 0;
    return 1;
}

void bfs()
{
    int nod, next;
    aux.push(1);
    while (!aux.empty())
    {
        nod = aux.top();
        vis_node[nod] = true;

        while (!graph[nod].empty() && vis_edge[graph[nod].back()])
            graph[nod].pop_back();

        if (!graph[nod].empty())
        {
            next = graph[nod].back();
            graph[nod].pop_back();
            vis_edge[next] = true;
            aux.push(st[next] + dr[next] - nod);
        }
        else
        {
            ans.push(nod);
            aux.pop();
        }
    }
}

void read()
{
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> st[i] >> dr[i];
        graph[st[i]].push_back(i);
        graph[dr[i]].push_back(i);
    }
}

void write()
{
    ans.pop();
    while (!ans.empty())
    {
        fout << ans.front() << " ";
        ans.pop();
    }
}

int main()
{
    read();
    if (!eulerian())
    {
        fout << -1;
        return 0;
    }

    bfs();

    if (connected() && complete())
        write();
    else
        fout << -1;

    return 0;
}