problems / 205

Package Sort Stack

easy constructive greedy simulation stack 1000 ms · 256 MB

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:

  1. Push the next incoming package onto the stack
  2. 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!

Example 1

Input

3
2 1 3

Output

1
2
3

Example 2

Input

3
2 3 1

Output

IMPOSSIBLE

Hints · reveal one at a time if you're stuck

Hint 1

Simulate the process on the first example. At each second, when is a pop possible, and when is a push the only option?

Hint 2

Keep a stack and the next label you expect to send. Once the top matches that label, popping it is never a mistake, since it must leave next anyway. If the top doesn't match and no packages are left to push, the answer is IMPOSSIBLE.

report an issue Prefer your own editor? sooks prep 205 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.