Cod sursa(job #1142656)

Utilizator alexclpAlexandru Clapa alexclp Data 14 martie 2014 00:30:32
Problema Ciclu Eulerian Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream in ("ciclueuler.in");
ofstream out ("ciclueuler.out");

const int N = 100009;

struct Muchie {
  int first;
  int second;
};

Muchie getMuchie (int x, int y)
{
  Muchie m;
  m.first = x;
  m.second = y;
  return m;
}

int noduri, muchii;

vector <int> indici[N]; 

bool folosit[N*5];

int ciclu[N*5];
int elementeCiclu;

bool vizitat[N];

Muchie v[N*5];

void read()
{
  in >> noduri >> muchii;

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

    indici[x].push_back(i);
    indici[y].push_back(i);

    v[i] = getMuchie(x, y);
  }
}

inline int varf (int nod, int valoare)
{
  if (v[nod].first == valoare) {
    return v[nod].second;
  }
  return v[nod].first;
}

inline void euler (int x)
{
  for (vector<int>::iterator it = indici[x].begin(); it < indici[x].end(); ++it) {
    int indice = *it;
    if (!folosit[indice]) {
      folosit[indice] = true;
      int y = varf(indice, x);
      euler(y);
    }
  }
  ciclu[++elementeCiclu] = x;
}

void dfs (int x)
{
  vizitat[x] = true;

  for (auto it = indici[x].begin(); it < indici[x].end(); ++it) {
    int y = *it;
    if (!vizitat[y]) {
      dfs(y);
    }
  }
}

bool check ()
{
  dfs(1);

  for (int i = 1; i <= noduri; ++i) {
    if (!vizitat[i] or indici[i].size() % 2) {
      return false;
    }
  }
  return true;
}

void solve ()
{
  bool ok = check();

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

  euler(1);

  //out << elementeCiclu << "\n";

  if (elementeCiclu == muchii + 1) {
    for (int i = 1; i <= muchii; ++i) {
      out << ciclu[i] << " ";
    }
    out << "\n";
  } else {
    out << "-1\n";
  }
}

int main()
{
  read();
  solve();

  return 0;
}