Cod sursa(job #2154371)

Utilizator andra_moldovanAndra Moldovan andra_moldovan Data 6 martie 2018 21:47:14
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <vector>
#include <stack>

#define MAXN 100005
#define MAXM 500005

using namespace std;

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

struct str{
    int node, poz;
};

vector <str> graph[MAXN];
stack <int> st;
int viz[MAXN], g[MAXN], N, M, fr[MAXM];

inline void Read() {
    int x, y;

    fin >> N >> M;

    for (int i = 1;  i <= M; i++) {
        fin >> x >> y;

        graph[x].push_back({y, i});
        graph[y].push_back({x, i});

        g[x]++; g[y]++;
    }
}

inline void Euler(int start) {
    int z, ok = 0;

    st.push(start);

    while (!st.empty()) {
        z = st.top();

        if (!g[z]) {
            if (ok == 0) {
                ok = 1;
            }
            else {
                fout << z << " ";
            }
            st.pop();
        }
        else {
            int l = graph[z].size() - 1;

            while (fr[graph[z][l].poz]) {
                graph[z].pop_back();
                l--;
            }

            fr[graph[z][l].poz] = 1; g[z]--; g[graph[z][l].node]--;

            st.push(graph[z][l].node);
        }
    }
}

inline void Solve() {
    int ok = 1, contor = 0;

    for (int i = 1; i <= N; i++) {
        if (g[i] % 2 == 1) {
            ok = 0;
            break;
        }
    }

    if (ok == 0) {
        fout << -1; return;
    }

    Euler(1);

}

int main() {
    Read();
    Solve();

    fin.close(); fout.close(); return 0;
}