What Goes Up Must Come Down
Time limit2sMemory limit512 MB
Rearrange the cards by adjacent swaps into a bitonic order with the fewest moves, counting inversions by value.
- Level
Hard8 of 10
- Topics
- Divide and conquer, Sorting, Greedy, Bit manipulation
- Solved
- No attempts yet
Problem
Several cards with numbers printed on them are lined up on the table.
We want to change their order so that the first part is in non-decreasing order of the numbers and the rest is in non-increasing order. For example, (1, 2, 3, 2, 1), (1, 1, 3, 4, 5, 9, 2), and (5, 3, 1) are acceptable orders, but (8, 7, 9) and (5, 3, 5, 3) are not.
Formally, let be the number of cards and let be the number printed on the card at the -th position () after reordering. There must exist such that and .
The only operation allowed for reordering is to swap the positions of an adjacent pair of cards. We want to know the minimum number of swaps required to complete the reorder.
Input
The input consists of a single test case of the following format.
n
a1 . . . an
An integer in the first line is the number of cards (). The integers through in the second line are the numbers printed on the cards, in the order of their original positions ().
Output
Output in a line the minimum number of swaps required to reorder the cards as specified.