Cod sursa(job #2052893)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 31 octombrie 2017 10:10:46
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

struct edge
{
    edge(int x, int y)
    {
        this->x = x;
        this->y = y;
    }
    int x, y;
};

class graf
{
    public:
        graf(int n = 0, int m = 0)
        {
            this->n = n;
            edges.reserve(m);
            vizEdge.resize(m);
            vecini.resize(n + 1);
        }
        void AddEdge(int x, int y)
        {
            edges.push_back(edge(x, y));
            vecini[x].push_back(edges.size() - 1);
            vecini[y].push_back(edges.size() - 1);
        }
        bool HasEulerCycle()
        {
            for(int i = 1; i <= n; ++i)
                if(vecini[i].size() % 2 == 1)
                    return false;
            return true;
        }
        void GetEulerCycle(vector<int> &ret)
        {
            stack<int> st;
            st.push(1);
            while(st.empty() == false)
            {
                int nod = st.top();
                if(vecini[nod].empty() == false)
                {
                    int edgeId = vecini[nod].back();
                    vecini[nod].pop_back();
                    if(vizEdge[edgeId] == false)
                    {
                        vizEdge[edgeId] = true;
                        st.push(edges[edgeId].x ^ edges[edgeId].y ^ nod);
                    }
                }
                else
                {
                    st.pop();
                    ret.push_back(nod);
                }
            }
            ret.pop_back();
        }
    private:
        int n;
        vector<edge> edges;
        vector<vector<int> > vecini;
        vector<bool> vizEdge;

};

int main()
{
    ifstream in("ciclueuler.in");
    int n, m;
    in >> n >> m;
    graf gr(n, m);
    int x, y;
    while(m--)
    {
        in >> x >> y;
        gr.AddEdge(x, y);
    }
    in.close();
    ofstream out("ciclueuler.out");
    if(gr.HasEulerCycle())
    {
        vector<int> rasp;
        gr.GetEulerCycle(rasp);
        for(auto x:rasp)
            out << x << " ";
    }
    else
        out << -1;
    out.close();
    return 0;
}