Cod sursa(job #1420507)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 18 aprilie 2015 16:34:29
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
// Ciclu eulerian - O(N+M) - RECURSIV
#include <fstream>
#include <bitset>
#include <vector>
#define Nmax 100009
#define Mmax 500009
#define pb push_back
#define x first
#define y second
using namespace std;

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

typedef pair<int,int> PP;


int N, M;
vector<int> G[Nmax]; /* matricea de adiacenta */
vector<int> Cycle; /* ciclul eulerian */
PP E[Mmax]; /* E[i] = (x, y) este muchia cu nr i */
bitset < Mmax > viz; /* viz[i] = 1 <=> am trecut deja pe muchia i */

void ReadInput() {
  fin >> N >> M;
  for (int i = 1; i <= M; i++) {
    int x, y;
    fin >> x >> y;
    E[i]=PP(x, y);
    G[x].pb(i);
    G[y].pb(i);
  }
}

inline bool AdmiteCiclu() {
  // sa aiba toate nodurile cu grad par
  for (int i = 1; i <= N; i++) {
    if (G[i].size()&1) {
      return 0;
    }
  } 
  return 1;
}

inline void DFS(const int& node) {
  for (vector<int>::iterator it = G[node].begin(); it!=G[node].end();it++) {
    if (!viz[*it]) {
      // Trec in celalalt capat al muchiei
      viz[*it] = 1;
      DFS(E[*it].x + E[*it].y - node); 
    }    
  }
  Cycle.pb(node);
}

int main() {
  ReadInput();

  if (AdmiteCiclu()) {
    DFS(1); // fac ciclul

    //afisez
    for (vector<int>::iterator it = Cycle.begin(); it!=Cycle.end();it++) {
      fout << *it << ' ';
    }
    fout << '\n';

  } else {
    fout << -1 << '\n';
  }
  fin.close();
  fout.close();
  return 0;
}