Pagini recente » Cod sursa (job #523788) | Cod sursa (job #269183) | Cod sursa (job #472833) | Cod sursa (job #1972486) | Cod sursa (job #527042)
Cod sursa(job #527042)
#include <fstream>
#include <stack>
#include <queue>
#include <list>
using namespace std;
#define NMAX 100000
int N;
list<int> adjList[NMAX+1];
int degree[NMAX+1];
bool visited[NMAX+1];
queue<int> bfs_queue;
stack<int> euler_stack;
list<int> cycle;
void readInput()
{
int M, to, from;
ifstream f("ciclueuler.in");
f >> N >> M;
for (int i=0;i<M;i++)
{
f >> from >> to;
adjList[from].push_back(to);
adjList[to].push_back(from);
degree[from]++;
degree[to]++;
}
f.close();
}
void bfs(int s)
{
visited[s] = true;
bfs_queue.push(s);
while (!bfs_queue.empty())
{
int x = bfs_queue.front();
bfs_queue.pop();
for (list<int>::iterator it = adjList[x].begin(); it != adjList[x].end(); it++)
{
if (!visited[*it])
{
bfs_queue.push(*it);
visited[*it] = true;
}
}
}
}
bool eulerian_test()
{
bfs(1);
for (int i=1;i<=N;i++)
{
if (!visited[i] || degree[i] &1)
{
return false;
}
}
return true;
}
void euler(int s)
{
while (!adjList[s].empty())
{
int x = adjList[s].front();
euler_stack.push(s);
degree[s]--;
degree[x]--;
adjList[s].pop_front();
for (list<int>::iterator it = adjList[x].begin(); it != adjList[x].end(); it++)
{
if (*it == s)
{
adjList[x].erase(it);
break;
}
}
s = x;
}
cycle.push_back(s);
}
int main(void)
{
ofstream g("ciclueuler.out");
readInput();
if (eulerian_test)
{
int s = 1;
do
{
euler(s);
s = euler_stack.top();
euler_stack.pop();
} while (!euler_stack.empty());
for (list<int>::iterator it = cycle.begin(); it != cycle.end(); it++)
{
g << *it << " ";
}
g<<"\n";
}
else
{
g << "-1\n";
}
g.close();
return 0;
}