Cod sursa(job #1758110)

Utilizator crushackPopescu Silviu crushack Data 16 septembrie 2016 16:22:21
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <list>
#include <stack>

using namespace std;

typedef vector<list<int>> Graph;

void delete_edge(Graph& graph, int a, int b) {
  graph[a].erase(find(graph[a].begin(), graph[a].end(), b));
  graph[b].erase(find(graph[b].begin(), graph[b].end(), a));
}

vector<int> euler(Graph& graph) {
  vector<int> ans;
  stack<int> st;
  st.push(1);

  for (auto node : graph) {
    if (node.size() & 1) {
      return vector<int>();
    }
  }

  while (!st.empty()) {
    int node = st.top();

    if (!graph[node].empty()) {
      int adj = *graph[node].begin();
      delete_edge(graph, node, adj);
      st.push(adj);
    } else {
      ans.push_back(node);
      st.pop();
    }
  }

  return ans;
}

int main() {
  Graph graph;
  ifstream fin("ciclueuler.in");
  ofstream fout("ciclueuler.out");
  int n, m;

  fin >> n >> m;
  graph.resize(n + 1);
  for (int e = 0; e < m; ++e) {
    int x, y;
    fin >> x >> y;
    graph[x].push_back(y);
    graph[y].push_back(x);
  }

  auto ans = euler(graph);

  if (ans.size() == 0) {
    fout << -1 << "\n";
    return 0;
  }

  if (n > 1) {
    ans.erase(ans.end() - 1);
  }

  for (int elem : ans) {
    fout << elem << " ";
  }
  fout << "\n";

  return 0;
}