Cod sursa(job #1628962)

Utilizator SmaugSmaug . Smaug Data 4 martie 2016 11:50:25
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAXN = 1e5 + 5;
const int MAXM = 5 * 1e5 + 5;

int n, m, odd, where = 1;
int x[MAXM], y[MAXM];
vector<int> g[MAXN], r;
bool vis[MAXM];
stack<int> stk;

int main() {
  fin >> n >> m;
  for (int i = 1; i <= m; ++i) {
    fin >> x[i] >> y[i];
    g[x[i]].push_back(i);
    g[y[i]].push_back(i);
  }
  for (int i = 1; i <= n; ++i) {
    odd += g[i].size() % 2;
    if (g[i].size() % 2 == 1) {
      where = i;
    }
  }
  if (odd != 0 && odd != 2) {
    fout << "-1\n";
    return 0;
  }
  stk.push(where);
  for (; !stk.empty(); ) {
    int node = stk.top();
    bool ok = true;
    while (g[node].size()) {
      int now = g[node].back();
      g[node].pop_back();
      if (!vis[now]) {
        vis[now] = true;
        stk.push(x[now] + y[now] - node);
        ok = false;
        break;
      }
    }
    if (ok) {
      r.push_back(node);
      stk.pop();
    }
  }
  r.pop_back();
  for (int i = 1; i <= m; ++i) {
    if (!vis[i]) {
      fout << "-1\n";
      return 0;
    }
  }
  for (const auto i : r) {
    fout << i << ' ';
  }
  fout << '\n';
  fout.close();
  return 0;
}