Up and Down (Large)
Time limit5sMemory limit512 MB
Find the fewest adjacent swaps that turn the sequence into one that rises to a peak and then falls.
- Level
Medium5 of 10
- Topics
- Greedy, Prefix sum
- Solved
- No attempts yet
Problem
You are given a sequence of distinct integers , and you want to rearrange it into an up and down sequence. A sequence is up and down when there is an index () with
If the whole sequence decreases, and if the whole sequence increases.
You may swap two adjacent elements of the sequence, one swap at a time. Find the minimum number of such swaps needed to reach an up and down sequence.
Input
The first line contains the number of test cases . test cases follow. Each test case begins with a line containing one integer . The next line contains distinct integers separated by spaces.
Limits
- The are pairwise distinct.
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from 1 and is the minimum number of swaps required to rearrange into an up and down sequence.
Hint
The sequence in the first example is already in the desired form (with ), so no swap is needed.
In the second example, swapping 3 and 7 produces an up and down sequence (with ).