Cod sursa(job #2254287)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 4 octombrie 2018 22:48:12
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include "bits/stdc++.h"

using namespace std;

const int NMax = 100005;

int n,m,x,y;
int grad[NMax], viz[5 * NMax];
vector<pair<int,int> > G[NMax];
stack<int> st;

int main(){
  ifstream cin("ciclueuler.in");
  ofstream cout("ciclueuler.out");
  cin >> n >> m;
  for(int i = 1; i <= m; ++i){
    cin >> x >> y;
    G[x].push_back(make_pair(y,i));
    G[y].push_back(make_pair(x,i));
    grad[x] ++;
    grad[y] ++;
  }
  for(int i = 1; i <= n; ++i){
    if(grad[i] & 1){
      //no eulerian cycle
      cout << -1 << '\n';
      return 0;
    }
  }
  int k = 0;
  st.push(1);
  while(!st.empty()){
    int node = st.top();
    while(G[node].size() > 0 && viz[G[node].back().second] == 1){
      G[node].pop_back();
    }
    if(G[node].size() == 0){
      k++;
      if(k > m){
        break;
      }
      cout << node << ' ';
      st.pop();
    }else{
      int new_node = G[node].back().first;
      viz[G[node].back().second] = 1;
      G[node].pop_back();
      st.push(new_node);
    }
  }
}