Cod sursa(job #1511877)

Utilizator spatarelDan-Constantin Spatarel spatarel Data 27 octombrie 2015 11:33:09
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <cstdio>
#include <vector>
#include <stack>

using namespace std;

const int MAXN = 100000;
const int MAXM = 500000;

FILE *f = fopen("ciclueuler.in", "r");
FILE *h = fopen("ciclueuler.out", "w");

//FILE *f = stdin;
//FILE *h = stdout;

int n, m;

struct muchie{
    int nr, vecin;
};

vector<muchie> graf[MAXN + 1];

int grad[MAXN + 1];

int index[MAXN + 1];

bool utilizat[MAXM + 1];

int raspuns[MAXM + 2], k;

stack<int> st;

void ciclu(int x) {
    st.push(x);
    while (!st.empty()) {
        x = st.top();
        bool added = false;
        for (; index[x] < (int)graf[x].size() && !added; ++index[x]) {
            if (!utilizat[graf[x][index[x]].nr]) {
                utilizat[graf[x][index[x]].nr] = true;
                st.push(graf[x][index[x]].vecin);
                added = true;
            }
        }
        if (!added) {
            st.pop();
            raspuns[++k] = x;
        }
    }
}

int main() {
    fscanf(f, "%d%d", &n, &m);
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fscanf(f, "%d%d", &x, &y);
        graf[x].push_back({i, y});
        graf[y].push_back({i, x});
        ++grad[x];
        ++grad[y];
    }
    bool existaSol = true;
    for (int i = 1; i <= n && existaSol; ++i) {
        if(grad[i] & 1) {
            existaSol = false;
        }
    }
    if (existaSol) {
        int i = 1;
        while(grad[i] == 0 && i < n) {
            ++i;
        }
        ciclu(i);
        if (k != m + 1) {
            fprintf(h , "-1\n");
        } else {
            for (int i = 1; i <= m; ++i) {
                fprintf(h, "%d ", raspuns[i]);
            }
        }
    } else {
        fprintf(h , "-1\n");
    }
    return 0;
}