# Cod sursa(job #1789756)

Utilizator Data 27 octombrie 2016 15:08:24 Ciclu Eulerian 100 cpp done Arhiva educationala 1.31 kb
``````#include <stdio.h>
#include <vector>
#include <queue>
#include <stack>

#define maxdim 100005

using namespace std;

int n, m;
int viz[maxdim], viz_edge[5 * maxdim];
vector<pair<int, int>> G[maxdim];
stack<int> st;
vector<int> solution;

void dfs(int nod) {
viz[nod] = 1;
for (auto &p : G[nod]) {
if (!viz[p.first]) {
dfs(p.first);
}
}
}

int valid() {
dfs(1);
for (int i = 1; i <= n; ++i) {
if (G[i].size() % 2 || !viz[i]) {
return 0;
}
}
return 1;
}

int euler() {
if (!valid()) {
return 0;
}
st.push(1);
while (!st.empty()) {
int nod = st.top();
while (!G[nod].empty() && viz_edge[G[nod].back().second]) {
G[nod].pop_back();
}
if (G[nod].empty()) {
st.pop();
solution.push_back(nod);
continue;
}
viz_edge[G[nod].back().second] = 1;
st.push(G[nod].back().first);
}
return 1;
}

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

scanf("%d %d", &n, &m);
for (int i = 1; i <= m; ++i) {
int x, y; scanf("%d %d", &x, &y);
G[x].push_back(make_pair(y, i));
G[y].push_back(make_pair(x, i));
}

if (!euler()) {
printf("-1\n");
} else {
solution.pop_back();
for (int nod : solution) {
printf("%d ", nod);
}
printf("\n");
}

return 0;
}
``````