Cod sursa(job #2866225)

Utilizator vladburacBurac Vlad vladburac Data 9 martie 2022 14:34:34
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1e5;

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

map <int,int> edges[NMAX+1];
stack <int> cpath;
stack <int> epath;
int grad[NMAX+1];

int main() {
  int n, m, i, j, a, b;
  fin >> n >> m;
  for( i = 0; i < m; i++ ) {
    fin >> a >> b;
    edges[a][b]++;
    if( a != b )
      edges[b][a]++;
    grad[a]++;
    grad[b]++;
  }
  i = 1;
  while( i <= n && grad[i] % 2 == 0 )
    i++;
  if( i <= n )
    fout << -1;
  else {
    cpath.push( 1 );
    while( !cpath.empty() ) {
      if( grad[cpath.top()] == 0 ) {
        epath.push( cpath.top() );
        cpath.pop();
      }
      else {
        grad[cpath.top()]--;
        grad[edges[cpath.top()].begin()->first]--;
        int u = edges[cpath.top()].begin()->first;
        if( edges[cpath.top()][u] == 1 )
          edges[cpath.top()].erase( u );
        else
          edges[cpath.top()][u]--;
        if( u != cpath.top() ) {
          if( edges[u][cpath.top()] == 1 )
            edges[u].erase( cpath.top() );
          else
            edges[u][cpath.top()]--;
        }
        cpath.push( u );
      }
    }
  }
  while( !epath.empty() ) {
    if( epath.size() != 1 )
      fout << epath.top() << " ";
    epath.pop();
  }
  return 0;
}