atcoder#AGC023E. [AGC023E] Inversions

[AGC023E] Inversions

Score : 17001700 points

Problem Statement

Snuke has an integer sequence AA whose length is NN. He likes permutations of (1,2,...,N)(1, 2, ..., N), PP, that satisfy the following condition:

  • PiAiP_i \leq A_i for all ii ( 1iN1 \leq i \leq N ).

Snuke is interested in the inversion numbers of such permutations. Find the sum of the inversion numbers over all permutations that satisfy the condition. Since this can be extremely large, compute the sum modulo 109+710^9+7.

Notes

The inversion number of a sequence ZZ whose length NN is the number of pairs of integers ii and jj ( 1i<jN1 \leq i < j \leq N ) such that Zi>ZjZ_i > Z_j.

Constraints

  • 1N2×1051 \leq N \leq 2 \times 10^5
  • 1AiN1 \leq A_i \leq N ( 1iN1 \leq i \leq N )
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

A1A_1 A2A_2 ...... ANA_N

Output

Print the sum of the inversion numbers over all permutations that satisfy the condition.

3
2 3 3
4

There are four permutations that satisfy the condition: (1,2,3)(1,2,3), (1,3,2)(1,3,2), (2,1,3)(2,1,3) and (2,3,1)(2,3,1). The inversion numbers of these permutations are 00, 11, 11 and 22, respectively, for a total of 44.

6
4 2 5 1 6 3
7

Only one permutation (4,2,5,1,6,3)(4,2,5,1,6,3) satisfies the condition. The inversion number of this permutation is 77, so the answer is 77.

5
4 4 4 4 4
0

No permutation satisfies the condition.

30
22 30 15 20 10 29 11 29 28 11 26 10 18 28 22 5 29 16 24 24 27 10 21 30 29 19 28 27 18 23
848414012