Pagini recente » Cod sursa (job #180671) | Cod sursa (job #2246582) | Cod sursa (job #1182910) | Cod sursa (job #23907) | Cod sursa (job #3284757)
#include <bits/stdc++.h>
using namespace std;
const int N_MAX = 1e5 + 5, M_MAX = 5e5 + 5;
int N, M;
bool visited[M_MAX];
struct Edge
{
int v;
int id;
Edge(int _v, int _id) :
v(_v), id(_id) { }
};
vector<Edge> G[N_MAX];
vector<int> Ans;
void SetInput(string name)
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
(void)!freopen((name + ".in").c_str(), "r", stdin);
(void)!freopen((name + ".out").c_str(), "w", stdout);
}
void ReadInput()
{
cin >> N >> M;
for(int i = 1, u, v; i <= M; i++)
{
cin >> u >> v;
G[u].emplace_back(v, i);
G[v].emplace_back(u, i);
}
}
bool HasEulerianCycle() /// OBS: we know the graph is conex already. Otherwise you have to check that too
{
for(int i = 1; i <= N; i++)
if(G[i].size() % 2 == 1)
return false;
return true;
}
void FindEulerianCycle(int v)
{
while(not G[v].empty())
{
auto [u, id] = G[v].back();
G[v].pop_back();
if(not visited[id])
{
visited[id] = true;
FindEulerianCycle(u);
}
}
Ans.push_back(v);
}
void Solve()
{
if(HasEulerianCycle())
{
FindEulerianCycle(1);
Ans.pop_back(); /// We don't need to write the last edge, which finishes the cycle
for(const int& v : Ans)
cout << v << ' ';
}
else
cout << "-1\n";
}
int main()
{
SetInput("ciclueuler");
ReadInput();
Solve();
return 0;
}