Cod sursa(job #2076821)

Utilizator CammieCamelia Lazar Cammie Data 27 noiembrie 2017 10:28:07
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 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 varf, poz;
};

vector <str> graph[MAXN];
stack <int> st;

int n, m, g[MAXN], viz[MAXN], 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 DFS(int nod) {
    viz[nod] = 1;

    for (auto x : graph[nod]) {
        if (!viz[x.varf])
            DFS(x.varf);
    }
}

inline void Solve() {
    int aux;

    for (int i = 1; i <= n; i++) {
        if (!viz[i]) {
            DFS(i);
            aux = i;
        }
    }

    for (int i = 1; i <= n; i++) {
        if (g[i] % 2 == 1) {
            fout << -1;
            return;
        }
    }

    st.push(aux);
    int z, x, afis = 0;

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

        if (g[z] == 0) {
            if (afis == 0)
                afis = 1;
            else fout << z << " ";
            st.pop();
        }
        else {
            x = graph[z].size() - 1;

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

            g[z]--; g[graph[z][x].varf]--;
            fr[graph[z][x].poz] = 1;
            st.push(graph[z][x].varf);
        }
    }
}

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

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