Pagini recente » Cod sursa (job #1808706) | Cod sursa (job #1402054) | Cod sursa (job #544583) | Cod sursa (job #445042) | Cod sursa (job #2645874)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream in("ciclueuler.in");
ofstream out("ciclueuler.out");
int const CAP = 1e5;
struct Edge {
int node1;
int node2;
int del;
};
int n, m;
vector<Edge> edges; //This is the only place where the state changes
vector<int> g[CAP]; //g[i][j] is not a node, it's an Edge
int visited[CAP];
void euler(int from) {
while(!g[from].empty()) {
int i = g[from].back(); //i = the index of an Edge
g[from].pop_back();
if (edges[i].del == 0) { //Correct and O(m)
edges[i].del = 1;
int to = edges[i].node2;
if(to == from) {
to = edges[i].node1;
}
euler(to);
}
}
out << from + 1<< ' ';
}
int cntDfs = 0;
stack<int> st;
void dfs(int start) {
st.push(start);
while (!st.empty()) {
int from = st.top();
cntDfs++;
st.pop();
for (int i = 0; i < g[from].size(); i++) {
int to = edges[g[from][i]].node1;
if(to == from) {
to = edges[g[from][i]].node2;
}
if (!visited[to]) {
st.push(to);
}
}
}
/*
if (visited[from]) {
return;
}
cntDfs++;
visited[from] = true;
for (int i = 0; i < g[from].size(); i++) {
int to = edges[g[from][i]].node1;
if(to == from) {
to = edges[g[from][i]].node2;
}
dfs(to);
}
*/
}
bool hasSolution() {
for (int i = 0; i < n; i++) {
if (g[i].size() % 2 != 0) {
return false;
}
}
dfs(0);
return (cntDfs == n);
}
int main() {
in >> n >> m;
for (int i = 0; i < m; i++) {
int x, y;
in >> x >> y;
x--;
y--;
edges.push_back({x, y, 0}); //i-th edge inserted
g[x].push_back(i);
g[y].push_back(i);
}
if (!hasSolution()) {
out << -1 << '\n';
return 0;
}
euler(0);
return 0;
}