Cod sursa(job #2663531)

Utilizator grigorut_octavianGrigorut Dominic Octavian grigorut_octavian Data 26 octombrie 2020 17:48:22
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.75 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");

struct nod
{
    int val;
    nod *next;
};

struct muchie
{
    int u,v;
    bool ver;
};

nod *l[100001];
bool fr[100001];
int gr[100001];
int n,m,k=0;
muchie M[500001];
int w[100001];

void adauga(int i,int j)
{
    nod *a=new nod;
    a->val=j;
    a->next=l[i];
    l[i]=a;
}

void creare_vec(int x,int y)
{
    M[++k].u=x;
    M[k].v=y;
    M[k].ver=false;
}

bool compara(muchie vs, muchie vd)
{
    return vs.u<vd.u;
}

void pt_w()
{
    int k=1;
    for(int i=1; i<=n; i++)
    {
        if(M[k].u==i) w[i]=k;
        else
        {
            while(M[k].u<i) k++;
            if(M[k].u==i) w[i]=k;
        }
    }
}

void citire()
{
    fin>>n>>m;
    for(int i=1; i<=m; i++)
    {
        int x,y;
        fin>>x>>y;
        adauga(x,y);
        adauga(y,x);
        gr[x]++;
        gr[y]++;
        creare_vec(min(x,y),max(x,y));
    }
    sort(M+1,M+n+1,compara);
    pt_w();
}


void dfs(int s)
{
    stack<int> st;
    st.push(s);
    while(!st.empty())
    {
        int top=st.top();
        st.pop();
        for(nod *p=l[top]; p!=NULL; p=p->next)
        {
            if(fr[p->val]==0)
            {
                fr[p->val]=fr[top]+1;
                st.push(p->val);
            }
        }
    }
}

int ver()
{
    for(int i=1; i<=n; i++)
    {
        if(gr[i]%2!=0)
            return 0;
    }
    return 1;
}

int conex()
{
    int cnt=0;
    for(int i=1; i<=n; i++)
    {
        if(fr[i]==0)
        {
            cnt++;
            dfs(i);
        }
    }
    if(cnt==1) return 1;
    return 0;
}

int se_poate(int x, int y)
{
    int a=w[x];
    for(int i=w[x]; M[a].u==M[i].u; i++)
    {
        if(x==M[i].u and y==M[i].v and M[i].ver==false)
        {
            M[i].ver=true;
            return 1;
        }
    }
    return 0;
}

void ciclu_euler()
{
    stack<int> st;
    queue<int> q;
    st.push(1);
    while(!st.empty())
    {
        int top=st.top();
        st.pop();
        bool ok=false;
        for(nod *p=l[top];p!=NULL;p=p->next)
        {
            if(se_poate(p->val,top)==1 or se_poate(top,p->val)==1)
            {
                ok=true;
                st.push(top);
                st.push(p->val);
                break;
            }
        }
        if(ok==false)
            q.push(top);
    }
    while(!q.empty())
    {
        int b=q.front();
        q.pop();
        fout<<b<<' ';
    }
}

void rez()
{
    if(conex()==1 and ver()==1)
    {
        ciclu_euler();
    }
    else fout<<-1;
}

int main()
{
    citire();
    rez();
    return 0;
}