C. Coloring Game
Problem Statement
Alice and Bob are playing a game using an integer array of size .
Initially, all elements of the array are colorless. First, Alice chooses 3 elements and colors them red. Then Bob chooses any element and colors it blue (if it was red — recolor it). Alice wins if the sum of the red elements is strictly greater than the value of the blue element.
Your task is to calculate the number of ways that Alice can choose 3 elements in order to win regardless of Bob’s actions.
Input
The first line contains a single integer — the number of test cases.
The first line of each test case contains a single integer .
The second line contains integers .
Additional constraint on the input: the sum of over all test cases doesn’t exceed 5000.
Output
For each test case, print a single integer — the number of ways that Alice can choose 3 elements in order to win regardless of Bob’s actions.
Solution
First, sort the array in non-decreasing order. This ensures that for any three elements (where ), we have .
For any three elements (where ), Alice can guarantee a win if the following conditions are met:
- (this ensures that the sum of the red elements is strictly greater than the blue element). This condition handles the case when Bob chooses the largest element as the blue element.
- . This ensures that the sum of the red elements is strictly greater than the largest element in the array, which is . This condition handles the case when Bob chooses the largest element as the blue element.
As long as these two conditions are satisfied, Alice can guarantee a win regardless of Bob’s choice.
We use two nested loops to iterate over all pairs and and check if there exists an such that both conditions are satisfied. To find , we can use binary search to find the largest and smallest that satisfies the conditions.