Pagini recente » Cod sursa (job #43459) | Cod sursa (job #144174) | Cod sursa (job #3135837) | Cod sursa (job #1320392) | Cod sursa (job #2593471)
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
vector<vector<int>> Graph;
bool BFS(int k, int N)
{
queue<int> Q;
vector<bool> used;
used.resize(N);
Q.push(k);
used[k] = true;
while (!Q.empty()) {
k = Q.front();
Q.pop();
for (auto v: Graph[k])
if (!used[v]) {
used[v] = true;
Q.push(v);
}
}
for (int i = 0; i < N; ++i)
if (used[i] == false)
return true;
return false;
}
void euler(int k)
{
stack<int> S;
do {
while (Graph[k].size()) {
int v = Graph[k].back();
Graph[k].pop_back(); // remove {k,v}
Graph[v].erase(find(begin(Graph[v]), end(Graph[v]), k)); // remove {v,k}
S.push(k);
k = v; // go in depth
}
k = S.top();
S.pop();
fout << k + 1 << " ";
} while (!S.empty());
fout << "\n";
}
int main()
{
fin.sync_with_stdio(false);
fout.sync_with_stdio(false);
fin.tie(0);
fout.tie(0);
int N, M;
fin >> N >> M;
Graph.resize(N);
for (int i = 0; i < M; ++i) {
int from, to;
fin >> from >> to;
--from; --to;
Graph[from].emplace_back(to);
Graph[to].emplace_back(from);
}
for (auto it : Graph)
if (it.size() % 2 == 1) {
fout << "-1\n"; // odd degree, can't have cycle
return 0;
}
if (BFS(0, N)) {
fout << "-1\n"; // not connected graph
return 0;
}
euler(0);
return 0;
}