Cod sursa(job #1706711)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 23 mai 2016 00:21:12
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>

using namespace std;

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

int n, m, x, y, i;
vector <int> ls[100005];
bool viz[100005];
int fiu, nod, l;
stack <int> stiva;

void df(int k){
    int i, l = ls[k].size();
    viz[k] = 1;
    for (i = 0; i < l; i++){
        if (viz[ ls[k][i] ] == 0 && viz[ ls[k][i] ] != k)
            df(ls[k][i]);
    }
}

int main(){
    f >> n >> m;
    for (i = 1; i <= m; i++){
        f >> x >> y;
        ls[x].push_back(y);
        ls[y].push_back(x);
    }
    df(1);
    for (i = 1; i <= n; i++){
        if (viz[i] == 0){
            g << "-1";
            return 0;
        }
        if (ls[i].size()%2 == 1){
            g << "-1";
            return 0;
        }
    }

    stiva.push(1);
    while (stiva.empty() == 0){
        nod = stiva.top(), l = ls[nod].size();
        if (l == 0){
            g << nod << ' ';
            stiva.pop();
            continue;
        }

        fiu = ls[nod][l-1];
        ls[nod].pop_back();
        ls[fiu].erase(find(ls[fiu].begin(), ls[fiu].end(), nod));
        stiva.push(fiu);
    }

    return 0;
}