#HK4107. 「BalkanOI 2023 Day1」Permutations

「BalkanOI 2023 Day1」Permutations

Description

You are given a permutation p[1],p[2],,p[n]p[1], p[2], \ldots, p[n] of the numbers 1,2,,n1,2, \ldots, n. You need to answer qq queries.

The ii-th query (for i{1,,q}i \in\{1, \ldots, q\} ) is described by the numbers L[i]L[i] and R[i]R[i] (1L[i]R[i]n1 \leq L[i] \leq R[i] \leq n). The answer to the query is the number of permutations of length nn that start with the sequence p[L[i]],p[L[i]+1],,p[R[i]1],p[R[i]]p[L[i]], p[L[i]+1], \ldots, p[R[i]-1], p[R[i]] and that, additionally, satisfy the property that the length of their longest decreasing subsequence is at most 22. Since the answers can be very large, output them modulo 109+710^{9}+7.

For a sequence a[1],a[2],,a[k]a[1], a[2], \ldots, a[k], the length of the longest decreasing subsequence is the greatest integer tt such that there are tt indices s[1],s[2],,s[t]s[1], s[2], \ldots, s[t] with the properties 1s[1]<s[2]<<s[t]k1 \leq s[1]<s[2]<\ldots<s[t] \leq k and a[s[1]]>a[s[2]]>>a[s[t]]a[s[1]]>a[s[2]]>\ldots>a[s[t]].

Input format

The first line contains the number nn.

The second line contains the numbers p[1],,p[n]p[1], \ldots, p[n], i.e., nn distinct integers from the interval [1,n][1, n].

The third line contains the number qq.

The next qq lines specify the queries: the ii-th of those lines, for i{1,,q}i \in\{1, \ldots, q\}, contains the numbers L[i]L[i] and R[i]R[i].

Output format

For each query, print the number of permutations modulo 109+710^{9}+7. Each should be on a separate line.

Input bounds

  • 1n31051 \leq n \leq 3 \cdot 10^{5}.
  • 1q31051 \leq q \leq 3 \cdot 10^{5}.

Subtasks

  1. (6 points) n10,q10n \leq 10, q \leq 10.
  2. (7 points) n1000,q1000n \leq 1000, q \leq 1000. Each query contains p[j]=np[j]=n in its interval.
  3. (9 points) Each query contains p[j]=np[j]=n in its interval.
  4. (12 points) n1000,q1000n \leq 1000, q \leq 1000. For each i{1,,n}i \in\{1, \ldots, n\}, p[i]=ip[i]=i, and for each j{1,,q}j \in\{1, \ldots, q\} ,L[j]=1L[j]=1.
  5. (18 points) For each i{1,,n},p[i]=ii \in\{1, \ldots, n\}, p[i]=i, and for each j{1,,q},L[j]=1j \in\{1, \ldots, q\}, L[j]=1.
  6. (12 points) n1000,q1000n \leq 1000, q \leq 1000.
  7. (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\langle 1,2,3,4,5\rangle that start with 44 and have the length of the longest decreasing subsequence at most $2¥. These are:

  • 4,1,2,3,5\langle 4,1,2,3,5\rangle;
  • 4,1,2,5,3\langle 4,1,2,5,3\rangle;
  • 4,1,5,2,3\langle 4,1,5,2,3\rangle;
  • 4,5,1,2,3\langle 4,5,1,2,3\rangle.