Under construction

Still being built. Things may change

The Dog, the Traitor, and the Cables

Time limit2sMemory limit1024 MB

Summary
Find the maximum number of cable segments a dog can bite on a shortest path from (1,1) to each queried cell in a grid with cables.
Level

Hard9 of 10

Topics
Graph, BFS, Shortest path, Dynamic programming
Solved
No attempts yet

Problem

Now the traitor has a dog! The deck of a space ship is a grid of n×mn \times m cells. Rows are numbered from 1 to nn from top to bottom, and columns are numbered from 1 to mm from left to right. Some pairs of side-adjacent cells are separated by a cable segment.

At the start, the dog is in cell (1,1)(1, 1), the top left cell. It chooses one player, and let the chosen player be in cell (x,y)(x, y). The dog picks one of the shortest paths from its start to (x,y)(x, y) (in one move, the dog goes from a cell to a side-adjacent cell). Then the dog and the player take turns moving. The dog runs along the chosen path, and the player runs toward the dog from the other end of the same path. The dog moves first. The process continues until the dog and the player are in the same cell. Each time the dog crosses a cable segment, it bites through it.

Help the players find the maximum number of cable segments the dog can bite through.

Input

The first line contains three integers nn, mm, and kk, the size of the grid and the number of cable segments (1≤n,m≤200 0001 \le n, m \le 200\,000; n⋅m≤200 000n \cdot m \le 200\,000, 0≤k≤n⋅(m−1)+(n−1)⋅m0 \le k \le n \cdot (m - 1) + (n - 1) \cdot m).

Each of the next kk lines describes one cable segment with four integers x1x_1, y1y_1, x2x_2, and y2y_2 (1≤x1,x2≤n1 \le x_1, x_2 \le n; 1≤y1,y2≤m1 \le y_1, y_2 \le m). These numbers give the positions of two side-adjacent cells (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2), and the cable segment lies on the border between them. It is guaranteed that the two cells are side-adjacent.

The next line contains one integer qq, the number of player positions to answer for (1≤q≤201 \le q \le 20).

Each of the next qq lines contains two integers xx and yy, the position of the player (1≤x≤n1 \le x \le n, 1≤y≤m1 \le y \le m).

Output

Print qq lines. The ii-th line contains the maximum number of cable segments the dog can bite through in the ii-th case.

Hint

(a) In the first input, the cables are placed as follows.

(b) In the second input, the cables are placed as follows.

Examples2

  1. Example 1

    Input
    3 5 4
    1 1 2 1
    2 2 2 3
    2 4 3 4
    2 4 2 5
    5
    1 1
    2 3
    1 4
    3 3
    3 5
    
    Expected output
    0
    1
    0
    1
    2
    
  2. Example 2

    Input
    5 5 10
    3 1 2 1
    3 4 3 3
    1 3 1 2
    4 2 3 2
    5 1 4 1
    3 1 4 1
    3 4 2 4
    2 2 2 1
    2 2 1 2
    1 2 1 1
    5
    5 5
    2 3
    2 1
    4 1
    1 5
    
    Expected output
    3
    2
    0
    1
    2