Under construction

Still being built. Things may change

Grand Escape

Time limit3sMemory limit1024 MB

Summary
Each resident falls straight down, and the fall slows by one step each time it touches a wall. Find the time each resident needs to reach y=0.
Level

Medium6 of 10

Topics
Segment tree, Sorting, Implementation
Solved
No attempts yet

Problem

SRC (Science Research City) is a city on the first quadrant of the two-dimensional plane. The city has NN walls. Each wall is drawn as a line segment parallel to the xx-axis. Specifically, the ii-th wall (1≤i≤N1 \leq i \leq N) is the segment connecting (Lx1,i,Lyi)(Lx_{1,i}, Ly_i) and (Lx2,i,Lyi)(Lx_{2,i}, Ly_i). Heavy rain that has not stopped raises the risk of flooding, so SRC built shelters along the line y=0y=0.

The city has MM residents. The ii-th resident (1≤i≤M1 \leq i \leq M) is at (Pxi,Pyi)(Px_i, Py_i). When SRC floods, each resident moves in the −y-y direction toward y=0y=0. The initial speed is 11.

Every time a resident touches a wall, the speed drops. Touching an endpoint of a segment also counts as touching the wall. If the speed before touching a wall was 1n\frac{1}{n}, the speed after touching is 1n+1\frac{1}{n+1}. In other words, the time needed to move 1 unit increases by 1. All yy-coordinates are distinct. So every resident and every wall has a different yy-coordinate, and no resident starts on a wall. Multiple xx-coordinates may be equal.

Input

The first line contains the number of walls NN.

The next NN lines each contain Lx1,iLx_{1,i}, Lx2,iLx_{2,i}, and LyiLy_i, separated by spaces, describing the ii-th wall. The ii-th wall is the segment connecting (Lx1,i,Lyi)(Lx_{1,i}, Ly_i) and (Lx2,i,Lyi)(Lx_{2,i}, Ly_i).

The next line contains the number of residents MM.

The next MM lines each contain the position PxiPx_i and PyiPy_i of the ii-th resident, separated by a space.

Output

Print MM lines. On the ii-th line, print the time it takes for the ii-th resident to reach y=0y=0.

Constraints

  • 0≤N≤200,0000 \leq N \leq 200,000 (note that N=0N=0 is possible)
  • 1≤M≤200,0001 \leq M \leq 200,000
  • Lx1i<Lx2iLx1_i < Lx2_i
  • Every coordinate (x,y)(x, y) in the input satisfies 1≤x,y≤1091 \leq x, y \leq 10^9.
  • All yy-coordinates are distinct.
  • All numbers in the input are integers.

Hint

Some test cases may have answers larger than 2312^{31}, so use the long long type.

Examples1

  1. Example 1

    Input
    3
    1 5 1
    2 9 4
    6 10 6
    4
    3 2
    4 8
    8 5
    7 7
    
    Expected output
    3
    13
    9
    17