Cod sursa(job #2520962)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 10 ianuarie 2020 00:36:35
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int Nmax = 100000, Mmax = 500000;

vector <int> g[Nmax + 5], sol;
stack <int> st;
int n, m, node, other, edge;
int from[Mmax + 5], to[Mmax + 5];
bool usenode[Nmax + 5], useedge[Mmax + 5];

void Read(){
    fin >> n >> m;
    int x, y;
    for (int i = 1; i <= m; i++){
        fin >> x >> y;
        g[x].push_back(i);
        g[y].push_back(i);
        from[i] = x;
        to[i] = y;
    }
}

void DFS(int node){
    usenode[node] = 1;
    for (auto i : g[node]){
        other = from[i] ^ to[i] ^ node;
        if (!usenode[other])
            DFS(other);
    }
}

int Check(){
    DFS(1);
    for (int i = 1; i <= n; i++)
        if (g[i].size() % 2 || (g[i].size() && !usenode[i]))
            return 0;
    return 1;
}

void Cycle(int node){
    while (!g[node].empty()){
        edge = g[node].back();
        g[node].pop_back();
        if (useedge[edge])
            continue;
        st.push(node);
        useedge[edge] = 1;
        other = from[edge] ^ to[edge] ^ node;
        node = other;
    }
}

void Solve(){
    node = 1;
    do{
        Cycle(node);
        node = st.top();
        st.pop();
        sol.push_back(node);
    }while (!st.empty());
}

void Print(){
    for (auto i : sol)
        fout << i << ' ';
    fout << '\n';
}

int main(){
    Read();
    if (!Check()){
        fout << -1 << '\n';
        return 0;
    }
    Solve();
    Print();
    return 0;
}