Cod sursa(job #1377280)

Utilizator radarobertRada Robert Gabriel radarobert Data 5 martie 2015 20:59:37
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
#include <list>
#include <queue>

using namespace std;

const int MAXN = 100002;

int n, m;
bool vis[MAXN];
bool first = true;
list<int> g[MAXN];
queue<int> q;
ofstream out("ciclueuler.out");

void bfs()
{
    q.push(1);
    vis[1] = 1;
    int x;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        for (list<int>::iterator it = g[x].begin(); it != g[x].end(); it++)
            if (!vis[*it])
            {
                vis[*it] = 1;
                q.push(*it);
            }
    }
}

void deleteEdge(int v, int w)
{
    for (list<int>::iterator it = g[w].begin(); it != g[w].end(); it++)
        if (*it == v)
        {
            it = g[w].erase(it);
            break;
        }
}

void euler(int x)
{
    int y;
    while (!g[x].empty())
    {
        y = g[x].front();
        g[x].pop_front();
        deleteEdge(x, y);
        euler(y);
    }
    if (first)
        first = false;
    else
        out << x << ' ';
}

int main()
{
    ifstream in("ciclueuler.in");

    in >> n >> m;
    for (int x, y, i = 1; i <= m; i++)
    {
        in >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    bfs();

    bool conex = true;
    for (int i = 1; i <= n; i++)
        if (!vis[i])
        {
            conex = false;
            break;
        }

    bool eulerian = true;
    for (int i = 1; i <= n; i++)
        if (g[i].size() % 2 == 1)
        {
            eulerian = false;
            break;
        }
    if (conex == false || eulerian == false)
    {
        out << "-1\n";
        return 0;
    }

    euler(1);
    out << '\n';

    return 0;
}