Pagini recente » Cod sursa (job #2005486) | Cod sursa (job #2041874) | Monitorul de evaluare | Profil MihaelaCismaru | Cod sursa (job #1243432)
#include <iostream>
#include <cstdio>
#include <list>
#include <queue>
#include <stack>
#define MAX_N 100003
using namespace std;
stack <int> st;
list <int> nodes[MAX_N];
queue <int> q;
bool vis[MAX_N];
int n;
FILE *out = fopen("ciclueuler.out", "w");
void BFS(int x)
{
vis[x] = 1;
q.push(x);
int cnode;
while (!q.empty())
{
cnode = q.front();
for(list<int>::iterator i = nodes[cnode].begin(); i != nodes[cnode].end(); i++)
{
if (!vis[*i])
{
vis[*i] = 1;
q.push(*i);
}
}
q.pop();
}
}
bool conex()
{
for (int i = 1; i <= n; ++i)
if (!vis[i])
return 0;
return 1;
}
int eulerian()
{
for (int i = 1; i <= n; ++i)
{
if (nodes[i].size() % 2 == 1)
return 0;
}
return 1;
}
void deleteEdge(int v, int w)
{
for(list<int>::iterator i = nodes[w].begin(); i != nodes[w].end(); i++)
{
if (*i == v)
{
i = nodes[w].erase(i);
break;
}
}
nodes[v].pop_front();
}
void euler(int x)
{
st.push(x);
fprintf(out, "%d", x);
int v, w;
while (!st.empty())
{
v = st.top();
if (nodes[v].empty())
{
st.pop();
continue;
}
w = nodes[v].front();
deleteEdge(v, w);
if (nodes[v].empty())
st.pop();
if (!nodes[w].empty())
{
st.push(w);
fprintf(out, " %d", w);
}
}
fprintf(out, " %d\n", w);
}
void solPrint()
{
if (conex() == false)
{
fprintf(out, "-1\n");
fclose(out);
return;
}
int x = eulerian();
if (x == 1)
euler(1);
else
fprintf(out, "-1\n");
fclose(out);
}
void read()
{
FILE *in = fopen("ciclueuler.in", "r");
int m;
fscanf(in, "%d%d", &n, &m);
int x, y;
for (; m > 0; m--)
{
fscanf(in, "%d%d", &x, &y);
nodes[x].push_back(y);
nodes[y].push_back(x);
}
fclose(in);
}
int main()
{
read();
BFS(1);
solPrint();
return 0;
}