# https://yukicoder.me/problems/no/878 import math from collections import deque class SegmentTree: """ 非再帰版セグメント木。 更新は「加法」、取得は「最大値」のもの限定。 """ def __init__(self, init_array): n = 1 while n < len(init_array): n *= 2 self.size = n self.array = [-1] * (2 * self.size) for i, a in enumerate(init_array): self.array[self.size + i] = a end_index = self.size start_index = end_index // 2 while start_index >= 1: for i in range(start_index, end_index): self.array[i] = max(self.array[2 * i], self.array[2 * i + 1]) end_index = start_index start_index = end_index // 2 def set(self, x, a): index = self.size + x self.array[index] = a while index > 1: index //= 2 self.array[index] = max(self.array[2 * index], self.array[2 * index + 1]) def get_max(self, l, r): L = self.size + l; R = self.size + r # 2. 区間[l, r)の最大値を求める s = -1 while L < R: if R & 1: R -= 1 s = max(s, self.array[R]) if L & 1: s = max(s, self.array[L]) L += 1 L >>= 1; R >>= 1 return s def main(): N, Q = map(int, input().split()) A = list(map(int, input().split())) queries = [] for _ in range(Q): _, l, r = map(int, input().split()) queries.append((l - 1, r - 1)) # 各aについて「高い要素」でなくなる最大の左端候補を求める seg_tree = SegmentTree([-1] * (N + 1)) max_left_list = [-1] * N for i in range(N): a = A[i] ans = seg_tree.get_max(a + 1, N + 1) max_left_list[i] = ans seg_tree.set(a, i) # Nについての平方分割 sqrt_n = int(math.sqrt(N)) partitions = [] left = 0 while left < N: partitions.append((left, min(N, left + sqrt_n))) left += sqrt_n partitions_array = [] for i in range(len(partitions)): l, r = partitions[i] cum_array = [0] * (N + 1) for j in range(l, r): a = A[i] l_index = max_left_list[j] cum_array[l_index + 1] += 1 cum_a = 0 for n in range(N + 1): cum_a += cum_array[n] cum_array[n] = cum_a partitions_array.append(cum_array) for l, r in queries: left_i = -1 right_i = -1 for i in range(len(partitions)): if l < partitions[i][1]: left_i = i if r < partitions[i][1]: right_i = i answer = 0 if abs(right_i - left_i) <= 1: for i in range(l, r + 1): if l > max_left_list[i]: answer += 1 else: for i in range(l, partitions[left_i][1]): if l > max_left_list[i]: answer += 1 for i in range(partitions[right_i][0], r + 1): if l > max_left_list[i]: answer += 1 for i in range(left_i + 1, right_i): a = partitions_array[i][l + 1] answer += partitions_array[i][1] - partitions_array[i][0] - a print(answer) if __name__ == "__main__": main()