Pagini recente » Cod sursa (job #3135936) | Cod sursa (job #656764) | Cod sursa (job #531007) | Cod sursa (job #1197546) | Cod sursa (job #1993726)
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <stack>
struct Edge {
int from, to;
bool check;
};
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;
while (!myStack.empty()) {
fin = true;
for (auto edge = graph[myStack.top()].begin(); edge != graph[myStack.top()].end(); edge++) {
if (edges[*edge].check) {
fin = false;
edges[*edge].check = false;
if (edges[*edge].from != myStack.top()) {
myStack.push(edges[*edge].from);
} else {
myStack.push(edges[*edge].to);
}
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;
edges[i].check = true;
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;
}