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 a_i > a_j.

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

1 \le N \le 5 \cdot 10^5

Subtask 1 [30%]

1 \le N \le 2 \cdot 10^3

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 i^\text{th} element is missing.

Output Specification

If the answer can be expressed in the form \frac{P}{Q}, where P and Q are relatively prime, output PQ^{-1} \pmod{10^9+7}, where Q^{-1} is the modular inverse of Q. It is guaranteed that the answer is rational.

Sample Input 1

5
4 3 0 2 1

Sample Output 1

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

2
0 0

Sample Output 2

500000004

Explanation for Sample Output 2

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

The expected number of inversions is \frac{1}{2!} + \frac{0}{2!} = \frac{1}{2}. The answer is 1 \cdot 2^{-1}, the modular inverse of 2 is 500\,000\,004, so the answer is 1 \cdot 500\,000\,004 = 500\,000\,004.

Sample Input 3

6
5 0 2 0 1 0

Sample Output 3

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 \frac{8}{3!} + \frac{9}{3!} + \frac{9}{3!} + \frac{10}{3!} + \frac{10}{3!} + \frac{11}{3!} = \frac{57}{6} = \frac{19}{2}. The answer is 19 \cdot 2^{-1}, the modular inverse of 2 is 500\,000\,004, so the answer is (19 \cdot 500\,000\,004) \bmod (10^9+7) = 500\,000\,013.


Comments

There are no comments at the moment.