Cod sursa(job #532587)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 11 februarie 2011 23:05:57
Problema Ciclu Eulerian Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.57 kb
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#define N 100001
#define M 500001
typedef struct stack
{long st[N],sp;};
typedef struct nod
{long info;
nod *next;}Nod,*list;
long a,b,i,j,k,n,m,s[N]={0},t;
list l,p,g[N];
stack q;

void push(stack &q,long x)
{q.st[++q.sp]=x;}

long pop(stack &q)
{return q.st[q.sp--];}

void add(list &q,long x)
{Nod *nou=new Nod;
nou->info=x;
nou->next=q;
q=nou;}

int contine(list &q,long x)
{Nod *p;
for(p=q;p!=NULL;p=p->next)
if(p->info==x)
      return 1;
return 0;}

void del(list &l,long x)
{Nod *p=l,*q=l;
while(p!=NULL&&p->info!=x)
      {q=p;
      p=p->next;}
if(p!=NULL)
      {if(q==p)
             l=l->next;
      else
             q->next=p->next;
      free(p);}}

void ciclu(list &p,list &u,long x)
{list q=new nod;
int gasit;
long i;
q->info=x;
q->next=NULL;
p=u=q;
do
      {gasit=0;
      for(i=1;i<=n&&gasit==0;i++)
      if(contine(g[u->info],i)==1&&contine(g[i],u->info)==1)
              {del(g[u->info],i);
              del(g[i],u->info);
              q=new nod;
              q->info=i;
              q->next=NULL;
              k++;
              u->next=q;
              u=q;
              gasit=1;}}
while(p->info!=u->info);
u->next=0;}

long cauta(list &q)
{while(q!=NULL)
         {if(g[q->info]!=NULL)
                 return q->info;
         q=q->next;}
return 0;}

int grade_pare(list g[N],long n)
{long i=1,s=0;
list p;
int gasit=0;
while(i<=n&&!gasit)
      {for(p=g[i];p!=NULL;p=p->next)
             s++;
      if(s%2==1)
             gasit=1;
      i++;}
return (!gasit);}

void df(list g[N],long i)
{long j;
list p;
stack q;
q.sp=0;
push(q,i);
while(q.sp!=0)
       {j=pop(q);
       s[j]=1;
       for(p=g[j];p!=NULL;p=p->next)
       if(s[p->info]==0)
              push(q,p->info);}}

int conex(list g[N],long s[N])
{long i;
int gasit=0;
df(g,1);
for(i=1;i<=n;i++)
if(s[i]==0)
      gasit=1;
return (!gasit);}

int main()
{ifstream f1("ciclueuler.in");
ofstream f2("ciclueuler.out");
f1>>n>>m;
for(j=1;j<=n;j++)
      g[j]=NULL;
for(i=1;i<=m;i++)
      {f1>>a>>b;
      add(g[a],b);
      add(g[b],a);}
k=1;
if(conex(g,s)==1&&grade_pare(g,n)==1)
      {Nod *p=NULL,*u,*w;
      ciclu(p,u,1);
      Nod *p1=NULL,*u1;
      while(k<m)
            {Nod *q=p;
            int x=cauta(q);
            ciclu(p1,u1,x);
            u1->next=q->next;
            q->next=p1->next;}
      for(w=p;w->next!=NULL;w=w->next)
            f2<<w->info<<" ";}
else
      f2<<"-1";
f1.close();
f2.close();
return 0;}