Under construction

Still being built. Things may change

Matryoshka Dolls

Time limit5sMemory limit512 MB

Summary
For each query segment, repeatedly remove the minimum and sum the index distances to the next smallest element until one element remains.
Level

Hard8 of 10

Topics
Array, Sorting, Union-find, Divide and conquer
Solved
No attempts yet

Statement

Denisson is an average enjoyer of Matryoshka dolls. A set of matryoshkas consists of a wooden figure that separates at the middle, top from bottom, to reveal a smaller figure of the same sort inside. That figure has another figure inside it, and so on. Recently he bought a set of these toys and placed them on the table in some order. The set has exactly nn dolls of different sizes, so the current order can be represented as a permutation pp of length nn, where pip_i is the size of the ii-th doll. Today Denisson wants to relax with his toys and plays the following game. First, he chooses a segment [l,r][l, r] of the permutation. Then he takes the smallest matryoshka on this segment and places it into the matryoshka of the next size. The time for this step is ∣i−j∣|i - j|, where pip_i and pjp_j are the sizes of the two smallest dolls on the chosen segment. He repeats this step until only one matryoshka is left on the segment. The total time of the game is the sum of the times of all steps. For each of the qq segments [li,ri][l_i, r_i], Denisson wants to know the total time of the game on that segment. He hopes you will not spend too much time finding these values.

Input

The first line contains two integers nn and qq (1≤n≤1051 \leq n \leq 10^5, 1≤q≤5⋅1051 \leq q \leq 5 \cdot 10^5), the number of matryoshkas and the number of requests. The second line contains the permutation pp (1≤pi≤n1 \leq p_i \leq n). Each of the following qq lines contains two integers lil_i and rir_i (1≤li≤ri≤n1 \leq l_i \leq r_i \leq n), the endpoints of the ii-th segment.

Output

For the ii-th request, print the total time needed to play the game on the segment [li,ri][l_i, r_i].

Examples1

  1. Example 1

    Input
    5 5
    1 5 2 4 3
    1 5
    1 4
    1 3
    1 2
    1 1
    
    Expected output
    7
    5
    3
    1
    0