Pagini recente » Monitorul de evaluare | Cod sursa (job #2923259) | Cod sursa (job #1481749) | Cod sursa (job #1411241) | Cod sursa (job #3309532)
#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <iomanip>
using namespace std;
#define ll long long
int n, m;
vector<vector<int>> graph;
vector<int> path;
vector<multiset<int>> adj; // use multiset to remove edges one by one
void ReadData() {
cin >> n >> m;
graph.assign(n, vector<int>());
adj.assign(n, multiset<int>());
for (int i = 0; i < m; i++) {
int start = 0, end = 0;
cin >> start >> end ;
start--; end--;
if (start != end) {
graph[start].push_back(end);
graph[end].push_back(start);
adj[start].insert(end);
adj[end].insert(start);
} else {
graph[start].push_back(end);
adj[start].insert(end);
}
}
}
void Solve() {
int start = 0;
for (int i = 0; i < n; i++) {
if (adj[i].size() % 2 == 1) {
start = i;
break;
}
}
stack<int> st;
vector<int> res;
st.push(start);
while (!st.empty()) {
int v = st.top();
if (!adj[v].empty()) {
int u = *adj[v].begin();
adj[v].erase(adj[v].find(u));
if (u != v) { // self-loop fix
adj[u].erase(adj[u].find(v));
}
st.push(u);
} else {
res.push_back(v);
st.pop();
}
}
if ((int)res.size() != m + 1) {
cout << "-1\n";
return;
}
for (int i = res.size() - 1; i >= 0; i--) {
cout << res[i] + 1 << " ";
}
cout << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
freopen("cyclueuler.in", "r", stdin);
freopen("cyclueuler.out", "w", stdout);
int t = 1;
// cin >> t; // Uncomment for multiple test cases
while (t--) {
ReadData();
Solve();
}
return 0;
}