Cod sursa(job #2202572)

Utilizator GeorgianBaditaBadita Marin-Georgian GeorgianBadita Data 9 mai 2018 10:01:14
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <algorithm>
#include <stack>
#include <vector>
#define pb push_back
#define NMAX 100005
#define MMAX 500005
using namespace std;

ifstream f("ciclueuler.in");
ofstream g("ciclueuler.out");

int n, m;
vector<int> G[NMAX];
vector<int> cycle;
stack<int> st;

void read_data(int &n, int &m){
    f >> n >> m;
    for(int i = 1; i<=m; i++){
        int x, y;
        f >> x >> y;
        G[x].pb(y);
        G[y].pb(x);
    }
}

int check_euler(){
    for(int i = 1; i<=n; i++){
        if(G[i].size() % 2 != 0){
            return -1;
        }
    }
    return 1;
}

vector<int> make_cyle(){
    vector<int> res;
    int start_node = check_euler();
    st.push(start_node);
    while(!st.empty()){
        int node = st.top();
        if(!G[node].empty()){
            int new_node = G[node].back();
            G[node].pop_back();
            G[new_node].erase(find(G[new_node].begin(), G[new_node].end(), node));
            st.push(new_node);
        }
        else{
            res.pb(node);
            st.pop();
        }
    }
    return res;
}

int main(){
    read_data(n, m);
    if(check_euler() == -1){
        g << "-1\n";
        return 0;
    }
    else{
        auto sol = make_cyle();
        for(const auto& node : sol){
            g << node << ' ';
        }
    }
    return 0;
}