Cod sursa(job #3215995)

Utilizator iraresmihaiiordache rares mihai iraresmihai Data 15 martie 2024 15:36:30
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <vector>

#define MAXN 500000
using namespace std;

struct node{
  vector <int> neighbours;
  int self;
};

int edge[MAXN];
bool used[MAXN];
int edgeSize;
node graph[MAXN];
FILE *fin, *fout;
vector <int> ans;
vector <int> aux;

void dfs(int pos) {
  aux.push_back(pos);

  while ( aux.size() ) {
    pos = aux.back();
    while ( graph[pos].neighbours.size() && used[graph[pos].neighbours.back()] ) {
      graph[pos].neighbours.pop_back();
    }
    if ( graph[pos].neighbours.size() ) {
      int v = edge[graph[pos].neighbours.back()] - pos;
      used[graph[pos].neighbours.back()] = true;
      aux.push_back(v);
    } else {
      ans.push_back(pos);
      aux.pop_back();
    }
  }
}

void addEdge(int a, int b) {
  if ( a == b ) {
    graph[a].self++;
    return;
  }

  edge[edgeSize] = a + b;
  graph[a].neighbours.push_back(edgeSize);
  graph[b].neighbours.push_back(edgeSize);
  edgeSize++;
}

int main() {
  fin = fopen("ciclueuler.in", "r");
  fout = fopen("ciclueuler.out", "w");

  int n, m, a, b, i;

  fscanf(fin, "%d%d", &n, &m);

  for ( i = 0; i < m; i++ ) {
    fscanf(fin, "%d%d", &a, &b);

    addEdge(a, b);
  }

  for ( i = 0; i < n; i++ ) {
    if ( graph[a].neighbours.size() % 2 ) {
      fprintf(fout, "-1\n");
      return 0;
    }
  }

  i = 0;
  while ( graph[i].neighbours.size() + graph[i].self == 0 ) {
    i++;
  }

  dfs(i);

  for ( i = 0; i < n; i++ ) {
    if ( graph[i].neighbours.size() ) {
      fprintf(fout, "-1\n");
      return 0;
    }
  }

  ans.pop_back();
  for ( int v : ans ) {
    fprintf(fout, "%d ", v);
    while ( graph[v].self ) {
      fprintf(fout, "%d ", v);
      graph[v].self--;
    }
  }
  fprintf(fout, "\n");

  fclose(fin);
  fclose(fout);

  return 0;
}