Pagini recente » Cod sursa (job #1030531) | Cod sursa (job #2051187) | Cod sursa (job #443845) | Cod sursa (job #2034940) | Cod sursa (job #1428976)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
void euler(int node, vector<int> adjList[], vector<int> &cycle);
void deleteEdge(int node, int neighbor, vector<int> adjList[]);
bool BFS(int src, vector<int> adjList[], int N);
int main()
{
int N, M, u, v, i;
ifstream f("ciclueuler.in");
f >> N >> M;
vector<int> adjList[N + 1];
int grade[N + 1];
fill(grade, grade + N + 1, 0);
for (i = 1; i <= M; i++)
{
f >> u >> v;
grade[u]++;
grade[v]++;
adjList[u].push_back(v);
if (u != v)
adjList[v].push_back(u);
}
f.close();
ofstream g("ciclueuler.out");
bool isEulerian = true;
for (i = 1; i <= N && isEulerian; i++)
if (grade[i] % 2 != 0)
isEulerian = false;
if (isEulerian)
isEulerian = BFS(u, adjList, N);
if (isEulerian)
{
vector<int> cycle;
euler(u, adjList, cycle);
for (i = 0; i < cycle.size(); i++)
g << cycle[i] << " ";
}
else
g << "-1";
g.close();
return 0;
}
void euler(int node, vector<int> adjList[], vector<int> &cycle)
{
int neighbor;
while (adjList[node].size())
{
neighbor = adjList[node][0];
deleteEdge(node, neighbor, adjList);
euler(neighbor, adjList, cycle);
}
cycle.push_back(node);
}
void deleteEdge(int node, int neighbor, vector<int> adjList[])
{
adjList[node].erase(adjList[node].begin());
bool found = false;
for (auto it = adjList[neighbor].begin(); it != adjList[neighbor].end() && !found; it++)
if (*it == node)
adjList[neighbor].erase(it), found = true;
}
bool BFS(int src, vector<int> adjList[], int N)
{
bool visited[N + 1];
fill(visited, visited + N + 1, false);
visited[src] = true;
queue<int> q;
q.push(src);
N--;
int x;
while(!q.empty())
{
x = q.front(), q.pop();
for (auto it = adjList[x].begin(); it != adjList[x].end(); it++)
if (!visited[*it])
{
N--;
q.push(*it);
visited[*it] = true;
}
}
return !N;
}