Pagini recente » Cod sursa (job #2036375) | Cod sursa (job #2862582) | Cod sursa (job #1700067) | Cod sursa (job #1546199) | Cod sursa (job #3217477)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
const int MAX_SIZE = 100000;
vector<int> graph[MAX_SIZE + 1];
vector<int> answer;
unordered_map<int, bool> isVisited;
void bfs(vector<int> currentNodes) {
if (currentNodes.empty() == 1) {
return;
}
vector<int> nextNodes;
for (vector<int>::iterator it = currentNodes.begin(); it < currentNodes.end(); ++it) {
for (vector<int>::iterator it2 = graph[*it].begin(); it2 < graph[*it].end(); ++it2) {
if (isVisited[*it2] == 0) {
isVisited[*it2] = 1;
nextNodes.push_back(*it2);
}
}
}
bfs(nextNodes);
}
void deleteEdge(int node1, int node2) {
for (vector<int>::iterator it = graph[node1].begin(); it < graph[node1].end(); ++it) {
if (*it == node2) {
graph[node1].erase(it);
return;
}
}
}
void euler(int currentNode) {
while (graph[currentNode].empty() == 0) {
int nextNode = graph[currentNode].back();
deleteEdge(nextNode, currentNode);
graph[currentNode].pop_back();
euler(nextNode);
}
answer.push_back(currentNode);
}
bool isEuler(int noNodes) {
for (int i = 1; i <= noNodes; ++i) {
if (graph[i].size() % 2 == 1) {
return 0;
}
}
vector<int> currentNodes;
currentNodes.push_back(1);
isVisited[1] = 1;
bfs(currentNodes);
for (int i = 1; i <= noNodes; ++i) {
if (isVisited[i] == 0) {
return 0;
}
}
return 1;
}
int main() {
int noNodes, noEdges;
fin >> noNodes >> noEdges;
for (int i = 1; i <= noEdges; ++i) {
int startNode, endNode;
fin >> startNode >> endNode;
graph[startNode].push_back(endNode);
graph[endNode].push_back(startNode);
}
if (isEuler(noNodes) == 0) {
fout << -1;
} else {
euler(1);
for (int i = 0; i < answer.size(); ++i) {
fout << answer[i] << ' ';
}
}
return 0;
}