#P5022. Lexicographically Smallest Travel Plan
Lexicographically Smallest Travel Plan
Lexicographically Smallest Travel Plan
Little Y is an enthusiastic traveler and an OIer. While visiting country X, she wants to visit every one of its n cities. The country has m bidirectional roads, each connecting two distinct cities. There are no multiple roads connecting the same pair of cities and no road connects a city to itself. Moreover, the road network is connected so that one can reach any city starting from any other city.
Little Y can only travel from one city to another using these roads. Her travel plan is defined as follows: choose any city as the starting point, and then, starting from that city, repeatedly do one of the following:
- Select a road from the current city that leads to a city she has not visited before.
- Or, backtrack along the road via which she first visited the current city to return to the previous city.
When she returns to the starting city, she may either end her journey or continue traveling, but her plan must visit every city at least once. Each time she visits a city for the first time (including the starting city), she records its number, forming a sequence of length n.
Little Y wishes this recorded sequence to be lexicographically smallest among all valid travel plans. For two sequences A and B of length n, we say A is lexicographically smaller than B if and only if there exists an index x (1 ≤ x ≤ n) such that:
- For all indices i with 1 ≤ i < x, Ai = Bi, and
- Ax < Bx.
Your task is to help Little Y determine and output this lexicographically smallest sequence.
Hint: It turns out the optimal strategy is to always choose the smallest numbered city available among the cities that are reachable by the current partial travel plan. This can be efficiently implemented using a min-heap (priority queue).
inputFormat
The input begins with a line containing two integers n and m (2 ≤ n, m ≤ 105), representing the number of cities and roads respectively.
This is followed by m lines, each containing two integers u and v (1 ≤ u, v ≤ n, u ≠ v) indicating that there is a bidirectional road connecting city u and city v.
It is guaranteed that the network is connected and there is at most one road between any two cities.
outputFormat
Output a single line with n integers, which is the lexicographically smallest sequence of city numbers recorded according to Little Y's travel plan. The numbers should be separated by a single space.
sample
3 2
1 2
1 3
1 2 3