Pagini recente » Cod sursa (job #182423) | Monitorul de evaluare | Cod sursa (job #941958) | Cod sursa (job #182426) | Cod sursa (job #3308297)
#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;
void ReadData() {
cin >> n >> m;
graph.assign(n, vector<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);
} else {
graph[start].push_back(end);
}
}
}
void removeVal(int node, int val){
auto it = find(graph[node].begin(), graph[node].end(), val);
if (it != graph[node].end()) {
graph[node].erase(it); // remove it
}
return;
}
int dfs (int node, int start, int end){
if (start != -1){
removeVal(start, end);
removeVal(end, start);
}
vector<bool> visited(n, false);
int first = 0;
stack<int> st;
st.push(first);
visited[first] = true;
int count = 1;
while (!st.empty()){
int node = st.top(); st.pop();
for (int val: graph[node]){
if (!visited[val]){
visited[val] = true;
st.push(val);
count++;
}
}
}
graph[start].push_back(end);
graph[end].push_back(start);
return count;
}
void Solve() {
for (int i = 0; i < n; ++i){
int count = 0;
for (int val: graph[i]){
if (val != i){
count++;
}
}
if (count % 2 != 0){
cout << "-1\n";
}
}
int start = 0;
stack<int> st;
st.push(start);
vector<pair<int, int>> result;
while (!st.empty()){
int node = st.top(); st.pop();
for (int val: graph[node]){
int reachableWith = dfs(node, -1, -1);
int reachableWithout = dfs(node, node, val);
if (node == val || reachableWith == reachableWithout || graph[node].size() == 1){
st.push(val);
removeVal(node, val);
removeVal(val, node);
result.push_back({node, val});
break;
}
}
}
for(int i = 0; i < result.size(); ++i ){
cout << result[i].first + 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;
}