Cod sursa(job #2653214)

Utilizator TeodorLuchianovTeo Luchianov TeodorLuchianov Data 27 septembrie 2020 12:59:59
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

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

int const NMAX = 1e5;
int const MMAX = 5e5;

struct Edge {
  int from;
  int to;
  bool deleted;
};

int n, m, start;
Edge edges[1 + MMAX];
vector <int> g[1 + NMAX];  //g[i] in loc sa fie un nod este un index de muchie
bool visited[1 + NMAX];

void dfs(int from) {
  visited[from] = true;
  for(int i = 0; i < g[from].size(); i++) {
    int to = edges[g[from][i]].to + edges[g[from][i]].from - from;
    if(!visited[to]) {
      dfs(to);
    }
  }
}

bool exists() {
  int ncc = 0;
  for(int i = 1; i <= n; i++) {
    if(g[i].size() > 0 && !visited[i]) {
      ncc++;
      start = i;
      dfs(i);
    }
    if(g[i].size() % 2 == 1) {
      return false;
    }
  }
  return (ncc == 1);
}

vector<int> output;

void euler(int from) {
  while(!g[from].empty()) {
    int e = g[from].back();
    g[from].pop_back();
    if(edges[e].deleted == false){
      edges[e].deleted = true;
      int to = edges[e].to + edges[e].from - from;
      //cerr << from << " - " << eIndex << " -> " << to << '\n';
      euler(to);
    }
  }
  output.push_back(from);
}

int main() {
  in >> n >> m;
  for(int i=1; i<=m; i++) {
    int a, b;
    in >> a >> b;
    edges[i] = {a, b, 0};
    g[a].push_back(i);
    g[b].push_back(i);
  }
  if(exists()) {
    euler(start);
    for(int i = 0; i < output.size() - 1; i++) {
      out << output[i] << ' ';
    }
  } else {
    out << -1;
  }
  return 0;
}