Cod sursa(job #896961)

Utilizator Impaler_009Mihai Nitu Impaler_009 Data 27 februarie 2013 18:13:09
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>
using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");

struct node
{
    int nr;
    node *next;
    node *prev;
} *list[100001],*eul;

int n,m,deg[100001],i,stack[5000010],k,y,x;
bool vis [100001];

void create_graph ()
{
    int a,b; node *d;
    fin>>a>>b;
    d=new node;
    d->nr=a;
    d->next=list[b];
    list[b]=d;
    d=new node;
    d->nr=b;
    d->next=list[a];
    list[a]=d;
    deg[a]++;
    deg[b]++;
}

void DFS (int x)
{
    vis[x]=1;
    node *dfs=list[x];
    while (dfs)
    {
        if (vis[dfs->nr]==0) DFS(dfs->nr);
        dfs=dfs->next;
    }
}

bool eulerian ()
{
    for (int i=1;i<=n;i++) if (deg[i]%2) return 0;
    DFS (1);
    for (int i=1;i<=n;i++) if (!vis[i]&&deg[i]>0) return 0;
    return 1;
}

void delete_paralel_edge (int x, int y)
{
    node *d,*t;
    d=list[y];
    if (d->nr==x) list[y]=list[y]->next;
    else {while (d->next->nr!=x) d=d->next;
    t=d->next;  d->next=d->next->next; delete t;}
}

void eulerian_circuit (int x, node* eul)
{
    node *d; int y;

}

int main()
{
    node *d,*lf,*displ;
    fin>>n>>m;
    for (i=1;i<=m;i++) create_graph ();
    if (!eulerian()) {fout<<-1; return 0;}
    eul=new node;
    displ=eul;
    eul->nr=1; eul->next=NULL;
    stack[1]=1; k=1;
    while (k>0)
    {
        if (list[stack[k]]==NULL) {k--;eul=eul->prev;}
        else
        {
        int x=stack[k];
        y=list[x]->nr;
        d=list[x];
        list[x]=list[x]->next;
        delete d;
        delete_paralel_edge (x,y);
        stack[++k]=y;
        d=new node; d->nr=y;
        lf=eul->next;
        if (lf!=NULL) lf->prev=d;
        d->next=lf; d->prev=eul;
        eul->next=d;
        eul=eul->next;
        }
    }
    while (displ) {fout<<displ->nr<<" "; displ=displ->next;}
}