Package Sort Stack
A delivery center receives n packages labeled 1 to n in a specific order, but the labels are scrambled — they arrive in some permutation of the natural order. Your job is to sort them back into the correct sequence using a single stack.
Each second, you must do exactly one of the following:
- Push the next incoming package onto the stack
- Pop the top package from the stack and send it out, only if its label matches the next expected output (the next number in the sequence 1, 2, 3, ...)
Starting from output number 1, determine whether you can successfully send out all packages in order 1, 2, 3, ..., n. If it's possible, output the sequence 1 2 3 ... n. Otherwise, output IMPOSSIBLE.
Input
The first line contains n (1 ≤ n ≤ 10⁵).
The second line contains n distinct integers p₁, p₂, ..., pₙ — a permutation of 1 to n representing the arrival order of packages.
Output
If the packages can be sorted using the stack method described above, print the sequence 1 2 3 ... n (each number on a separate line).
If it's impossible, print IMPOSSIBLE.
Notes
In the first example, packages arrive as [2, 1, 3]. The process:
- Expect output 1. Package 2 arrives, push it.
- Package 1 arrives, push it.
- Top is 1, matches next expected. Pop and output 1. Expect output 2.
- Top is 2, matches next expected. Pop and output 2. Expect output 3.
- Package 3 arrives, push it.
- Top is 3, matches next expected. Pop and output 3.
- Success! Output 1 2 3.
In the second example, packages arrive as [2, 3, 1]. The process:
- Expect output 1. Package 2 arrives, push it.
- Package 3 arrives, push it (stack is now [2, 3]).
- Package 1 arrives, push it (stack is now [2, 3, 1]).
- Top is 1, matches next expected. Pop and output 1. Expect output 2. Stack is [2, 3].
- Top is 3, but we need 2. We have no more input, and 3 is blocking 2 in the stack. Impossible!