Queue Sort
Time limit1sMemory limit128 MB
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 and two stacks and . The following seven operations are available.
- QA(n): Take one number out of and put it into . Repeat this times.
- QB(n): Take one number out of and put it into . Repeat this times.
- QQ(n): Take one number out of and put it back into . Repeat this times.
- AQ(n): Take one number out of and put it into . Repeat this times.
- BQ(n): Take one number out of and put it into . Repeat this times.
- AB(n): Take one number out of and put it into . Repeat this times.
- BA(n): Take one number out of and put it into . Repeat this times.
Since is a queue (FIFO), a number is always removed from the front and inserted at the back. Since and 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 .
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 , the count of numbers in the queue. The next integers are the contents of the queue, given in order from the front.
Every number in the queue is an integer between and inclusive, and each number appears exactly once. does not exceed .
The last line of the input contains a single , 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.