problems / 267

Missing Invoice Numbers (medium version)

medium binary-search intervals sorting prefix-sums 1000 ms · 256 MB

Missing Invoice Numbers (medium version)

Unlike the easy version (problem 265), the used numbers arrive as unsorted, possibly overlapping blocks, and every query asks for free numbers starting from a given point.

The billing service numbers its invoices with positive integers. Over the years some numbers were handed out and others were skipped, and finance now wants to reuse the skipped ones. Numbers were reserved in blocks: block i used every invoice number from l_i to r_i inclusive. The blocks come from several regional servers, so they are listed in no particular order and may overlap or repeat. Every positive integer not covered by any block is free, including all numbers larger than the end of the last block.

Answer q independent queries. A query (x, k) comes from a team that wants to issue invoices numbered x or higher: print the k-th smallest free invoice number that is at least x.

Input

The first line contains two integers n and q (1 ≤ n, q ≤ 2·10^5).

Each of the next n lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ 10^18), the first and last number of a used block.

Each of the next q lines contains two integers x and k (1 ≤ x ≤ 10^18, 1 ≤ k ≤ 10^18).

Output

For each query, print on its own line the k-th smallest positive integer that is at least x and is not covered by any block.

Notes

In the first example the blocks [5, 7], [2, 3] and [6, 9] cover 2, 3, 5, 6, 7, 8 and 9, so the free numbers are 1, 4, 10, 11, 12, ... For the query (1, 3) they are counted from 1: 1, 4, 10. For (5, 1) the numbers 5 to 9 are used, so the first free one is 10. For (4, 2) the free numbers from 4 on are 4, 10, ...

In the second example the answers exceed the range of a 32-bit integer: use 64-bit integers. They always fit in a signed 64-bit integer.

Example 1

Input

3 5
5 7
2 3
6 9
1 3
5 1
4 2
2 1
11 3

Output

10
10
10
4
13

Example 2

Input

2 3
3000000000 5000000000
1 2999999999
1 1
4000000000 10
1 1000000000000000000

Output

5000000001
5000000010
1000000005000000000

Hints · reveal one at a time if you're stuck

Hint 1

Overlapping blocks are awkward. Can you turn the input into sorted, disjoint blocks first?

Hint 2

The k-th free number that is at least x is the K-th free number overall, for K = k plus the number of free numbers below x. Both counts become easy with prefix sums over the blocks.

Hint 3

For each merged block, count the free numbers before it: this sequence is increasing, so a binary search tells you how many whole blocks lie below the answer.

report an issue Prefer your own editor? sooks prep 267 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.