Problem H
Hamiltooonian Hike

Alice, backpacking in the mountains.

Alice loves hiking. She often travels through forests and over mountains for several days, bringing only a backpack. For next year’s summer, she decided to travel to a beautiful area which contains a large number of cabins: places where hikers can lay down a sleeping bag and stay for the night. These cabins are connected by hiking trails, paths along the scenery in the area which lead to a next cabin.

Alice’s plan is to perform a multi-day hike. Every day, she will walk along the trails to a new cabin to spend the night. She can walk up to three trails in one day—walking four trails is too exhausting. In order to experience as much of the cabins as possible, Alice has decided that she wants to sleep in every cabin at least once. However, the summer has a limited number of days: she does not have the time to visit a cabin multiple times.

Alice has noticed that this requires careful planning of her hike and wonders how to find such a route. Determine which cabin Alice should walk to for every day. Figure 1 shows a possible route for the second sample case.


The input consists of:

  • One line containing two integers $n$ ($2\leq n\leq 2\cdot 10^5$) and $m$ ($1\leq m \leq 2\cdot 10^5$), the number of cabins and hiking trails.

  • $m$ lines each containing two integers $x,y$ ($1 \leq x,y \leq n$, $x \neq y$), indicating that there is a hiking trail between cabins $x$ and $y$.

It is guaranteed that every cabin is reachable from every other cabin. There is at most one hiking trail between any two cabins.


Output the order in which Alice should visit the $n$ cabins.

You do not need to minimize the total number of hiking trails.

If there are multiple valid solutions, you may output any one of them.

\includegraphics[width=0.9\textwidth ]{figure.pdf}
Figure 1: The input and a possible route (dashed red arrows) for the second sample case.
Sample Input 1 Sample Output 1
4 3
1 2
1 3
1 4
2 1 3 4
Sample Input 2 Sample Output 2
7 8
1 2
1 7
2 3
2 4
3 4
4 5
5 6
5 7
1 4 2 5 7 6 3

Please log in to submit a solution to this problem

Log in