Cod sursa(job #2165558)

Utilizator vladvlad00Vlad Teodorescu vladvlad00 Data 13 martie 2018 12:39:37
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>

using namespace std;

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

struct nod
{
    int x;
    nod*urm;
};

typedef nod* lista;

void DFS(int x);
void ins(lista &L, int nr);
void del(lista &L, int nr);

int n, m, vf, uz[100005], gr[100005], S[500005];
lista L[100005];

int main()
{
    int i, aux, x, y;

    fin >> n >> m;
    for (i=1;i<=m;i++)
    {
        fin >> x >> y;
        ins(L[x],y);
        ins(L[y],x);
        gr[x]++;
        gr[y]++;
    }
    DFS(1);
    for (i=1;i<=n;i++)
        if (gr[i]%2 || !uz[i])
        {
            fout << -1 << '\n';
            return 0;
        }
    S[++vf] = 1;
    while (vf)
    {
        aux = S[vf];
        if (L[aux])
        {
            S[++vf] = L[aux]->x;
            del(L[L[aux]->x],aux);
            del(L[aux],L[aux]->x);
        }
        else
        {
            if (vf > 1)
                fout << aux << ' ';
            vf--;
        }
    }
    return 0;
}

void ins(lista &L, int nr)
{
    nod *p = new nod;

    p->x = nr;
    p->urm = L;
    L = p;
}

void del(lista &L, int nr)
{
    nod *p, *q;
    if (L->x == nr)
    {
        p = L;
        L = L->urm;
        delete p;
    }
    else
    {
        p = L;
        q = p->urm;
        while (q->x != nr)
        {
            p = p->urm;
            q = q->urm;
        }
        p->urm = q->urm;
        delete q;
    }
}

void DFS(int x)
{
    nod*p;

    uz[x] = 1;
    p = L[x];
    while (p)
    {
        if (!uz[p->x])
            DFS(p->x);
        p = p->urm;
    }
}