Cod sursa(job #2121065)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 3 februarie 2018 11:36:33
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <stack>
#include <bitset>
using namespace std;

const int MAXM = 500005;
const int MAXN = 100005;

int n, m;

struct M{
  int x, y;
  bool removed;
  M() : removed(0) { }
};

vector<M> muchii;
vector<int> graf[MAXN];
stack<int> st;

class InParser {
private:
    FILE *fin;
    char *buff;
    int sp;

    char read_ch() {
        ++sp;
        if (sp == 4096) {
            sp = 0;
            fread(buff, 1, 4096, fin);
        }
        return buff[sp];
    }

public:
    InParser(const char* nume) {
        fin = fopen(nume, "r");
        buff = new char[4096]();
        sp = 4095;
    }

    InParser& operator >> (int &n) {
        char c;
        while (!isdigit(c = read_ch()) && c != '-');
        int sgn = 1;
        if (c == '-') {
            n = 0;
            sgn = -1;
        } else {
            n = c - '0';
        }
        while (isdigit(c = read_ch())) {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }

    InParser& operator >> (long long &n) {
        char c;
        n = 0;
        while (!isdigit(c = read_ch()) && c != '-');
        long long sgn = 1;
        if (c == '-') {
            n = 0;
            sgn = -1;
        } else {
            n = c - '0';
        }
        while (isdigit(c = read_ch())) {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }
};

int main() {
  InParser inp("ciclueuler.in");
  freopen("ciclueuler.out", "w", stdout);

  inp>>n>>m;

  M k;
  for (int i = 0; i < m; i++) {
    inp>>k.x>>k.y;
    muchii.push_back(k);
    graf[k.x].push_back(i);
    graf[k.y].push_back(i);
  }

  for (int i = 1; i <= n; i++)
    if (graf[i].size() % 2) {
      printf("-1\n");
      exit(0);
    }

  st.push(1);

  while (!st.empty()) {
    int x = st.top();

    if (!graf[x].empty()) {
      int it = graf[x].front();
      graf[x].erase(graf[x].begin(), graf[x].begin() + 1);

      if(!muchii[it].removed) {
        muchii[it].removed = 1;
        int toAdd = x != muchii[it].x ? muchii[it].x : muchii[it].y;
        st.push(toAdd);
        continue;
      }
    } else {
      st.pop();
      printf("%d ", x);
    }
  }

  return 0;
}