Cod sursa(job #1526451)

Utilizator spatarelDan-Constantin Spatarel spatarel Data 16 noiembrie 2015 12:09:31
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <cstdio>
#include <stack>
#include <vector>

using std::stack;
using std::vector;

const int MAX_N = 100000;
const int MAX_M = 500000;

struct Muchie {
  int index;
  int vecin;
};

int M = 0, grad[1 + MAX_N];
bool vizitatM[MAX_M];
vector <Muchie> G[1 + MAX_N];
stack <int> stiva;

bool sePoate;
vector <int> solutie;

void adaugare(int u, int v) {
  grad[u]++;
  grad[v]++;
  G[u].push_back(Muchie{M, v});
  G[v].push_back(Muchie{M, u});
  M++;
}

int stergereVecin(int u) {
  while (!G[u].empty() && vizitatM[G[u].back().index]) {
    G[u].pop_back();
  }
  if (!G[u].empty()) {
    vizitatM[G[u].back().index] = true;
    int v = G[u].back().vecin;
    G[u].pop_back();
    M--;
    grad[u]--;
    grad[v]--;
    return v;
  } else {
    return 0;
  }
}

int main()
{
  //freopen("ciclueuler.in", "r", stdin);
  //freopen("ciclueuler.out", "w", stdout);
  int n, m;
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= m; i++)
  {
    int u, v;
    scanf("%d %d", &u, &v);
    adaugare(u, v);
  }
  sePoate = true;
  for (int i=1; i<=n; i++)
    if (grad[i] % 2 == 1)
      sePoate = false;
  if (sePoate) {
    int i;
    for (i = 1; grad[i] == 0; i++);
    stiva.push(i);
    while (!stiva.empty())
    {
      int nod = stiva.top();
      if (grad[nod] != 0)
        stiva.push(stergereVecin(nod));
      else
      {
        solutie.push_back(nod);
        stiva.pop();
      }
    }
    if (M > 0)
      sePoate = false;
  }
  if (sePoate) {
    for (int i = 0; i < (int)solutie.size() - 1; i++)
    {
      printf("%d ", solutie[i]);
    }
    printf("\n");
  } else {
    printf("-1\n");
  }
  return 0;
}