Cod sursa(job #1529305)

Utilizator serbanSlincu Serban serban Data 20 noiembrie 2015 18:54:41
Problema Ciclu Eulerian Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

using namespace std;

vector<int> L[100005];
int l[100005];
bool v[100005];

deque<int> q;

bool viz[100005];
void dfs(int node) {
    viz[node] = true;
    for(int i = 0; i < L[node].size(); i ++) {
        if(!viz[L[node][i]]) {
            dfs(L[node][i]);
        }
    }
}

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

    int n, m, x, y;
    f >> n >> m;
    for(int i = 1; i <= m; i ++) {
        f >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    bool ok = true;
    for(int i = 1; i <= n; i ++) {
        l[i] = L[i].size();
        if(l[i] & 1)
            ok = false;
    }
    if(!ok) {
        g << "-1\n";
        return 0;
    }
    //verific conexitate
    dfs(1);
    for(int i = 1; i <= n; i ++)
        if(!viz[i]) ok = false;
    if(!ok) {
        g << "-1\n";
        return 0;
    }

    q.push_back(1);
    while(!q.empty()) {
        int a = q.back();
        q.pop_back();
        g << a << " ";
        if(l[a]) {
            int node = L[a][l[a] - 1];
            for(int j = 0; j < l[node]; j ++) {
                if(L[node][j] == a) {
                    L[node][j] = L[node][l[node] - 1];
                    l[node] --;
                    j = l[node];
                }
            }
            l[a] --;
            if(l[node])
                q.push_back(node);
        }

    }
    g << "\n";

    return 0;
}