Queue Sort

Time limit1sMemory limit128 MB

Summary
Given a permutation in a queue and two auxiliary stacks, find the minimum number of bulk transfer operations to sort the queue into ascending order.
Level

Hard8 of 10

Topics
BFS, Simulation, Implementation, Brute force
Solved
No attempts yet

Problem

There is a queue QQ and two stacks AA and BB. The following seven operations are available.

  • QA(n): Take one number out of QQ and put it into AA. Repeat this nn times.
  • QB(n): Take one number out of QQ and put it into BB. Repeat this nn times.
  • QQ(n): Take one number out of QQ and put it back into QQ. Repeat this nn times.
  • AQ(n): Take one number out of AA and put it into QQ. Repeat this nn times.
  • BQ(n): Take one number out of BB and put it into QQ. Repeat this nn times.
  • AB(n): Take one number out of AA and put it into BB. Repeat this nn times.
  • BA(n): Take one number out of BB and put it into AA. Repeat this nn times.

Since QQ is a queue (FIFO), a number is always removed from the front and inserted at the back. Since AA and BB are stacks (LIFO), a number is always removed from the top and pushed onto the top.

Each operation counts as one, regardless of the value of nn.

Initially the queue holds all of the numbers and both stacks are empty. You want the numbers in the queue, read from front to back, to be in ascending order. Find the minimum number of operations required. (When sorting is finished, all numbers must be back in the queue and both stacks must be empty.)

For example, if the queue is (4 3 1 2 0), it can be sorted in 3 operations: QA(2), QQ(2), AQ(2). If the queue is (5 4 1 3 2 0), it can be sorted in 4 operations: QB(2), QQ(1), QB(2), BQ(4).

Input

The input consists of several test cases. Each test case is given on one line whose first integer is NN, the count of numbers in the queue. The next NN integers are the contents of the queue, given in order from the front.

Every number in the queue is an integer between 00 and N−1N-1 inclusive, and each number appears exactly once. NN does not exceed 1010.

The last line of the input contains a single 00, which is not processed and marks the end of the input.

Output

For each test case, print on its own line the minimum number of operations needed to sort the queue in ascending order.

Examples3

  1. Example 1

    Input
    5 4 3 1 2 0
    6 5 4 1 3 2 0
    0
    
    Expected output
    3
    4
    
  2. Example 2

    Input
    1 0
    2 0 1
    2 1 0
    0
    
    Expected output
    0
    0
    1
    
  3. Example 3

    Input
    5 0 1 2 3 4
    5 4 3 2 1 0
    0
    
    Expected output
    0
    2