Under construction

Still being built. Things may change

Bridges

Interview

Time limit1sMemory limit1024 MB

Summary
For each range L to R, find the bridge height M (floor average of the endpoints) and sum the scaffolding and tunnel costs over that range.
Level

Medium5 of 10

Topics
Sorting, Prefix sum, Array
Solved
No attempts yet

Problem

Architect Marijonas wants to improve transportation in an area where mountains are lined up in a straight line. The area is described by an array AA of size NN, where A[k]A[k] is the height of the kk-th mountain.

Marijonas plans to build a bridge between two mountains. He has not yet decided which two, but he wants to know the construction cost of a bridge between mountains LiL_i and RiR_i.

The cost is computed as follows.

  • The bridge height MiM_i is the average of the two end heights, rounded down: Mi=⌊A[Li]+A[Ri]2⌋M_i = \left\lfloor \frac{A[L_i] + A[R_i]}{2} \right\rfloor
  • The bridge passes over every mountain kik_i with Li≤ki≤RiL_i \le k_i \le R_i.
  • If A[ki]≤MiA[k_i] \le M_i, scaffolding must be built, and the cost is Mi−A[ki]M_i - A[k_i].
  • If A[ki]>MiA[k_i] > M_i, a tunnel must be dug, and the cost is 11.

Marijonas can compute the cost of one bridge easily, but he wants the costs for QQ pairs of mountains. Compute the construction cost for each query.

Input

The first line contains the array size NN. The second line contains the space-separated integers A[1],A[2],…,A[N]A[1], A[2], \dots, A[N]. The third line contains the number of queries QQ. Each of the next QQ lines contains two space-separated integers LiL_i and RiR_i.

Output

Print QQ lines. Each line contains one integer, the construction cost of a bridge between mountains LiL_i and RiR_i, in the same order as the queries.

Constraints

  • 1≤N,Q≤100 0001 \le N, Q \le 100\,000
  • 1≤Li≤Ri≤N1 \le L_i \le R_i \le N (1≤i≤Q1 \le i \le Q)
  • 1≤A[i]≤10 0001 \le A[i] \le 10\,000 (1≤i≤N1 \le i \le N)

Examples1

  1. Example 1

    Input
    4
    1 2 4 2
    2
    1 3
    1 4
    
    Expected output
    2
    3