Sorting Array (Small)

Split a permutation into K contiguous blocks, sort each block, then reorder at most P=2 blocks by swapping to fully sort the array; find the largest feasible K.

Medium7ArraySortingGreedyDynamic programmingNo attempts yetTime limit5sMemory limit512 MB

Problem

We are building a somewhat unusual algorithm that sorts an array AA containing every integer from 1 to NN exactly once. The elements of AA start in an arbitrary order. Besides the input order, the algorithm depends on two integers PP and KK, where PP is at most 3. Here is how it works.

  1. Split AA into KK non-empty subarrays A1,A2,,AKA_1, A_2, \dots, A_K so that concatenating them in order as A1A2AKA_1 A_2 \dots A_K gives back AA.
  2. Sort each subarray on its own.
  3. Choose at most PP of the subarrays, then swap the places of two chosen subarrays as many times as you want.

For example, take A=[1 5 4 3 2]A = [1\ 5\ 4\ 3\ 2] and P=2P = 2. One way to split it into K=4K = 4 subarrays is:

A1 = [1]
A2 = [5]
A3 = [4]
A4 = [3 2]

After sorting each subarray

A1 = [1]
A2 = [5]
A3 = [4]
A4 = [2 3]

After swapping A4 and A2

A1 = [1]
A2 = [2 3]
A3 = [4]
A4 = [5]

We want to show that the algorithm suits distributed environments. For a fixed input and a fixed PP, find the largest KK for which a careful choice of the split and the swaps sorts the original array.

Input

The first line of the input gives the number of test cases, TT.

TT test cases follow. Each test case consists of two lines. The first line contains the two integers NN and PP described above. The second line contains NN integers X1,X2,,XNX_1, X_2, \dots, X_N representing the array AA.

Output

For each test case, output one line containing Case #x: y, where xx is the test case number starting from 1, and yy is the largest possible value of KK.

Constraints

  • 1T1001 \le T \le 100
  • 1N50001 \le N \le 5000
  • 1XiN1 \le X_i \le N for every ii
  • XiXjX_i \ne X_j whenever iji \ne j
  • P=2P = 2

Hint

The first test case of the example input is the walkthrough given in the statement.

The second test case is split like this.

[4 5] [1 2 3]
Swap the two subarrays: [1 2 3] [4 5]

The third test case is split like this.

[6] [3 5 2 4] [1]
Sort [3 5 2 4], then swap [6] and [1]: [1] [2 3 4 5] [6]