Cod sursa(job #1120243)

Utilizator PatrikStepan Patrik Patrik Data 24 februarie 2014 22:27:07
Problema Ciclu Eulerian Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.58 kb
    #include<cstdio>
    #include<vector>
    using namespace std;
    #define NMAX 100001
    #define pb push_back
    int N , M  , grad[NMAX]  , nr;
    vector<int> G[NMAX] , E[NMAX] , sol;
    vector<int>::iterator it;
    bool sw = 1 , u[NMAX];

    void read();
    void solve();
    void write();
    void ciclu(int nod);
    void DFS(int nod);
    void drum(int nod);

    int main()
    {
        read();
        solve();
        write();
        return 0;
    }

    void read()
    {
        int x , y;
        freopen("ciclueuler.in" , "r" , stdin );
        scanf("%d%d" , &N , &M );
        for(int i = 1 ; i<= M ; ++i )
        {
            scanf("%d%d" , &x , &y );
            G[x].pb(y) ; G[y].pb(x) ;
            grad[x]++ ; grad[y]++ ;
        }
    }

    void solve()
    {
        bool ok;
        for(int i = 1 ; i<= N ; ++i )
        if(grad[i]%2){sw = 0;return;}
        DFS(1);
        if(nr < N){sw = 0;return;}
        do
        {
            ok = 0;
            int i = 1;
            while(!grad[i] && i <= N)i++;
            if(i <= N)
            {
                ok = 1;ciclu(i);
            }
        }while(ok);
        drum(1);
    }

    void DFS(int nod)
    {
        u[nod] = 1;
        nr++;
        for(int i = 0 ;  i< (int)G[nod].size() ; ++ i)
        if(!u[G[nod][i]])
            DFS(G[nod][i]);
    }

    void ciclu(int sursa)
    {
        int x , y;
        x = sursa ; y = G[x][0];
        while(y != sursa)
        {
            E[sursa].pb(y);
            G[x].erase(G[x].begin());
            for(it = G[y].begin() ; it < G[y].end() ; ++it )
                if(*it == x)
            {
                G[y].erase(it);
                break;
            }
            grad[x]--;grad[y]--;
            x = y;
            y = G[y][0];
        }
         G[x].erase(G[x].begin());
            for(it = G[y].begin() ; it < G[y].end() ; ++it )
                if(*it == x)
            {
                G[y].erase(it);
                break;
            }
            grad[x]--;grad[y]--;
    }

    void write()
    {
        freopen("ciclueuler.out" , "w" , stdout );
        if(!sw)
            printf("-1");
        else
            for(int i = 0 ; i< (int)sol.size()-1 ; ++i )
                printf("%d " , sol[i]);
    }

    void drum(int nod)
    {
        sol.pb(nod);
        for(int i = 0 ; i < (int)E[nod].size() ; ++i )
            if(E[E[nod][i]].size())
                drum(E[nod][i]);
            else
                sol.pb(E[nod][i]);
        sol.pb(nod);
    }