Under construction

Still being built. Things may change

Cyber Donut Crime Investigation

Time limit5sMemory limit128 MB

Summary
For each query point find the database point minimizing the L1 distance, over many test cases with up to 100000 points and 50000 queries.
Level

Hard8 of 10

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

Problem

By the year 2042, the internet has advanced far enough to create virtual reality, and cyber crimes happen every day. To fight them, the winner of the 2041 SWERC contest built an agent that drops a single donut at the scene whenever a cyber crime occurs. Every donut carries a unique id, and the Madrid Police Department keeps a large database that stores each crime together with the unique id of the donut left at its scene.

Today is your day. Your mission is to develop a new agent that reads the records stored in the database and finds the donut most similar to the one at a new crime scene.

Virtual-criminology experts proposed the criterion for judging how similar two donuts are: their similarity is the absolute difference of their hole radii plus the absolute difference of their outer radii. That is, writing ll for the hole radius and ww for the outer radius, the similarity of two donuts (l1,w1)(l_1, w_1) and (l2,w2)(l_2, w_2) is ∣l1−l2∣+∣w1−w2∣|l_1 - l_2| + |w_1 - w_2|. A smaller value means the two donuts are more alike.

Input

The input consists of several test cases.

The first line of each test case contains the number of donuts stored in the database, nn (1≤n≤100 0001 \le n \le 100\,000).

Each of the next nn lines contains two integers, the hole radius ll and the outer radius ww of one database donut (1≤l,w≤1091 \le l, w \le 10^9).

The next line contains qq, the number of donuts to look up (1≤q≤50 0001 \le q \le 50\,000).

Each of the next qq lines contains two integers, the hole radius and outer radius of one donut to look up.

Consecutive test cases are separated by a blank line, and a single line containing −1-1 marks the end of the input.

Output

For each test case, print qq lines. The ii-th line must contain, as an integer, the similarity between the ii-th queried donut and the most similar (smallest-similarity) donut in the database.

The outputs of different test cases must be separated by a single blank line.

Examples1

  1. Example 1

    Input
    2
    2 3
    3 4
    2
    1 1
    3 4
    
    2
    1 1
    9 9
    4
    4 5
    6 5
    2 5
    3 4
    
    -1
    
    Expected output
    3
    0
    
    7
    7
    5
    5