Cod sursa(job #2172902)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 15 martie 2018 18:51:02
Problema Ciclu Eulerian Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 1e5 + 10;
const int mmax = 5e5 + 10;

int n, m;
vector < int > st, ans, g[nmax];

bool used_edge[mmax];
pair < int, int > edge[mmax];

int other_node(int edge_idx, int node1) {
    return (edge[edge_idx].first == node1) ? edge[edge_idx].second : edge[edge_idx].first;
}

void run_euler() {
    st.push_back(1);
    while (st.size()) {
        int node = st.back();
        if (g[node].size() == 0) {
            st.pop_back();
            ans.push_back(node);
            continue;
        }

        int to_edge = g[node].back(); g[node].pop_back();
        if (!used_edge[to_edge]) {
            used_edge[to_edge] = 1;
            int to = other_node(to_edge, node);

            st.push_back(to);
        }
    }

    ans.pop_back();
}

int main()
{
    freopen("ciclueuler.in","r",stdin);
    freopen("ciclueuler.out","w",stdout);

    ios_base :: sync_with_stdio(false);

    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        cin >> x >> y;
        edge[i] = {x, y};

        g[x].push_back(i);
        g[y].push_back(i);
    }

    run_euler();
    for (auto &it: ans)
        cout << it << ' ';

    return 0;
}