#P1943E2. MEX Game 2 (Hard Version)
MEX Game 2 (Hard Version)
Description
This is the hard version of the problem. The only difference between the two versions is the constraint on , and the sum of . You can make hacks only if both versions of the problem are solved.
Alice and Bob play yet another game on an array of size . Alice starts with an empty array . Both players take turns playing, with Alice starting first.
On Alice's turn, she picks one element from , appends that element to , and then deletes it from .
On Bob's turn, he picks at most elements from , and then deletes it from .
The game ends when the array is empty. Alice's score is defined to be the MEX of . Alice wants to maximize her score while Bob wants to minimize it. Find Alice's final score if both players play optimally.
The array will be given in compressed format. Instead of giving the elements present in the array, we will be giving their frequencies. Formally, you will be given , the maximum element in the array, and then integers , where represents the number of times occurs in the array .
The (minimum excludant) of an array of integers is defined as the smallest non-negative integer which does not occur in the array. For example:
- The MEX of is , because does not belong to the array.
- The MEX of is , because and belong to the array, but does not.
- The MEX of is , because , , and belong to the array, but does not.
Each test contains multiple test cases. The first line contains a single integer () — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers and ().
The second line contains integers ().
It is guaranteed the sum of over all test cases does not exceed .
For each test case, find Alice's score if both players play optimally.
Input
Each test contains multiple test cases. The first line contains a single integer () — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers and ().
The second line contains integers ().
It is guaranteed the sum of over all test cases does not exceed .
Output
For each test case, find Alice's score if both players play optimally.
Note
In the first test case, the array is . A possible game with a score of is as follows:
- Alice chooses the element . After this move, and .
- Bob chooses to remove the elements , and . After this move, and .
- Alice chooses the element . After this move, and .
- Bob removes the remaining elements , , and . After this move, and .
At the end, which has a MEX of . Note that this is an example game and does not necessarily represent the optimal strategy for both players.
In the second test case, Alice can choose a in her first turn, guaranteeing that her score is at least . While Bob can remove all copies element in his first turn, thus guaranteeing that Alice's score cannot exceed . So Alice's score is if both players play optimally.