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

#FT0000079. Thứ hạng từ điển của hoán vị (The Permutation Game Again)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Thứ hạng từ điển của hoán vị (The Permutation Game Again)

The Permutation Game Again

Source: SPOJ

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation p1,p2,…,pnp_1,p_2,\ldots,p_n of integers 1,2,…,n1,2,\ldots,n, with each number appearing exactly once.

Consider all permutations of these numbers, ordered in increasing lexicographic order. At the first position where two permutations differ, the one containing the smaller number is ordered first. The first permutation has rank 1, not rank 0.

Compute the rank of the given permutation and output its remainder modulo 109+710^9+7.

Input

The first line contains integer nn.

The second line contains nn integers p1,…,pnp_1,\ldots,p_n, forming a permutation of 1,…,n1,\ldots,n.

Output

Print one integer: the 1-based lexicographic rank of the permutation modulo 109+710^9+7.

Subtasks

  • Subtask 1 (20 points): 1≤n≤81\le n\le 8; 1≤pi≤n1\le p_i\le n; each integer from 11 to nn occurs exactly once.

  • Subtask 2 (30 points): 1≤n≤20001\le n\le 2000; 1≤pi≤n1\le p_i\le n; each integer from 11 to nn occurs exactly once.

  • Subtask 3 (50 points): 1≤n≤2000001\le n\le 200000; 1≤pi≤n1\le p_i\le n; each integer from 11 to nn occurs exactly once.

Examples

Input

4
2 1 4 3

Output

8

Explanation

For n=4n=4, there are 4!=244!=24 permutations. The first 3!=63!=6 begin with 11.

Permutations beginning with 22 come next. Within this group, prefix 2,12,1 precedes prefixes 2,32,3 and 2,42,4. Exactly two permutations begin with 2,12,1:

  • [2,1,3,4][2,1,3,4] has rank 77.
  • [2,1,4,3][2,1,4,3] has rank 88.

The input is the latter, so its 1-based rank is 88 and the required output is 8.