Cod sursa(job #1111606)

Utilizator ctftmAurelian ctftm Data 18 februarie 2014 23:21:13
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>
using namespace std;

const int N = 1 + 1e5, M = 1 + 5e5;

class Stack{
    int v[M];

public:
    Stack(){
        v[0] = 0;
    }

    void push(int x){
        v[ ++v[0] ] = x;
    }

    int pop(){
        return v[ --v[0] ];
    }

    int top(){
        return v[ v[0] ];
    }

    bool isEmpty(){
        return v[0] == 0;
    }
};

struct Muchie{
    int x, index;
    Muchie(int x, int i) : x(x), index(i) {};
};

vector<Muchie> graph[N];
bool usedEdge[N];
Stack S;
int n;

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

void readGraph(){
    int m, x, y;

    in >> n >> m;
    for (int i = 1 ; i <= m ; i++){
        in >> x >> y;
        graph[x].push_back( Muchie(y, i) );
        graph[y].push_back( Muchie(x, i) );
    }
}

void euler(){
    int x;

    for (int i = 1 ; i <= n ; i++)
        if (graph[i].size() & 1){
            out << "-1\n";
            return;
        }

    S.push(1);
    while (!S.isEmpty()){
        x = S.top();
        while ( !graph[x].empty() && usedEdge[ graph[x].back().index ] )
            graph[x].pop_back();
        if (!graph[x].empty()){
            usedEdge[ graph[x].back().index ] = true;
            S.push( graph[x].back().x );
        } else {
            S.pop();
            out << x << " ";
        }
    }
}

int main(){
    readGraph();
    euler();
    return 0;
}