Cod sursa(job #2579498)

Utilizator GeorgianBaditaBadita Marin-Georgian GeorgianBadita Data 12 martie 2020 15:31:32
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include<fstream>
#include<vector>
#include<stack>
#include<algorithm>
#define NMAX 100005

//in-out
std::ifstream f("ciclueuler.in");
std::ofstream g("ciclueuler.out");

//data
std::stack<int> cycleStack;
std::vector<int> G[NMAX];
std::vector<int> cycle;
int n, m;

//read-data
void readData(){
    f >> n >> m;
    int x, y;
    for(int i = 0; i<m; i++){
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

//check if a graph has an euler cycle or path
bool isEuler(){
    for(int i = 1; i<=n; i++){
        if(G[i].size() % 2 != 0){
            return false;
        }
    }
    return true;
}

//construct cycle
void constructCycle(){
    cycleStack.push(1);

    while(!cycleStack.empty()){
        int node = cycleStack.top();

        if(G[node].size()){
            int newNode = G[node].back();
            G[node].pop_back();
            cycleStack.push(newNode);
            G[newNode].erase(std::find(G[newNode].begin(), G[newNode].end(), node));
        }else{
            cycle.push_back(node);
            cycleStack.pop();
        }
    }
}

int main(){
    readData();
    if(!isEuler()){
        g << -1;
        return 0;
    }
    constructCycle();
    cycle.pop_back();
    for(const auto& elem : cycle){
        g << elem << ' ';
    }
    return 0;
}