Cod sursa(job #2643483)

Utilizator Marius7122FMI Ciltea Marian Marius7122 Data 19 august 2020 22:51:42
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>

using namespace std;

const int N = 100005;
const int M = 500005;

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

vector<pair<int, int>> g[N];    // <destination, edge id>
vector<int> path;
bitset<M> used;

void euler(int node)
{
    stack<int> st;
    st.push(node);

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

        // visited all his edges
        if(g[currNode].size() == 0)
            path.push_back(currNode);
        // still has nodes
        else
        {
            auto edge = g[currNode].back();
            g[currNode].pop_back();
            st.push(currNode);
            if(!used[edge.second])
            {
                used[edge.second] = true;
                st.push(edge.first);
            }
        }
    }
}

int main()
{
    int n, m;
    fin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        int x, y;
        fin >> x >> y;
        g[x].push_back({y, i});
        g[y].push_back({x, i});
    }

    for(int i = 1; i <= n; i++)
    {
        if(g[i].size() % 2 != 0)
        {
            fout << -1;
            return 0;
        }
    }

    euler(1);

    for(int node : path)
        fout << node << ' ';

    return 0;
}