Cod sursa(job #556944)

Utilizator rusu_raduRusu Radu rusu_radu Data 16 martie 2011 13:15:40
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.48 kb
#include <cstdio>
#include <cassert>
#include <vector>
#define Nmax 100005
#define InFile "ciclueuler.in"
#define OutFile "ciclueuler.out"
#define pb push_back

using namespace std;

int n, m, Mcl, Vmax=1;
int Nx[6*Nmax], V[6*Nmax], Pr[Nmax];
int viz[Nmax], gr[Nmax], cl[Nmax];
vector <int> A[Nmax];

void read();
int verif ();
void DFS (int);
void create_cicle (int nd,int);
void kill (int x, int y);
void write();
void solve();

int main()
{
  assert (freopen (InFile, "r", stdin));
  assert (freopen (OutFile, "w", stdout));
  read();
  if (!verif ()){
    printf ("-1\n");
    return 0;
  }
  else
    solve();
  write();
  return 0;
}

void read()
{
  int i, x, y;
  scanf ("%d %d\n", &n, &m);
  for (i=1; i<=m; i++){
    scanf ("%d %d\n", &x, &y);
    A[x].pb (y), gr[x]++;
    A[y].pb (x), gr[y]++;
  }
}

int verif ()
{
  int i;
  for (i=1; i<=n; i++)
    if (gr[i]%2==1)
      return 0;
  DFS (1);
  for (i=1; i<=n; i++)
    if (!viz[i])
      return 0;
  return 1;
}

void DFS (int nd)
{
  int i, lg=A[nd].size();
  viz[nd]=1;
  for (i=0; i<lg; i++)
    if (!viz[A[nd][i]])
      DFS (A[nd][i]);
}

void solve()
{
  int i=1, Ax, Pz=1, Pzc, nd, Poz;
  V[Vmax]=1; Pr[Vmax]=1; Nx[Vmax++]=Vmax;
  create_cicle (1, 1);
  while (Mcl<m)
  {
    for (; i<=n; i++)
      if (gr[i]>0 && cl[i])
      {
        nd=i;
        //Pz=1;
        while (V[Pz]!=nd) Pz=Nx[Pz];
        Pzc=Vmax;
        Ax=Nx[Pz];
        create_cicle (nd, Pz);
        break;
      }
    //unite them
    Nx[Pz]=Pzc;
    Pr[Pzc]=Pz;
    Poz=Vmax-1;
    Nx[Poz]=Ax;
    Pr[Ax]=Poz;
    //Nx[Pr[Pzc]]=Nx[Pz];
    //PrNx[Pz]]=Pr[Pzc];
    //Nx[Vmax-1]=Pz;
  }
}

void create_cicle (int nd, int Poz)
{
  int spy, i, lg, x, y, Pzs, Pzf;
  spy=nd;
  /*V[Vmax]=nd,*/ Pzs=Poz/*, Nx[Vmax++]=Vmax*/;
  do
  {
    cl[spy]=1;
    lg=A[spy].size();
    for (i=0; i<lg; i++)
      if (A[spy][i])
      {
        x=spy; y=A[spy][i];
        A[spy][i]=0; gr[x]--;
        gr[y]--; Mcl++;
        kill (y, x);
        V[Vmax]=y, Pzf=Vmax, Pr[Vmax]=Vmax, Nx[Vmax++]=Vmax;
        Nx[Pzs]=Pzf;
        Pr[Pzf]=Pzs;
        Pzs=Pzf;
        spy=y;
        break;
      }
  }
  while (spy!=nd);
}

void kill (int x, int y)
{
  int i, lg=A[x].size();
  for (i=0; i<lg; i++)
    if (A[x][i]==y){
      A[x][i]=0;
      return;
    }
}

void write()
{
  int i, Pz=1;
  for (i=1; i<=m; i++)
  {
    printf ("%d ", V[Pz]);
    Pz=Nx[Pz];
  }
}