Brainman
Time limit1sMemory limit128 MB
Given a sequence, find the minimum number of adjacent swaps needed to sort it in non-decreasing order; this equals the number of inversions.
- Level
Medium4 of 10
- Topics
- Divide and conquer, Sorting, Array
- Solved
- No attempts yet
Problem
Raymond Babbitt amazes his brother Charlie. Recently Raymond counted 246 toothpicks spilled all over the floor in an instant, just by glancing at them, and he can even count playing cards. Charlie would love to do cool things like that too, and he wants to beat his brother at a similar task.
Here is what Charlie thinks of. You are given a sequence of numbers. The goal is to move the numbers around until the sequence is sorted in non-decreasing order. The only allowed operation is to swap two adjacent numbers.
For example, the sequence can be sorted with nine adjacent swaps:
However, it is even possible to sort it with only three such swaps:
The question is: what is the minimum number of adjacent swaps needed to sort a given sequence? Since Charlie does not have Raymond's mental capabilities, he asks you to write a program that answers the question.
Input
The first line contains the number of scenarios.
Each scenario is given on a single line: first the length () of the sequence, followed by the elements of the sequence (each element is an integer in ). All numbers on the line are separated by single spaces.
Output
For each scenario, print a line Scenario #i:, where i is the scenario number starting at 1, followed by a line containing the minimum number of adjacent swaps needed to sort that scenario's sequence. Separate the output of consecutive scenarios with a single blank line.