Cod sursa(job #2593477)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 3 aprilie 2020 23:35:49
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <set>

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

vector<multiset<int>> Graph;

void euler(int k)
{
  stack<int> S;
  do {  
    while (Graph[k].size()) {
      int v = (*Graph[k].begin());

      Graph[k].erase(Graph[k].begin()); // remove {k,v}
      Graph[v].erase(find(begin(Graph[v]), end(Graph[v]), k)); // remove {v,k}

      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].insert(to);
    Graph[to].insert(from);
  }

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

  euler(0);
  
  return 0;
}