Cod sursa(job #1461306)

Utilizator petru.cehanCehan Petru petru.cehan Data 15 iulie 2015 13:29:38
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

const int NMAX = 100005;

using namespace std;

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

int N , M , x , y ;
int grad [ NMAX ] ;
vector <int> v [ NMAX ] ;
stack <int> S ;
bool viz [ NMAX ] ;

void DFS ( int nod )
{
    viz [ nod ] = true ;
    for ( unsigned int i = 0; i < v [nod].size(); ++ i )
    {
        int vecin = v [nod] [i] ;
        if ( !viz [vecin] )
            DFS (vecin) ;
    }
}

void RemoveEdge ( int x , int y )
{
    v[x] .erase ( v[x] .begin() ) ;
    v[y] .erase ( find ( v[y] .begin() , v[y] .end() , x ) ) ;
}

void Euler()
{
    S.push ( 1 ) ;
    while ( !S.empty () )
    {
        int nod = S.top () ;

        if ( v [nod].size () )
        {
            S.push ( v [nod] [0] );
            RemoveEdge ( nod , v[nod] [0] ) ;
        }
        else
        {
            fout << nod << " " ;
            S.pop () ;
        }
    }
}

int main()
{
    fin >> N >> M;
    for ( int i = 1 ; i <= M ; ++ i )
    {
        fin >> x >> y;
        v [x].push_back (y);
        v [y].push_back (x);
        ++ grad [x] ;
        ++ grad[y] ;
    }

    DFS(1);

    for (int i = 1; i <= N; ++i)
    {
        if (!viz[i] || grad[i]%2 != 0) // daca nu e conex sau daca gradele nu is toate pare
        {
            fout << "-1";
            return 0;
        }
    }

    Euler ();

    fin.close();
    fout.close();
    return 0;
}