Depth of Cartesian Tree
시간 제한8초메모리 제한2048 MB
각 부분 배열 질의마다 해당 구간의 데카르트 트리를 만들고 모든 노드 깊이의 합을 구한다.
문제
The cartesian tree of a sequence of distinct integers, is an unique binary tree defined as follows.
- The cartesian tree of a sequence with one element is the tree of one node;
- The root of the cartesian tree of a sequence corresponds to the maximum value of the sequence;
- If the root does not correspond to the leftmost index, the left subtree is the cartesian tree of the subarray left to it;
- If the root does not correspond to the rightmost index, the right subtree is the cartesian tree of the subarray right to it.
In a binary tree, the depth of a node is defined as the distance from the root to the node.
You are given a permutation of elements . You must solve queries of the following kind.
- : Assume that you construct a cartesian tree of the subsequence . Answer the sum of the depths of all nodes in the tree.
입력
The first line contains two integers and () --- the length of the permutation and number of queries respectively.
The second line contains distinct integers () --- the permutation .
The next lines contain two integers () --- the bounds of query .
출력
For each query, output the answer on a new line.