Cod sursa(job #2173394)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 15 martie 2018 22:02:22
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 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() {
	for (int i = 1; i <= n; ++i)
		if (g[i].size() % 2) {
			cout << -1 << '\n';
			exit(0);
		}
		
    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;
}