Expected Inversions

View as PDF

Submit solution


Points: 12 (partial)
Time limit: 2.0s
Memory limit: 256M

Author:
Problem types

Josh is given an array a of length N, where every element is in the range [1,N] inclusive. However, some elements are missing and are denoted with the value 0.

Josh, being the innovator he is, decides to randomly assign the missing elements so that the resulting array is a permutation of the first N positive integers. Your task is to find the expected number of inversions after Josh has finished filling in missing values!

An inversion is defined to be a pair of indices (i,j) such that i<j and ai>aj.

Note: It is guaranteed that there will be at least 1 way Josh can fill in the missing elements to result in a permutation of the first N positive integers.

Constraints

1N5105

Subtask 1 [30%]

1N2103

Subtask 2 [70%]

No additional constraints.

Input Specification

The first line will contain N, the length of Josh's array.

The next line will contain N space-separated integers in the range [0,N], with a value of 0 at position i meaning that the ith element is missing.

Output Specification

If the answer can be expressed in the form PQ, where P and Q are relatively prime, output PQ1(mod109+7), where Q1 is the modular inverse of Q. It is guaranteed that the answer is rational.

Sample Input 1

Copy
5
4 3 0 2 1

Sample Output 1

Copy
8

Explanation for Sample Output 1

There is only 1 way Josh can assign values to missing elements.

The resulting array is [4,3,5,2,1] and there are 8 inversions.

Sample Input 2

Copy
2
0 0

Sample Output 2

Copy
500000004

Explanation for Sample Output 2

There are 2 valid arrays, [1,2] and [2,1].

The expected number of inversions is 12!+02!=12. The answer is 121, the modular inverse of 2 is 500000004, so the answer is 1500000004=500000004.

Sample Input 3

Copy
6
5 0 2 0 1 0

Sample Output 3

Copy
500000013

Explanation for Sample Output 3

There are 6 valid arrays, [5,3,2,4,1,6], [5,3,2,6,1,4], [5,4,2,3,1,6], [5,4,2,6,1,3], [5,6,2,3,1,4], [5,6,2,4,1,3].

The expected number of inversions is 83!+93!+93!+103!+103!+113!=576=192. The answer is 1921, the modular inverse of 2 is 500000004, so the answer is (19500000004)mod(109+7)=500000013.


Comments


  • 2
    Bolaloon  commented on Nov. 29, 2024, 3:34 a.m.

    There are testcases without any missing elements.


    • 2
      bruce  commented on Nov. 29, 2024, 8:55 p.m.

      Correct. The problem doesn't guarantee that there are missing numbers. Your code should cover the case.