Cod sursa(job #628629)

Utilizator gramatovici_paulGramatovici Paul gramatovici_paul Data 1 noiembrie 2011 19:00:14
Problema Ciclu Eulerian Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include <cstdio>
#include <vector>

using namespace std;

vector<int> muchii[100100],leg[100100];
vector<char> marc[100100];
int stiv[100100];
bool viz[100100];

int main()
{
    int n,m,i,x,y,k,nod;
    freopen("ciclueuler.in","r",stdin);
    freopen("ciclueuler.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(i=1;i<=m;++i)
    {
        scanf("%d%d",&x,&y);
        if (x!=y)
        {
            muchii[x].push_back(y);
            marc[x].push_back(0);
            muchii[y].push_back(x);
            leg[x].push_back(muchii[y].size()-1);
            leg[y].push_back(muchii[x].size()-1);
            marc[y].push_back(0);
        }
        else
        {
            muchii[x].push_back(x);
            marc[x].push_back(0);
            muchii[x].push_back(x);
            leg[x].push_back(muchii[x].size()-1);
            leg[x].push_back(muchii[x].size()-2);
            marc[x].push_back(0);
        }
    }
    for(i=1;i<=n;++i)
    {
        if(muchii[i].size()&1)
        {
            printf("-1\n");
            return 0;
        }
    }
    k=n-1;
    viz[1]=true;
    stiv[0]++;
    stiv[1]=1;
    while(k && stiv[0])
    {
        i=0;
        while(i<muchii[stiv[stiv[0]]].size() && viz[muchii[stiv[stiv[0]]][i]])
        {
            i++;
        }
        if(i==muchii[stiv[stiv[0]]].size())
        {
           stiv[0]--;
        }
        else
        {
            k--;
            viz[muchii[stiv[stiv[0]]][i]]=true;
            stiv[stiv[0]+1]=muchii[stiv[stiv[0]]][i];
            marc[stiv[stiv[0]]][i]=1;
            marc[muchii[stiv[stiv[0]]][i]][leg[stiv[stiv[0]]][i]]=1;
            stiv[0]++;
        }
    }
    if(k)
    {
        printf("-1\n");
        return 0;
    }
    k=m-1;
    nod=1;
    printf("1");
    while(k)
    {
        i=0;
        while(i<muchii[nod].size() && marc[nod][i]!=0)
        {
            i++;
        }
        if(i==muchii[nod].size())
        {
            i=0;
            while(i<muchii[nod].size() && marc[nod][i]!=1)
            {
                i++;
            }
        }
        printf(" %d",muchii[nod][i]);
        marc[nod][i]=2;
        marc[muchii[nod][i]][leg[nod][i]]=2;
        nod=muchii[nod][i];
        k--;
    }
    printf("\n");
    return 0;
}