Merging Branches
Time limit2sMemory limit1024 MB
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 branches, and the sales territory of the th branch is the range . It is known that for all , and for .
Two branches intersect if some point is included in both branches' sales territories. For example, and intersect, and and intersect. But and do not intersect.
Moloco can widen the sales territory of every branch by spending on advertisement. If Moloco spends won, then every branch may widen its sales territory by at most length units. The start and end of each widened territory must be integers.
Formally, let the new sales territory of the th branch be . The following conditions must hold.
- and
- and 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 .
You work for Moloco. You want to examine hypothetical scenarios where Moloco owns only the th through th branches. For each query, find the minimum cost to merge all of those branches into one.
Input
The first line contains two integers and (, ).
The next lines each contain two integers and (), the sales territory of the th branch. It is guaranteed that for all .
The next lines each contain two integers and (), describing the th query.
Output
Print lines. The th line contains the answer to the th query, which is the minimum cost to merge branches through .
Hint
If there is only one branch, no cost is needed.