Cod sursa(job #2755915)

Utilizator popashtefan10Popa Stefan popashtefan10 Data 28 mai 2021 19:33:12
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <cstdio>
#include <vector>

using namespace std;

const int NMAX = 100000;
const int MMAX = 500000;

struct muchie {
  int nod1, nod2;

  muchie(int _nod1 = 0, int _nod2 = 0) : nod1(_nod1), nod2(_nod2) {}

  int other(int nod) {
    return nod1 + nod2 - nod;
  }
};

int n, m;
int grad[NMAX + 5];
bool uz[MMAX + 5];
muchie muchii[MMAX + 5];
vector<int> v[NMAX + 5];

void read() {
  int x, y;

  scanf("%d %d", &n, &m);
  for(int i = 1; i <= m; i++) {
    scanf("%d %d", &x, &y);
    muchii[i] = muchie(x, y);
    v[x].push_back(i);
    v[y].push_back(i);
    grad[x]++;
    grad[y]++;
  }
}

bool eulerian() {
  for(int i = 1; i <= n; i++)
    if(grad[i] % 2 == 1)
      return false;
  return true;
}

void find_eulerian_cycle() {
  int stk[MMAX + 5];
  int top = 0;

  stk[++top] = 1;
  while(top) {
    int nod = stk[top];
    while(!v[nod].empty() && uz[v[nod].back()])
      v[nod].pop_back();

    if(v[nod].empty()) {
      printf("%d ", nod);
      top--;
    }
    else {
      int m_idx = v[nod].back();
      int vec = muchii[m_idx].other(nod);
      stk[++top] = vec;
      uz[m_idx] = true;
    }
  }
}

int main() {
  freopen("ciclueuler.in", "r", stdin);
  freopen("ciclueuler.out", "w", stdout);

  read();
  if(eulerian())
    find_eulerian_cycle();
  else
    printf("-1");

  return 0;
}