Description
You are given a permutation p[1],p[2],…,p[n] of the numbers 1,2,…,n. You need to answer q queries.
The i-th query (for i∈{1,…,q} ) is described by the numbers L[i] and R[i] (1≤L[i]≤R[i]≤n). The answer to the query is the number of permutations of length n that start with the sequence p[L[i]],p[L[i]+1],…,p[R[i]−1],p[R[i]] and that, additionally, satisfy the property that the length of their longest decreasing subsequence is at most 2. Since the answers can be very large, output them modulo 109+7.
For a sequence a[1],a[2],…,a[k], the length of the longest decreasing subsequence is the greatest integer t such that there are t indices s[1],s[2],…,s[t] with the properties 1≤s[1]<s[2]<…<s[t]≤k and a[s[1]]>a[s[2]]>…>a[s[t]].
The first line contains the number n.
The second line contains the numbers p[1],…,p[n], i.e., n distinct integers from the interval [1,n].
The third line contains the number q.
The next q lines specify the queries: the i-th of those lines, for i∈{1,…,q}, contains the numbers L[i] and R[i].
For each query, print the number of permutations modulo 109+7. Each should be on a separate line.
- 1≤n≤3⋅105.
- 1≤q≤3⋅105.
Subtasks
- (6 points) n≤10,q≤10.
- (7 points) n≤1000,q≤1000. Each query contains p[j]=n in its interval.
- (9 points) Each query contains p[j]=n in its interval.
- (12 points) n≤1000,q≤1000. For each i∈{1,…,n}, p[i]=i, and for each j∈{1,…,q} ,L[j]=1.
- (18 points) For each i∈{1,…,n},p[i]=i, and for each j∈{1,…,q},L[j]=1.
- (12 points) n≤1000,q≤1000.
- (36 points) No additional constraints.
5
4 2 1 5 3
4
1 1
2 3
2 4
1 3
4
5
1
0
For the first query, consider that there are four permutations of the sequence ⟨1,2,3,4,5⟩ that start with 4 and have the length of the longest decreasing subsequence at most $2¥. These are:
- ⟨4,1,2,3,5⟩;
- ⟨4,1,2,5,3⟩;
- ⟨4,1,5,2,3⟩;
- ⟨4,5,1,2,3⟩.