Cod sursa(job #2777857)

Utilizator MindralexMindrila Alex Mindralex Data 25 septembrie 2021 13:27:58
Problema Ciclu Eulerian Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int maxVal = 100001;

int n, grad[maxVal];

struct nod
{
  int info;
  nod * urm;
}* v[maxVal];

void adaugare (int x, int y)
{
  nod * t = new nod;
  t -> info = y;
  t -> urm = v[x];
  v[x] = t;
}

void citire ()
{
  int m;
  fin >> n >> m;
  for (int i = 1; i <= m; i++)
  {
    int x, y;
    fin >> x >> y;
    adaugare (x, y);
    adaugare (y, x);
    grad[x]++, grad[y]++;
  }

}

void dfs (int x, int vizitat[])
{
  vizitat[x] = 1;
  nod * t = v[x];
  while (t)
  {
    if (vizitat[t -> info] == 0)
    dfs(t -> info, vizitat);
    t = t -> urm;
  }
}

bool is_eulerian ()
{
  for (int i = 1; i <= n; i++)
    if (grad[i] % 2 != 0)
      return false;
  int vizitat[maxVal] = {0};
  dfs (1, vizitat);
  for (int i = 1; i <= n; i++)
    if (vizitat[i] == 0)
      return false;
  return true;
}

void delete_nod (int x, int y) // din lista lui x sterge nodul cu valoarea y
{
  if (v[x] -> info == y)
  {
    nod * aux = v[x];
    v[x] = v[x] -> urm;
    delete aux;
  }
  else
  {
    nod * aux = v[x];
    while (aux -> urm -> info != y)
      aux = aux -> urm;
    
    nod * aux2 = aux -> urm;
    aux -> urm = aux -> urm -> urm;
    delete aux2;
  }
}

int main ()
{
  citire();
  if (is_eulerian())
  {
    int stiva[500001], k = 1;
    stiva[k] = 1;
    int a[maxVal], i = 0;
    while (k)
    {
      nod * t = v[stiva[k]];
      if (t)
      {
        stiva[++k] = t -> info;
        
        nod * aux = v[stiva[k - 1]];
        v[stiva[k - 1]] = v[stiva[k - 1]] -> urm;
        delete(aux);

        nod * p = v[stiva[k]];
        while (p)
        {
          if (p -> info == stiva[k-1])
          {
            delete_nod(stiva[k], p -> info);
          }
          p = p -> urm;
        }
      }
      else a[++i] = stiva[k--];
    }
    for (int j = 1; j < i; j++)
      fout << a[j] << ' ';
  }
  else
    fout << -1;
  return 0;
}