Sorting Array (Large)
Time limit30sMemory limit512 MB
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 containing every integer from 1 to exactly once. The integers in start in an arbitrary order. Besides the input order, the algorithm depends on two integers and . The algorithm works as follows:
- Partition into non-empty contiguous subarrays such that concatenating them in order, , gives .
- Sort each subarray individually.
- Choose at most 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 and . One possible partition into 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 , find the maximum number of subarrays 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, .
test cases follow. Each test case consists of two lines. The first line contains two integers and , as described above.
The second line contains integers representing the array .
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 .
Constraints
- for all
- for all
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]