Under construction

Still being built. Things may change

Sequence and Queries 36

Time limit1sMemory limit512 MB

Summary
Given distinct values 1 to N, for each query [l, r] count the pairs x at most y inside it where max minus min equals y minus x.
Level

Hard8 of 10

Topics
Array, Sliding window, Divide and conquer
Solved
No attempts yet

Problem

A sequence A1,A2,…,ANA_1, A_2, \ldots, A_N of length NN is given. Every number in the sequence is between 1 and NN inclusive, and all numbers are distinct. Write a program that handles the following query.

  • l r: Print the number of integer pairs (x,y)(x, y) with l≤x≤y≤rl \le x \le y \le r that satisfy (max⁡i=xyAi)−(min⁡i=xyAi)=y−x\left(\max_{i=x}^{y} A_i\right) - \left(\min_{i=x}^{y} A_i\right) = y - x.

Input

The first line contains the size of the sequence NN. (1≤N≤120,0001 \le N \le 120{,}000)

The second line contains A1,A2,…,ANA_1, A_2, \ldots, A_N. All numbers are distinct. (1≤Ai≤N1 \le A_i \le N)

The third line contains the number of queries MM. (1≤M≤120,0001 \le M \le 120{,}000)

Each of the following MM lines contains one query. (1≤l≤r≤N1 \le l \le r \le N)

Output

Print the result of each query on its own line.

Examples1

  1. Example 1

    Input
    5
    1 3 2 5 4
    5
    1 1
    1 2
    1 3
    1 4
    1 5
    
    Expected output
    1
    2
    5
    6
    10