Under construction

Still being built. Things may change

Sorting Array (Large)

Time limit30sMemory limit512 MB

Summary
Given a permutation of 1..N and a limit P, partition it into contiguous blocks, sort each, then reorder at most P blocks by swaps; maximize the number of blocks.
Level

Hard8 of 10

Topics
Greedy, Sorting, Implementation, Combinatorics
Solved
No attempts yet

Problem

We are building a somewhat unusual algorithm that sorts an array AA containing every integer from 1 to NN exactly once. The integers in AA start in an arbitrary order. Besides the input order, the algorithm depends on two integers PP and KK. The algorithm works as follows:

  1. Partition AA into KK non-empty contiguous subarrays A1,A2,…,AKA_1, A_2, \ldots, A_K such that concatenating them in order, A1A2…AKA_1A_2 \ldots A_K, gives AA.
  2. Sort each subarray individually.
  3. Choose at most PP of the subarrays, and swap any two of the chosen subarrays any number of times. Subarrays that are not chosen stay in place.

For example, let A=[1 5 4 3 2]A = [1\ 5\ 4\ 3\ 2] and P=2P = 2. One possible partition 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 array and value of PP, find the maximum number of subarrays KK such that, choosing the partition and the swaps wisely, the array ends up sorted.

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 two integers NN and PP, as described above.

The second line contains NN integers X1,X2,…,XNX_1, X_2, \ldots, X_N representing the array AA.

Output

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

Constraints

  • 1≤T≤1001 \le T \le 100
  • 1≤N≤50001 \le N \le 5000
  • 1≤P≤31 \le P \le 3
  • 1≤Xi≤N1 \le X_i \le N for all ii
  • Xi≠XjX_i \ne X_j for all i≠ji \ne j

Notes

Case #1: the same as the walkthrough in the statement.

Case #2:

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

Case #3:

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

Case #4:

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

Case #5:

[1] [2] [6] [4] [5] [3]
Swap [6] and [3]: [1] [2] [3] [4] [5] [6]

Examples1

  1. Example 1

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