PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000098. Chọn ghế ngẫu nhiên tạo dãy tăng (Random IS)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Chọn ghế ngẫu nhiên tạo dãy tăng (Random IS)

Random IS

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

There are NN chairs in a row from left to right. The chair at position ii has ID aia_i. The IDs form a permutation of 1,2,…,N1,2,\ldots,N and are all distinct.

Initially no chair is marked. A selection of marked chairs is good when their IDs, read from left to right, form a strictly increasing sequence.

Repeat the following procedure:

  1. Consider all unmarked chairs. A chair is eligible if marking it would keep the marked selection good.
  2. If no eligible chair remains, discard all unmarked chairs and stop.
  3. Otherwise, if kk chairs are eligible, choose one uniformly at random among them, mark it, and return to step 1.

Let EE be the expected number of chairs that remain when the procedure stops. Write E=P/QE=P/Q in lowest terms. Let M=109+7M=10^9+7; the statement guarantees that QQ has a multiplicative inverse modulo MM.

Output the unique integer RR in [0,M−1][0,M-1] satisfying P≡Q⋅R(modM)P\equiv Q\cdot R\pmod M, equivalently R=P⋅Q−1 mod MR=P\cdot Q^{-1}\bmod M.

Input

The first line contains NN. The second line contains NN integers a1,a2,…,aNa_1,a_2,\ldots,a_N, the chair IDs from left to right.

Output

Print one integer RR, representing the expected number of remaining chairs modulo 109+710^9+7.

Subtasks

  • Subtask 1 (20 points): 1≤N≤71\le N\le7; a1,…,aNa_1,\ldots,a_N is a permutation of 1,2,…,N1,2,\ldots,N, with no repeated value.
  • Subtask 2 (30 points): 1≤N≤1501\le N\le150; a1,…,aNa_1,\ldots,a_N is a permutation of 1,2,…,N1,2,\ldots,N, with no repeated value.
  • Subtask 3 (50 points): 1≤N≤20001\le N\le2000; a1,…,aNa_1,\ldots,a_N is a permutation of 1,2,…,N1,2,\ldots,N, with no repeated value.

Examples

Example 1

Input

3
3 1 2

Output

666666673

Explanation

Initially all three chairs are eligible, each with probability 1/31/3 of being chosen first. Choosing ID 33 at the first position prevents choosing IDs 11 and 22 later, leaving 11 chair. Choosing ID 11 or ID 22 first eventually marks both chairs with IDs 1,21,2, leaving 22 chairs. The expectation is (1+2+2)/3=5/3(1+2+2)/3=5/3. Since the inverse of 33 modulo 109+710^9+7 is 333333336333333336, the required residue is 666666673666666673.

Example 2

Input

2
1 2

Output

2

Explanation

Whichever chair is marked first, the other can still be marked because (1,2)(1,2) is strictly increasing. Every run leaves exactly 22 chairs, giving expectation and modular answer 22.