Cod sursa(job #2757778)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 6 iunie 2021 14:53:26
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

const int NMAX = 1e5;

int n, m;
std::vector<int> graph[1 + NMAX];

std::queue<int> q;
bool vis[1 + NMAX];

std::vector<int> stack;
std::vector<int> ans;

void bfs(int src) {
  q.push(src);
  vis[src] = true;

  while (!q.empty()) {
    auto node = q.front();
    q.pop();

    for (auto& nb: graph[node]) {
      if (!vis[nb]) {
        q.push(nb);
        vis[nb] = true;
      }
    }
  }
}

bool has_euler_cycle() {
  for (int i = 1; i <= n; ++i) {
    if (graph[i].size() % 2 != 0)
      return false;
  }

  bfs(1);

  for (int i = 1; i <= n; ++i) {
    if (!vis[i])
      return false;
  }

  return true;
}

inline void del(int node, int next) {
  graph[node].pop_back();

  for (auto& i: graph[next]) {
    if (i == node) {
      std::swap(i, graph[next].back());
      graph[next].pop_back();
      break;
    }
  }
}

void dfs() {
  int node = stack.back();

  while (!graph[node].empty()) {
    int next = graph[node].back();

    del(node, next);

    node = next;

    stack.push_back(node);
  }
}

void solve() {
  stack.push_back(1);

  dfs();

  while (!stack.empty()) {
    if (graph[stack.back()].empty()) {
      ans.push_back(stack.back());

      stack.pop_back();
    }
    else
      dfs();
  }
}

int main() {
  std::ifstream in("ciclueuler.in");
  std::ofstream out("ciclueuler.out");

  in >> n >> m;

  for (int i = 1; i <= m; ++i) {
    int x, y;
    in >> x >> y;

    graph[x].push_back(y);
    graph[y].push_back(x);
  }

  if (!has_euler_cycle()) {
    out << "-1\n";
    return 0;
  }

  ans.reserve(1 + m);
  solve();

  ans.pop_back();
  for (auto& i: ans)
    out << i << ' ';

  return 0;
}