Cod sursa(job #2593482)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 3 aprilie 2020 23:44:05
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <tuple>
#include <bitset>

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

vector<vector<pair<int, int>>> Graph;
bitset<500005> used;

void euler(int k)
{
  stack<int> S;
  do {  
    while (Graph[k].size()) {
      int v, index;
      tie(v, index) = Graph[k].back();
      Graph[k].pop_back(); // remove {k,v}
      if (used[index])
	continue;
      used[index] = true;
      S.push(k);
      k = v; // go in depth
    }

    k = S.top();
    S.pop();

    fout << k + 1 << " ";
  } while (!S.empty());
  fout << "\n";
}

int main()
{
  fin.sync_with_stdio(false);
  fout.sync_with_stdio(false);
  fin.tie(0);
  fout.tie(0);
  
  int N, M;
  fin >> N >> M;
  Graph.resize(N);
  
  for (int i = 0; i < M; ++i) {
    int from, to;
    fin >> from >> to;
    --from; --to;
    Graph[from].emplace_back(to, i);
    Graph[to].emplace_back(from, i);
  }

  for (auto it : Graph)
    if (it.size() % 2 == 1) {
      fout << "-1\n"; // odd degree, can't have cycle
      return 0;
    }

  euler(0);
  
  return 0;
}