Cod sursa(job #2092536)

Utilizator Robert_VRVRobert Vadastreanu Robert_VRV Data 21 decembrie 2017 21:29:18
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <stdio.h>
#include <vector>
#include <stack>

const int MAX_N = 100000;
const int MAX_M = 500000;

struct Edge {
  int u;
  int v;
  bool visited;

  short int other(int vertex) {
    return u + v - vertex;
  }
};


int n, m, g[1 + MAX_N];
Edge edges[1 + MAX_M];
std::vector<Edge*> neighbours[1 + MAX_N];

int main()
{
  freopen("ciclueuler.in", "r", stdin);
  freopen("ciclueuler.out", "w", stdout);
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= m; i++)  {
    int p, q;
    scanf("%d%d", &p, &q);
    g[p]++;
    g[q]++;
    edges[i] = Edge{p, q, false};
    neighbours[p].push_back(&edges[i]);
    neighbours[q].push_back(&edges[i]);
  }
  for (int i = 1; i <= n; i++)
    if (g[i] % 2 != 0) {
      printf("-1\n");
      return 0;
    }
  std::stack <int> answer;
  answer.push(1);
  int nrsol = 0;
  while (!answer.empty()) {
    int last = answer.top();
    if (!neighbours[last].empty()) {
      if (neighbours[last].back()->visited == false) {
        answer.push(neighbours[last].back()->other(last));
        neighbours[last].back()->visited = true;
      }
      neighbours[last].pop_back();
    }
    else {
      nrsol++;
      if (nrsol <= m)
        printf("%d ", last);
      answer.pop();
    }
  }
  return 0;
}