Cod sursa(job #2528328)

Utilizator AndreiJJIordan Andrei AndreiJJ Data 21 ianuarie 2020 19:16:40
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>
#include <vector>
#include <iostream>
#include <bitset>
#include <stack>

using namespace std;

const int N = 1e5 + 5;

vector <int> L[N]; /// the list L[i] stores the indices of the edges that are incident to the i-th vertex
vector <int> to(N), from(N); /// to[i] and from[i] store the vertices connected by the i-th edge
vector <int> eulcycle; /// stores the solution;
bitset <5 * N> used; /// used[i] = 1 if the i-th edge is already in the cycle, 0 otherwise
stack <int> st; /// stores the nodes in the cycle

int n;

/// A connected graph has an Euler cycle if and only if every vertex has even degree. - Euler's theorem

void Read ()
{
    ifstream fin ("ciclueuler.in");
    int m, x, y, i;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y;
        L[x].push_back(i);
        L[y].push_back(i);
        from[i] = x;
        to[i] = y;
    }
}

void Solve ()
{
    ofstream fout ("ciclueuler.out");
    for (int i = 1; i <= n; i++)
        if (L[i].size() & 1)
        {
            fout << "-1\n";
            fout.close();
            return;
        }
    st.push(1);
    while (!st.empty())
    {
        int node = st.top();
        if (L[node].size())
        {
            int nextedge = L[node].back();
            L[node].pop_back();
            if (!used[nextedge])
            {
                used[nextedge] = 1;
                int nextnode = (from[nextedge] ^ to[nextedge] ^ node);
                st.push(nextnode);
            }
        }
        else
        {
            st.pop();
            eulcycle.push_back(node);
        }
    }
    for (unsigned int i = 0; i < eulcycle.size() - 1; i++)
        fout << eulcycle[i] << " ";
    fout << "\n";
    fout.close();
}

int main()
{
    Read();
    Solve();
    return 0;
}