Cod sursa(job #1970771)

Utilizator popescu.octavianPopescu Octavian popescu.octavian Data 19 aprilie 2017 16:25:24
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
#define per pair<int,int>
#define pb push_back
#define NMax 100105
#define MMax 500105
using namespace std;

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

vector<int> st;
vector<per> G[NMax];
//stack<int> st;

int N, M, i, grad[NMax], viz[NMax], a, b, used[MMax];

void DFS (int x)
{
    viz[x]=1;
    for(int i=0; i<G[x].size(); i++)
        if(!viz[G[x][i].first])
            DFS(G[x][i].first);
}
void euler (int nod)
{
    st.pb(nod);
    while(!st.empty())
    {
        int x=st.back();
        if(!G[x].empty())
        {
            int y=G[x].back().first, mc=G[x].back().second;
            G[x].pop_back();
            if(!used[mc])
            {
                st.pb(y);
                used[mc]=1;
            }
        }
        else
        {
            g<<x<<' ';
            st.pop_back();
        }

    }
}
int main()
{
    f>>N>>M;
    for(i=1; i<=M; i++)
    {
        f>>a>>b;
        G[a].pb(per(b,i)); grad[a]++;
        G[b].pb(per(a,i)); grad[b]++;
    }

    DFS(1);
    for(i=1; i<=N; i++)
        if(grad[i]%2==1 || viz[i]==0)
        {
            g<<-1<<'\n';
            return 0;
        }

    euler(1);
    return 0;
}