Cod sursa(job #1348812)

Utilizator Edsger.DijkstraEdsger Wybe Dijkstra Edsger.Dijkstra Data 19 februarie 2015 21:09:44
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int MAXN = 100010;
const int MAXM = 500010;

vector < pair <int, int> > Graf[MAXN];
bool Used[MAXM];
int Grad[MAXN];

class Stack
{
private:
    int St[MAXM];
    int N;
public:
    Stack ()
    {
        N = 0;
    }

    void push (const int &X)
    {
        St[++ N] = X;
    }

    void pop ()
    {
        N --;
    }

    int top ()
    {
        return St[N];
    }

    bool empty ()
    {
        return (N == 0);
    }
} S;

int main()
{
    int N, M, i, a, b;

    in >> N >> M;
    for (i = 1; i <= M; i ++){
        in >> a >> b;
        Graf[a].push_back (make_pair (b, i));
        Graf[b].push_back (make_pair (a, i));
        Grad[a] ++;
        Grad[b] ++;
    }

    for (i = 1; i <= N; i ++)
        if (Grad[i] & 1){
            out << "-1";

            return 0;
        }

    int nod;
    vector < pair <int, int> > :: iterator it;

    S.push (1);
    while (!S.empty ())
    {
        nod = S.top ();

        while (!Graf[nod].empty () && Used[Graf[nod].back ().second])
            Graf[nod].pop_back ();

        if (!Graf[nod].empty ()){
            Used[Graf[nod].back ().second] = 1;
            S.push (Graf[nod].back ().first);
        }
        else{
            S.pop ();
            out << nod << " ";
        }
    }

    return 0;
}