Under construction

Still being built. Things may change

Merging Branches

Time limit2sMemory limit1024 MB

Summary
Given N sorted sales territories, answer Q queries for the minimum widening K that merges branches s through e into one.
Level

Medium6 of 10

Topics
Array, Greedy, Binary search
Solved
No attempts yet

Problem

Moloco is an ad-tech company in KAIST city, which can be modeled as a 1-dimensional line. Moloco has NN branches, and the sales territory of the iith branch is the range [li,ri][l_i, r_i]. It is known that li<ril_i < r_i for all ii, and ri≤li+1r_i \leq l_{i+1} for 1≤i≤N−11 \leq i \leq N-1.

Two branches intersect if some point is included in both branches' sales territories. For example, [3,5][3, 5] and [5,7][5, 7] intersect, and [1,4][1, 4] and [2,5][2, 5] intersect. But [1,2][1, 2] and [3,5][3, 5] do not intersect.

Moloco can widen the sales territory of every branch by spending on advertisement. If Moloco spends KK won, then every branch may widen its sales territory by at most KK length units. The start and end of each widened territory must be integers.

Formally, let the new sales territory of the iith branch be [li′,ri′][l_i', r_i']. The following conditions must hold.

  • li′≤lil_i' \leq l_i and ri≤ri′r_i \leq r_i'
  • (li−li′)+(ri′−ri)≤K(l_i - l_i') + (r_i' - r_i) \leq K
  • li′l_i' and ri′r_i' are both integers

Moloco wants to merge all branches into one, because too many branches make company management difficult. Two branches can be merged if they intersect. The sales territory of the merged branch is the union of the two original territories.

Fig 1. Illustration of the first sample case when K=4K=4.

You work for Moloco. You want to examine hypothetical scenarios where Moloco owns only the ssth through eeth branches. For each query, find the minimum cost to merge all of those branches into one.

Input

The first line contains two integers NN and QQ (1≤N≤50001 \leq N \leq 5000, 1≤Q≤1061 \leq Q \leq 10^6).

The next NN lines each contain two integers lil_i and rir_i (1≤li<ri≤1091 \leq l_i < r_i \leq 10^9), the sales territory of the iith branch. It is guaranteed that ri≤li+1r_i \leq l_{i+1} for all 1≤i≤N−11 \leq i \leq N-1.

The next QQ lines each contain two integers sis_i and eie_i (1≤si≤ei≤N1 \leq s_i \leq e_i \leq N), describing the iith query.

Output

Print QQ lines. The iith line contains the answer to the iith query, which is the minimum cost to merge branches sis_i through eie_i.

Hint

If there is only one branch, no cost is needed.

Examples2

  1. Example 1

    Input
    5 2
    1 3
    5 6
    10 15
    20 24
    28 33
    1 5
    3 5
    
    Expected output
    4
    3
    
  2. Example 2

    Input
    7 7
    1 3
    6 10
    14 18
    18 19
    22 24
    28 29
    32 40
    1 7
    3 5
    2 6
    1 2
    4 4
    4 7
    3 4
    
    Expected output
    3
    2
    3
    2
    0
    3
    0