Cod sursa(job #2527412)

Utilizator nicolaefilatNicolae Filat nicolaefilat Data 20 ianuarie 2020 12:11:15
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <assert.h>

const int MAXN = 100000 + 1;

using namespace std;

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

bool viz[500005];
int grad[MAXN];
int stiva[5*MAXN];
vector<pair<int,int> >graf[500005];
int n,m;

void dfs(int nod){
    for(auto pereche : graf[nod]){
        int curent = pereche.first;
        int label = pereche.second;
        if(!viz[label]){
            viz[label] = true;
            dfs(curent);
            out<<nod<<" ";
        }
    }

}
void dfs_stiva(int start){
    int varf = 0;
    stiva[++varf] = start;
    while(varf > 0){
        bool are_vecini = false;
        int nod = stiva[varf];
        int sz = graf[nod].size();
        for(int i = 0; i < sz; ++i){
            int curent = graf[nod][i].first;
            int label = graf[nod][i].second;
            if(!viz[label]){
                are_vecini = true;
                viz[label] = true;
                stiva[++varf] = curent;
                break;
            }
        }
        if(!are_vecini){
            --varf;
            out<<nod<<' ';
        }
    }
}

int main()
{
    in.tie(0);
    out.tie(0);
    ios::sync_with_stdio(false);
    in>>n>>m;
    int muchii = 0;
    for(int i = 1; i <= m; ++i){
        int x,y;
        in>>x>>y;
        graf[x].emplace_back(make_pair(y,++muchii));
        graf[y].emplace_back(make_pair(x,muchii));
        ++grad[x];
        ++grad[y];
    }
    bool ok = true;
    for(int i = 1; i <= n && ok; ++i)
        if(grad[i] % 2)
            ok = false;
    if(!ok){
        out<<-1;
        return 0;
    }
    dfs_stiva(1);
    return 0;
}