Under construction

Still being built. Things may change

Counting close pairs in a range

Time limit3sMemory limit512 MB

Summary
Given a sequence and K, each query asks how many index pairs inside a subarray have value difference at most K.
Level

Hard8 of 10

Topics
Divide and conquer, Prefix sum, Sorting, Binary search
Solved
No attempts yet

Problem

You are given a sequence A1,A2,…,ANA_1, A_2, \dots, A_N of length NN and an integer KK. Write a program that answers MM queries of the following form.

  • l r: print the number of pairs (i,j)(i, j) with l≤i<j≤rl \le i < j \le r and ∣Ai−Aj∣≤K|A_i - A_j| \le K.

Input

The first line contains the length of the sequence NN and the integer KK (1≤N≤1000001 \le N \le 100000, 1≤K≤1000001 \le K \le 100000).

The second line contains A1,A2,…,ANA_1, A_2, \dots, A_N separated by spaces (1≤Ai≤1000001 \le A_i \le 100000).

The third line contains the number of queries MM (1≤M≤1000001 \le M \le 100000).

Each of the next MM lines contains one query as two integers ll and rr (1≤l≤r≤N1 \le l \le r \le N).

Output

For each query, print the answer on its own line, in the order the queries are given.

Examples2

  1. Example 1

    Input
    4 31
    1 16 32 64
    4
    1 4
    1 2
    2 4
    2 3
    
    Expected output
    3
    1
    1
    1
    
  2. Example 2

    Input
    1 1
    1
    1
    1 1
    
    Expected output
    0