Cod sursa(job #2416586)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 27 aprilie 2019 18:58:25
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005, MAXM = 500005;

vector<pair<int, int> > graf[MAXN];
vector<int> ans;
int grad[MAXN];
bool viz[MAXM];
stack<int> ciclu;

int main()
{
    ifstream fin("ciclueuler.in");
    ofstream fout("ciclueuler.out");
    int n, m, x, y;
    fin >> n >> m;
    for(int i = 1; i <= m; ++i){
        fin >> x >> y;
        grad[x]++;
        grad[y]++;
        graf[x].push_back({y, i});
        graf[y].push_back({x, i});
    }
    bool ok = 1;
    for(int i = 1; i <= n; ++i)
        if(grad[i] % 2 || grad[i] == 0)
            ok = 0;
    if(ok){
        ciclu.push(1);
        while(!ciclu.empty()){
            int nod = ciclu.top();
            if(graf[nod].size()){
                int son = graf[nod].back().first, edge = graf[nod].back().second;
                graf[nod].pop_back();
                if(!viz[edge]){
                    viz[edge] = 1;
                    ciclu.push(son);
                }
            }
            else{
                ans.push_back(nod);
                ciclu.pop();
            }
        }
        ans.pop_back();
        for(auto x : ans)
            fout << x << " ";
    }
    else fout << -1;
    return 0;
}