Cod sursa(job #2593471)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 3 aprilie 2020 23:28:37
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>

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

vector<vector<int>> Graph;

bool BFS(int k, int N)
{
  queue<int> Q;
  vector<bool> used;
  used.resize(N);
  Q.push(k);
  used[k] = true;
  while (!Q.empty()) {
    k = Q.front();
    Q.pop();
    for (auto v: Graph[k])
      if (!used[v]) {
	used[v] = true;
	Q.push(v);
      }
  }

  for (int i = 0; i < N; ++i)
    if (used[i] == false)
      return true;

  return false;
}

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

      Graph[k].pop_back(); // 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].emplace_back(to);
    Graph[to].emplace_back(from);
  }

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

  euler(0);
  
  return 0;
}