[Solution] Wish I Knew How to Sort Codeforces Solution
You are given a binary array (all elements of the array are or ) of length . You wish to sort this array, but unfortunately, your algorithms teacher forgot to teach you sorting algorithms. You perform the following operations until is sorted:
- Choose two random indices and such that . Indices are chosen equally probable among all pairs of indices such that .
- If , then swap elements and .
What is the expected number of such operations you will perform before the array becomes sorted?
It can be shown that the answer can be expressed as an irreducible fraction , where and are integers and . Output the integer equal to . In other words, output such an integer that and .
Each test contains multiple test cases. The first line contains the number of test cases (). Description of the test cases follows.
The first line of each test case contains an integer () — the number of elements in the binary array.
The second line of each test case contains integers () — elements of the array.
It's guaranteed that sum of over all test cases does not exceed .
For each test case print one integer — the value .
Consider the first test case. If the pair of indices will be chosen, these elements will be swapped and array will become sorted. Otherwise, if one of pairs or will be selected, nothing will happen. So, the probability that the array will become sorted after one operation is , the probability that the array will become sorted after two operations is , the probability that the array will become sorted after three operations is and so on. The expected number of operations is .
In the second test case the array is already sorted so the expected number of operations is zero.
In the third test case the expected number of operations equals to so the answer is .
No comments:
Post a Comment