#P7601. [THUPC 2021] 区间本质不同逆序对

[THUPC 2021] 区间本质不同逆序对

Description

You are given a sequence aa of length nn.

There are mm queries. Each query gives an interval [l,r][l, r]. For each query, compute $|\{(a_i, a_j) : l \le i < j \le r \wedge a_i > a_j\}|$.

1n1051 \le n \le 10^5, 1m5×1051 \le m \le 5 \times 10^5.

Input Format

The first line contains a positive integer nn.

The second line contains nn positive integers. The ii-th number aia_i is the value at position ii in the sequence. It is guaranteed that 1ain1 \leq a_i \leq n.

The third line contains a positive integer mm.

Then follow mm lines. Each line contains two positive integers separated by two spaces, denoted l,rl, r, representing one query. It is guaranteed that 1lrn1 \leq l \le r \leq n.

Output Format

Output mm lines. The ii-th line contains one integer, which is the answer to the ii-th query.

5
2 1 3 2 1
4
2 4
1 5
3 5
2 2
1
3
3
0

Hint

[Sample Explanation]

For the first query, the set is {(3,2)}\{(3,2)\}.

For the second and third queries, the set is {(2,1),(3,1),(3,2)}\{(2,1),(3,1),(3,2)\}.

For the fourth query, the set is the empty set.

[Source]

From the 2021 Tsinghua University Student Programming Contest and Intercollegiate Invitational (THUPC2021).

Resources such as editorial solutions can be found at https://github.com/yylidiw/thupc_0/tree/master.

Translated by ChatGPT 5