Cod sursa(job #2374187)

Utilizator Dragne.Andrei11Dragne Andrei Dragne.Andrei11 Data 7 martie 2019 17:24:17
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax=100005;

struct numere
{
    int nod;
    int poz;
};

int grad[nmax];
bool vis[5*nmax];

deque <int> rasp;
stack <int> st;
vector <numere> g[nmax];

void dfs(int start_node)
{
    st.push(start_node);
    for(int i=0; i<g[start_node].size(); i++)
    {
        if(vis[g[start_node][i].poz]==false)
        {
            grad[start_node]--;
            grad[g[start_node][i].nod]--;
            vis[g[start_node][i].poz]=true;
            dfs(g[start_node][i].nod);
        }
    }
    while(!st.empty())
    {
        if(grad[st.top()]!=0)
            break;
        rasp.push_back(st.top());
        st.pop();
    }
}

int main()
{
    freopen("ciclueuler.in", "r", stdin);
    freopen("ciclueuler.out", "w", stdout);
    int n, m;

    scanf("%d%d", &n, &m);
    for(int i=1; i<=m; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        grad[x]++;
        grad[y]++;
        if(x!=y)
        {
            if(grad[x]%2==1)
                grad[0]++;
            else
                grad[0]--;
            if(grad[y]%2==1)
                grad[0]++;
            else
                grad[0]--;
        }
        numere k;
        k.nod=x;
        k.poz=i;
        g[y].push_back(k);
        k.nod=y;
        g[x].push_back(k);
    }
    if(grad[0]!=0)
    {
        printf("-1\n");
        return 0;
    }
    dfs(1);
    rasp.pop_front();
    while(rasp.size())
    {
        printf("%d ", rasp.back());
        rasp.pop_back();
    }

    return 0;
}