#P8078. [WC2022] 秃子酋长

[WC2022] 秃子酋长

Background

5s 512M -O2

Problem Description

It is said that in the Minsk Aerospace Bureau, there is a powerful Bald Chieftain.

The Bald Chieftain has boundless magic power. He has no hair on his head, and his head is very hard. He can also run fairly fast.

One day, the Peashooter came to the Minsk Aerospace Bureau.

To test this newcomer, the Bald Chieftain gave him the following problem:

Given a permutation a1,,ana_1, \dots, a_n of length nn, there are mm queries. In each query, for the interval [l,r][l, r], consider the numbers in this interval after sorting. Take the positions of these numbers in the original sequence, and compute the sum of the absolute differences between the positions of adjacent numbers in the sorted order.

Input Format

The first line contains two integers n,mn, m.

The next line contains nn integers, representing the elements of the sequence aa in order.

Then follow mm lines, each containing two integers l,rl, r, representing one query.

Output Format

For each query, output one integer per line, representing the answer.

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

Hint

Sample Explanation

For the first query, 2,32, 3 becomes 2,32, 3 after sorting. Their positions in the original sequence are 3,43, 4. The sum of absolute differences of positions of adjacent elements is 34=1|3 - 4| = 1.

For the second query, 4,2,3,14, 2, 3, 1 becomes 1,2,3,41, 2, 3, 4 after sorting. Their positions in the original sequence are 5,3,4,25, 3, 4, 2. The sum of absolute differences of positions of adjacent elements is 53+34+42=5|5 - 3| + |3 - 4| + |4 - 2| = 5.

Constraints

For 10%10\% of the testdata, n,m103n, m \leq 10^3.
For another 10%10\% of the testdata, n,m5×104n, m \leq 5 \times 10^4.
For another 10%10\% of the testdata, n,m105n, m \leq 10^5.
For another 10%10\% of the testdata, n,m2×105n, m \leq 2 \times 10^5.
For another 20%20\% of the testdata, aii10|a_i - i| \leq 10.
For another 20%20\% of the testdata, m=n(n1)2m=\dfrac{n(n-1)}{2}.
For the remaining testdata, there are no special restrictions.

For 100%100\% of the testdata, it holds that 1n,m5×1051 \leq n, m \leq 5 \times 10^5, 1ain1 \leq a_i \leq n, all aia_i are distinct, 1lrn1 \leq l \leq r \leq n, and all values are integers.

Translated by ChatGPT 5