Pagini recente » Cod sursa (job #1893466) | Cod sursa (job #1416830) | Clasament pregatire_oji_11-12_ | Cod sursa (job #386898) | Cod sursa (job #2884170)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream f ("ciclueuler.in");
ofstream g ("ciclueuler.out");
const int N_MAX = 100001;
const int M_MAX = 500001;
int n, m;
int from[M_MAX], to[M_MAX];
bool visited[M_MAX];
vector <int> G[N_MAX];
vector <int> path;
stack <int> S;
void Read()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
f >> x >> y;
G[x].push_back(i);
G[y].push_back(i);
from[i] = x;
to[i] = y;
}
}
bool IsCycle()
{
for (int i = 1; i <= n; i++)
{
if (G[i].size() % 2 == 1)
{
return false;
}
}
return true;
}
void Euler(int start)
{
S.push(start);
while (S.empty() == false)
{
int node = S.top();
if (G[node].empty() == false)
{
int edge = G[node].back();
G[node].pop_back();
if (visited[edge] == false)
{
visited[edge] = true;
if (to[edge] != node)
{
S.push(to[edge]);
}
else
{
S.push(from[edge]);
}
}
}
else
{
path.push_back(node);
S.pop();
}
}
}
void Print()
{
for (unsigned int i = 0; i < path.size()-1; i++)
{
g << path[i] << " ";
}
}
int main()
{
Read();
if (IsCycle() == false)
{
g << -1;
}
else
{
Euler(1);
}
Print();
}