This page is still under construction.

Parts of this page are still being built. What you see may change.

Manhattan Sort

Time limit1sMemory limit128 MB

Summary
Sort each sequence of distinct integers with swaps that cost the distance between positions and report the minimum total cost.
Level

Medium5 of 10

Topics
Greedy, Sorting, Math
Solved
No attempts yet

Problem

You are given a sequence SS of NN distinct integers. Sort it into ascending order at the lowest possible cost, using only one operation.

The Manhattan swap: it takes the elements SiS_i and SjS_j sitting at positions ii and jj, exchanges them, and costs ∣i−j∣|i-j|.

For example, the sequence {9,5,3}\{9, 5, 3\} becomes sorted after a single Manhattan swap. Exchange the first element with the last one and pay 22, the distance between their positions.

Input

The first line contains an integer TT, the number of test cases. Each test case consists of two lines. The first line contains one integer NN (1≤N≤301 \le N \le 30), the length of the sequence SS. The second line contains the NN elements of SS, separated by spaces. All elements are distinct and fit in a 32 bit signed integer.

Output

For each test case, print one line in the form Case #x: y, where xx is the test case number starting from 1 and yy is the minimum cost of sorting the sequence into ascending order using only Manhattan swaps.

Examples2

  1. Example 1

    Input
    2
    3
    9 5 3
    6
    6 5 4 3 2 1
    
    Expected output
    Case #1: 2
    Case #2: 9
    
  2. Example 2

    Input
    3
    1
    42
    2
    2 1
    3
    2 3 1
    
    Expected output
    Case #1: 0
    Case #2: 1
    Case #3: 2