Pagini recente » Cod sursa (job #1448892) | Cod sursa (job #1220546) | sad | Cod sursa (job #630976) | Cod sursa (job #1993733)
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <stack>
struct Edge {
int from, to;
};
bool valid(std::vector<std::list<int>> &graph, std::vector<Edge> &edges, int nV) {
for (int i(1); i <= nV; i++) {
if (graph[i].size() & 1) {
return false;
}
}
std::vector<bool> check(nV + 1, false);
std::list<int> myQ;
check[1] = true;
myQ.push_back(1);
int node;
while (!myQ.empty()) {
node = myQ.front();
myQ.pop_front();
for (int edge : graph[node]) {
if (!check[edges[edge].from]) {
check[edges[edge].from] = true;
myQ.push_back(edges[edge].from);
}
if (!check[edges[edge].to]) {
check[edges[edge].to] = true;
myQ.push_back(edges[edge].to);
}
}
}
for (int i(1); i <= nV; i++) {
if (!check[i]) {
return false;
}
}
return true;
}
void visit(std::vector<std::list<int>> &graph,
std::vector<Edge> &edges, std::vector<int> &res) {
std::stack<int> myStack;
myStack.push(1);
bool fin;
int edge, toErase;
while (!myStack.empty()) {
fin = true;
for (; !graph[myStack.top()].empty(); ) {
edge = graph[myStack.top()].front();
graph[myStack.top()].pop_front();
fin = false;
if (edges[edge].from != myStack.top()) {
myStack.push(edges[edge].from);
toErase = edges[edge].from;
} else {
myStack.push(edges[edge].to);
toErase = edges[edge].from;
}
for (auto it = graph[toErase].begin(); it != graph[toErase].end(); it++) {
if (*it == edge) {
graph[toErase].erase(it);
break;
}
}
break;
}
if (fin) {
res.push_back(myStack.top());
myStack.pop();
}
}
}
int main() {
std::ifstream fileIn("ciclueuler.in");
std::ofstream fileOut("ciclueuler.out");
int nV, nM;
fileIn >> nV >> nM;
std::vector<std::list<int>> graph(nV + 1);
std::vector<Edge> edges(nM);
int a, b;
for (int i(0); i < nM; i++) {
fileIn >> a >> b;
edges[i].from = a;
edges[i].to = b;
graph[a].push_back(i);
graph[b].push_back(i);
}
std::vector<int> res;
if (!valid(graph, edges, nV)) {
fileOut << -1;
} else {
visit(graph, edges, res);
for (auto node = res.begin(); node != res.end(); node++) {
fileOut << *node << ' ';
}
}
fileIn.close();
fileOut.close();
return 0;
}