Cod sursa(job #2428132)

Utilizator pickleVictor Andrei pickle Data 3 iunie 2019 22:07:12
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < n; i++)
#define repa(i, l, r) for (int i = l; i < r; i++)
#define repd(i, r, l) for (int i = r; i > l; i--)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int Nmax = 100555;
const int Mmax = 500555;
ifstream fin ("ciclueuler.in");
ofstream fout ("ciclueuler.out");

vi G[Nmax];
char used[Mmax];
int from[Mmax], to[Mmax];

int main(void) {
  int N,M,a,b;
  fin >> N >> M;
  for(int i = 1; i <= M; i++) {
    fin >> a >> b;
    from[i] = a;
    to[i] = b;
    G[a].push_back(i);
    G[b].push_back(i);
  }
  for(int i = 1; i <= N; i++)
    if (G[i].size() & 1) {
      fout << -1 << endl;
      return 0;
    }

  vi res;
  stack<int> st;
  st.push(from[1]);
  while(!st.empty()) {
    int v = st.top();

    while(G[v].size() && used[G[v].back()]) { G[v].pop_back(); }

    if (G[v].size() == 0) {
      st.pop();
      res.push_back(v);
    } else {
      int e = G[v].back();
      used[e] = 1;
      int dest = v ^ from[e] ^ to[e]; // destination is the other end of the edge e (the vertex that is not v)
      st.push(dest);
    }
  }

  if (res.size() != M+1) {
    fout << -1 << endl;
    return 0;
  } else {
    for(int i = 0; i < M; i++)
      fout << res[i] << ' ';
    fout << endl;
  }

  return 0;
}