#P5462. X Dragon Ball
X Dragon Ball
X Dragon Ball
In the game "X Dragon Ball", you are given an even number \(n\) of distinct Dragon Balls arranged in a queue. Each ball has a unique number. In one move, you may choose any two adjacent balls in the current queue, append them (preserving their order) to the end of a target queue (which starts empty), and then close the gap in the original queue. This process is repeated until the original queue becomes empty. Different sequences of moves can lead to different target queues. Your task is to determine the target queue that is lexicographically maximum among all possible outcomes.
Example: For an initial queue of [1, 3, 2, 4], one sequence of moves is to first remove the adjacent pair (3, 2) resulting in a target queue [3, 2] and the remaining queue [1, 4]. Then, remove the remaining pair (1, 4) to obtain the final target queue [3, 2, 1, 4].
Note: Lexicographical comparison is performed element‐by‐element: given two sequences, the first differing element determines the order.
inputFormat
The input consists of two lines. The first line contains an even integer \(n\) (with \(n \ge 2\)). The second line contains \(n\) distinct integers representing the Dragon Balls in the order they appear in the queue.
outputFormat
Output the lexicographically maximum target queue as a sequence of integers separated by spaces.
sample
4
1 3 2 4
3 2 1 4