Cod sursa(job #1970723)

Utilizator popescu.octavianPopescu Octavian popescu.octavian Data 19 aprilie 2017 15:56:14
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
#define pb push_back
#define NMax 100005

using namespace std;

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

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

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

void DFS (int x)
{
    viz[x]=1;
    for(int i=0; i<G[x].size(); i++)
        if(!viz[G[x][i]])
            DFS(G[x][i]);
}
void euler (int nod)
{
    st.push(nod);
    while(!st.empty())
    {
        int x=st.top();
        if(G[x].size())
        {
            int y=G[x].back(); G[x].pop_back();
            st.push(y);
            G[y].erase(find(G[y].begin(), G[y].end(), x));
        }
        else
        {
            g<<x<<' ';
            st.pop();
        }

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

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

    euler(1);
    return 0;
}