Cod sursa(job #2204036)

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

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

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

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

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

void make_cylce(){
    st.push(1);
    while(!st.empty()){
        auto 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{
            sol.push_back(node);
            st.pop();
        }
    }
}

int main(){
    read_data();
    if(is_euler() == false){
        g << -1 << '\n';
        return 0;
    }
    else{
        make_cylce();
        for(const auto& elem : sol) {
            g << elem << ' ';
        }
    }
    return 0;
}