Cod sursa(job #1874959)

Utilizator borcanirobertBorcani Robert borcanirobert Data 10 februarie 2017 16:38:27
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

const int MAXM = 500005;
vector<vector<int>> G;
int N, M;
stack<int> st;
vector<int> ans;
bool usedEgde[MAXM];
int from[MAXM], to[MAXM];

void ReadGraph();
void Euler();

int main()
{
    ReadGraph();
    Euler();

    fin.close();
    fout.close();
    return 0;
}

void ReadGraph()
{
    int x, y;

    fin >> N >> M;
    G = vector<vector<int>>(N + 1);
    for ( int i = 1; i <= M; ++i )
    {
        fin >> x >> y;
        G[x].push_back(i);      /// marchez muchia de la x la y in G[x] si G[y] ca fiind muchia nuamrul i
        G[y].push_back(i);

        from[i] = x, to[i] = y;
    }
}

void Euler()
{
    for ( int i = 1; i <= N; ++i )
        if ( G[i].size() & 1 )
        {
            fout << "-1" << '\n';
            return;
        }

    st.push(1);

    while ( !st.empty() )
    {
        int x = st.top();

        if ( !G[x].empty() )
        {
            int e = G[x].back();
            G[x].pop_back();

            if ( !usedEgde[e] )
            {
                usedEgde[e] = true;
                int y = from[e] ^ to[e] ^ x; /// nu stiu in ce sens am luat muchia x spre y, poate ea era y spre x, iar prin aceasta formula imi rramane in y muchia care ducea de la x
                /** ECHIVALENT
                int y;
                if ( x == from[e] )
                    y = to[e];
                else
                    y = from[e];
                */
                st.push(y);
            }
        }
        else    /// nu mai ajung nicaieri, deci pun muchia x in answer
        {
            ans.push_back(x);
            st.pop();
        }
    }

    for ( const auto& x : ans )
        fout << x << ' ';
}