Cod sursa(job #1881661)

Utilizator FlowstaticBejan Irina Flowstatic Data 16 februarie 2017 17:30:30
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <cstdio>
#include <queue>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

FILE* fin = fopen("ciclueuler.in","r");
FILE* fout = fopen("ciclueuler.out","w");

void BFS(int vf);
void Citire();
bool EsteEulerian();
void Rezolva();

const int NMAX = 100005;

struct varf
{
    int v2;
    int contor;
};

int N,M;
vector<int> G[NMAX];
queue<int>Q;
stack<int> stiv;
bool viz[NMAX];

int main()
{
    Citire();
    if(EsteEulerian())
    {
        Rezolva();
    }
    else
    {
        fprintf(fout,"-1\n");
    }
    return 0;
}

void Citire()
{
    fscanf(fin,"%d %d",&N,&M);
    int x,y;
    while(M--)
    {
        fscanf(fin,"%d %d",&x,&y);
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

bool EsteEulerian()
{
    BFS(1);
    int i;
    for( i = 1; i<= N; i++)
        if(G[i].size() %2 || viz[i] == 0 )
            return 0;
    return 1;
}

void BFS(int vf)
{
    Q.push(vf); viz[vf] = 1;
    int i;
    while( !Q.empty() )
    {
        vf = Q.front();
        Q.pop();
        for(i = 0; i < G[vf].size(); i++)
            if( viz[ G[vf][i] ] == 0 )
                {
                    Q.push( G[vf][i] );
                    viz[ G[vf][i] ] = 1;
                }
    }
}

void Rezolva()
{
    int vf = 1,i,vf2;
    stiv.push(vf);
    while(!stiv.empty())
    {
        vf = stiv.top();
        if(G[vf].size() == 0)
            fprintf(fout,"%d ",vf), stiv.pop();
        else
        {
            vf2 = G[vf][G[vf].size()-1];
            stiv.push(vf2);
            G[vf].pop_back();
            G[vf2].erase(find(G[vf2].begin(),G[vf2].end(), vf));
        }
    }
}