Matryoshka Dolls
Time limit5sMemory limit512 MB
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 dolls of different sizes, so the current order can be represented as a permutation of length , where is the size of the -th doll. Today Denisson wants to relax with his toys and plays the following game. First, he chooses a segment 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 , where and 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 segments , 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 and (, ), the number of matryoshkas and the number of requests. The second line contains the permutation (). Each of the following lines contains two integers and (), the endpoints of the -th segment.
Output
For the -th request, print the total time needed to play the game on the segment .