Pagini recente » Cod sursa (job #1520215) | Cod sursa (job #1761469) | Cod sursa (job #1110185) | Cod sursa (job #2208959) | Cod sursa (job #2207979)
#include <fstream>
#include <list>
#include <stack>
#include <list>
using namespace std;
struct graph {
int vertexCount;
int edgeCount;
list<int>* adjList;
int* grade;
int* visited;
};
void readGraph(graph& g, ifstream& in) {
in >> g.vertexCount >> g.edgeCount;
g.adjList = new list<int>[g.vertexCount + 1];
g.grade = (int*)calloc(g.vertexCount + 1, sizeof(int));
g.visited = (int*)calloc(g.vertexCount + 1, sizeof(int));
for (int i = 1; i <= g.edgeCount; i++) {
int a, b;
in >> a >> b;
g.grade[a]++;
g.grade[b]++;
g.adjList[a].push_back(b);
g.adjList[b].push_back(a);
}
}
/*
bool conex(graph& g) {
list<int> bfs;
bool* visited = (bool*)calloc(g.vertexCount + 1, sizeof(bool));
int discovered = 0;
bfs.push_back(1);
while (!bfs.empty()) {
int crt = bfs.front();
bfs.pop_front();
if (!visited[crt])
discovered++;
visited[crt] = true;
for (auto edg : g.adjList[crt]) {
int adj = crt == edg->a ? edg->b : edg->a;
if (!visited[adj])
bfs.push_back(adj);
}
}
return discovered == g.vertexCount;
}
*/
bool eulerCycleIt(graph& g, int node, list<int>& path) {
stack<int> s;
s.push(node);
//g.visited[node] = -1;
for (int i = 1; i < g.edgeCount; i++){
int crt = s.top();
g.visited[crt]++;
int adj;
if (!g.adjList[crt].empty())
adj = g.adjList[crt].back();
while (!g.adjList[crt].empty() && (g.visited[adj] >= (g.grade[adj] / 2))) {
g.adjList[crt].pop_back();
if(!g.adjList[crt].empty())
adj = g.adjList[crt].back();
}
if (!g.adjList[crt].empty()) {
auto adj = g.adjList[crt].back();
g.adjList[crt].pop_back();
s.push(adj);
}
}
if (s.size() != g.edgeCount)
return false;
path.push_back(node);
while (s.size()>1) {
path.push_back(s.top());
s.pop();
}
return true;
}
bool notEulerian(graph& g) {
for (int i = 1; i <= g.vertexCount; i++) {
if (g.grade[i] % 2 == 1)
return true;
}
return false;
}
/*
void eulerCycle(graph& g, int node, list<int>& path) {
while (!g.adjList[node].empty()) {
if (!g.adjList[node].back()->used) {
edge* edg = g.adjList[node].back();
int adj = node == edg->a ? edg->b : edg->a;
edg->used = true;
g.adjList[node].pop_back();
eulerCycle(g, adj, path);
}
else
g.adjList[node].pop_back();
}
path.push_back(node);
}
*/
int main() {
graph g;
ifstream in("ciclueuler.in");
readGraph(g, in);
in.close();
ofstream out("ciclueuler.out");
if (notEulerian(g)) {
out << -1;
}
else {
list<int> path;
if(!eulerCycleIt(g, 1, path))
out << -1;
else {
for (auto elem : path) {
out << elem << " ";
}
}
}
out.close();
return 0;
}