Pagini recente » Monitorul de evaluare | Autentificare | Monitorul de evaluare | Statistici oanaaa (oanaaa) | Cod sursa (job #2161036)
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
int n, m, grad[100001];
vector<int> adj[100001];
bool b[100001];
int dfs_cnt(int nod)
{
int cnt = 1;
b[nod] = 1;
for (int i = 0; i < adj[nod].size(); i++)
{
int next = adj[nod][i];
if (!b[next] && next)
cnt += dfs_cnt(next);
}
return cnt;
}
int euler(int nod)
{
while (adj[nod].size())
{
fout << nod << ' ';
if (adj[nod].size() == 1)
{
int next = adj[nod][0], poz;
for (int j = 0; j < adj[next].size(); j++)
if (adj[next][j] == nod)
{
poz = j;
break;
}
adj[nod].erase(adj[nod].begin());
if (nod != next)
adj[next].erase(adj[next].begin() + poz);
nod = next;
continue;
}
for (int i = 0; i < adj[nod].size(); i++)
{
int next = adj[nod][i];
if (next)
{
for (int j = 1; j <= n; j++)
b[j] = 0;
int cnt = dfs_cnt(next), poz;
for (int j = 0; j < adj[next].size(); j++)
if (adj[next][j] == nod)
{
poz = j;
break;
}
adj[nod][i] = 0;
adj[next][poz] = 0;
for (int j = 1; j <= n; j++)
b[j] = 0;
if (dfs_cnt(next) != cnt)
{
adj[nod][i] = next;
adj[next][poz] = nod;
}
else
{
adj[nod].erase(adj[nod].begin() + i);
if (next != nod)
adj[next].erase(adj[next].begin() + poz);
i--;
nod = next;
break;
}
}
}
}
}
int main()
{
int x, y, cnt_impar = 0, start = 1;
fin >> n >> m;
while (m--)
{
fin >> x >> y;
adj[x].push_back(y);
if (x != y)
adj[y].push_back(x);
grad[x]++;
grad[y]++;
}
for (int i = 1; i <= n; i++)
{
if (grad[i] % 2 == 1)
{
if (cnt_impar < 2)
{
cnt_impar++;
start = i;
}
else
{
start = 0;
}
}
}
if (start == 0)
fout << -1;
else
euler(start);
return 0;
}