Cod sursa(job #1648030)

Utilizator Andreiii500Andrei Puiu Andreiii500 Data 10 martie 2016 23:42:48
Problema Ciclu Eulerian Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include<iostream>
#include<fstream>
using namespace std;

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

const int N = 100;
const int M = 500000;

int mat[N][N],mat_init[N][N];
int v[M+1],sol[M+1]; /// v = stiva
int n,m,top,n_sol,caz;

void push(int x)
{
    if(top >= 1)
    {
        --mat[x][v[top]];
        --mat[v[top]][x];
    }

    ++top;
    v[top] = x;
}

int pop()
{
    ++n_sol;
    sol[n_sol] = v[top];
    if(n_sol > 1 && mat_init[sol[n_sol]][sol[n_sol-1]] < 1) return 0;

    ///--mat[v[top]][v[top-1]];
    ///--mat[v[top-1]][v[top]];
    --top;
    return 1;
}

int main()
{
    int i,j,a,b;

    in>>n>>m;
    for(i=1; i<=m; ++i)
    {
        in>>a>>b;
        ++mat[a][b];
        ++mat[b][a];
    }

    for(i=1; i<=n; ++i)
        for(j=1; j<=n; ++j)
        {
            mat_init[i][j] = mat[i][j];
            mat_init[j][i] = mat[j][i];
        }

    /*for(i=1; i<=n; ++i)
    {
        for(j=1; j<=n; ++j) cout<<mat[i][j]<<" ";
        cout<<"\n";
    }*/

    push(1);
    while(top > 0)
    {
        ///cout<<"v["<<top<<"] = "<<v[top]<<"\n";

        for(i=1; i<=n; ++i)
            if(mat[i][v[top]] > 0)
            {
                push(i);
                break;
            }
        if(i == n+1)
        {
            if(pop() == 0)
            {
                caz=1;
                break;
            }
        }
    }

    if(sol[1] != sol[n_sol]) caz=1;

    if(caz == 0) for(i=1; i<=n_sol; ++i) out<<sol[i]<<" ";
    else cout<<"-1";


    return 0;
}