Depth of Cartesian Tree

시간 제한8초메모리 제한2048 MB

요약
각 부분 배열 질의마다 해당 구간의 데카르트 트리를 만들고 모든 노드 깊이의 합을 구한다.
난이도

어려움10점 중 9점

유형
트리, 분할 정복, 세그먼트 트리, 누적 합
정답자
아직 제출이 없습니다

문제

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 pp of elements 1,2,⋯ ,n1,2,\cdots,n. You must solve qq queries of the following kind.

  • ll rr: Assume that you construct a cartesian tree of the subsequence p_l,p_l+1,⋯ ,p_rp\_l,p\_{l+1},\cdots,p\_r. Answer the sum of the depths of all nodes in the tree.

입력

The first line contains two integers nn and qq (1≤n,q≤1061 \leq n, q \leq 10^6) --- the length of the permutation and number of queries respectively.

The second line contains nn distinct integers p_1,p_2,⋯ ,p_np\_1, p\_2, \cdots, p\_n (1≤p_i≤n1 \leq p\_i \leq n) --- the permutation pp.

The next qq lines contain two integers l_i,r_il\_i, r\_i (1≤l_i≤r_i≤n1 \leq l\_i \leq r\_i \leq n) --- the bounds of query ii.

출력

For each query, output the answer on a new line.

예제1

  1. 예제 1

    입력
    7 10
    1 5 4 7 2 6 3
    1 7
    1 3
    2 4
    3 5
    4 6
    5 7
    1 4
    2 5
    3 6
    4 7
    
    예상 출력
    10
    2
    3
    2
    3
    2
    5
    4
    4
    5