Crane
Time limit4sMemory limit128 MB
Given a permutation of up to 8 crates, find the fewest block-half swaps of any even-length interval needed to sort it.
- Level
Medium5 of 10
- Topics
- BFS, Graph, Brute force
- Solved
- No attempts yet
Problem
There are crates waiting to be loaded onto a ship. The crates are numbered , and the numbers give the loading order. Something went wrong in transit, so the crates now stand in a row in an arbitrary order. The dock has very little free space, so the only way to sort them is to swap whole blocks of crates.
A crane does the swapping. In one move the crane picks a contiguous interval of crates whose length is even, then exchanges the first half of the interval with the second half. The order inside each half stays the same.
The crane's software has a bug: the move counter is a 9-based integer (not 10-based, as you might think) with at most 6 digits. The crane therefore stops working and has to be serviced after moves.
Find the smallest number of crane moves that puts the crates in the order .
Input
The first line of input contains the number of test cases . The descriptions of the test cases follow.
Each test case starts with a line holding an integer (), the number of crates. The next line holds a permutation of , the crate numbers from left to right.
Output
For each test case print a single line containing the minimum number of crane moves needed to sort that row of crates. Do not follow the crane's strange software design, use the standard decimal numeral system.