Cod sursa(job #1646957)

Utilizator clopotelNeamtu Sergiu clopotel Data 10 martie 2016 18:21:29
Problema Ciclu Eulerian Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <cstdio>
#define pb push_back
#include <vector>
#include <stack>
using namespace std;
FILE* f=fopen("ciclueuler.in","r");
FILE* g=fopen("ciclueuler.out","w");
int n,m,ok;
vector <int> v[100001];
stack <int> st;

void sterg(int x,int y)
{
    for(int i=0;i<v[x].size();i++)
        if(v[x][i]==y)
            v[x].erase(v[x].begin()+i);
    for(int i=0;i<v[y].size();i++)
        if(v[y][i]==x)
            v[y].erase(v[y].begin()+i);
}
int main()
{
    fscanf(f,"%d%d",&n,&m);
    int x,y;
    for(int i=0;i<m;i++)
    {
        fscanf(f,"%d%d",&x,&y);
        v[x].pb(y);
        if(x!=y)
            v[y].pb(x);
    }
    int cn=1;
    while(!v[cn].empty() or !st.empty())
    {
        if(v[cn].empty())
        {
            fprintf(g,"%d ",cn);
            ok=1;
            cn=st.top();
            st.pop();
        }
        else
        {
            st.push(cn);
            int aux=v[cn][0];
            sterg(cn,aux);
            cn=aux;
        }
    }
    if(ok==0)
        fprintf(g,"%d",-1);
    return 0;
}