GUPTA MECHANICAL

IN THIS WEBSITE I CAN TELL ALL ABOUT TECH. TIPS AND TRICKS APP REVIEWS AND UNBOXINGS ALSO TECH. NEWS .............

Sunday 23 October 2022

[Solution] Wish I Knew How to Sort Codeforces Solution



E. Wish I Knew How to Sort
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a binary array a (all elements of the array are 0 or 1) of length n. You wish to sort this array, but unfortunately, your algorithms teacher forgot to teach you sorting algorithms. You perform the following operations until a is sorted:

  1. Choose two random indices i and j such that i<j. Indices are chosen equally probable among all pairs of indices (i,j) such that 1i<jn.
  2. If ai>aj, then swap elements ai and aj.

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 pq, where p and q are integers and q0(mod998244353). Output the integer equal to pq1mod998244353. In other words, output such an integer x that 0x<998244353 and xqp(mod998244353).

Input

Each test contains multiple test cases. The first line contains the number of test cases t (1t105). Description of the test cases follows.

The first line of each test case contains an integer n (1n200000) — the number of elements in the binary array.

The second line of each test case contains n integers a1,a2,,an (ai{0,1}) — elements of the array.

It's guaranteed that sum of n over all test cases does not exceed 200000.

Output

For each test case print one integer — the value pq1mod998244353.

Note

Consider the first test case. If the pair of indices (2,3) will be chosen, these elements will be swapped and array will become sorted. Otherwise, if one of pairs (1,2) or (1,3) will be selected, nothing will happen. So, the probability that the array will become sorted after one operation is 13, the probability that the array will become sorted after two operations is 2313, the probability that the array will become sorted after three operations is 232313 and so on. The expected number of operations is i=1(23)i113i=3.

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 754 so the answer is 7541249561107(mod998244353).

No comments:

Post a Comment