Under construction

Still being built. Things may change

Fishing

Interview

Time limit2sMemory limit1024 MB

Summary
For each query (W, P), the task is to sum the fish caught by bait placed at (W, P) that is reeled diagonally up-left until it leaves the grid.
Level

Medium4 of 10

Topics
Prefix sum, Matrix
Solved
No attempts yet

Problem

Geondeok sits on Warudo, a small island attached to Ilgam Lake, reeling in time.

Ilgam Lake can be represented as an N×MN\times M grid. The grid is divided into 1×11\times 1 square cells, and each cell holds several fish. The cell that is the deepest and farthest from Geondeok is (N,M)(N,M).

Geondeok can swing a fishing rod to throw bait into any cell he wants. If he attaches a sinker of weight aa and swings the rod with strength bb, bait is placed in cell (a,b)(a,b).

The bait catches fish inside the lake grid. It catches all fish in every cell from the cell where the bait sits up to the surface. In other words, bait at (a,b)(a,b) catches all fish in (i,b)(i,b) for every integer ii with 1≤i≤a1\leq i\leq a.

When Geondeok reels the line in by one turn, the bait at (a,b)(a,b) moves to (a−1,b−1)(a-1,b-1) and catches the fish in its new cell. If the bait leaves the lake grid, it is retrieved immediately.

Each time Geondeok gives a sinker weight and a swing strength, find how many fish are caught by the time the bait is retrieved after the swing and reeling in. Help Geondeok catch as many fish as possible!

Input

The first line contains the integers N,MN,M for the lake size and QQ, the number of times Geondeok swings the rod, separated by spaces. (1≤N,M≤2 0001\leq N,M\leq 2\,000; 1≤Q≤300 0001\leq Q\leq 300\,000)

From the second line through the NN lines that follow, the number of fish AijA_{ij} in each cell is given. The jj-th number on the ii-th line means cell (i,j)(i,j) has AijA_{ij} fish. (0≤Aij≤5000\leq A_{ij}\leq 500)

From line N+2N+2 through the QQ lines that follow, the integer WiW_i, the weight of the sinker Geondeok attaches to the bait, and the integer PiP_i, the strength of the swing, are given separated by a space. (1≤Wi≤N1\leq W_i\leq N; 1≤Pi≤M1\leq P_i\leq M)

Output

For each of the QQ fishing attempts, print on its own line how many fish are caught before the bait is retrieved.

Hints

Since the input is large, fast I/O is recommended. Fast I/O for common languages is shown below.

  • C++: When using cin and cout, you must call cin.tie(nullptr); ios::sync_with_stdio(false); once before any I/O. For a newline, use '\n' instead of endl.
  • Java: You must use BufferedReader and BufferedWriter.
  • Python3, PyPy3: Use sys.stdin.readline().rstrip() instead of input().

Examples1

  1. Example 1

    Input
    4 5 3
    1 2 3 4 5
    5 2 1 4 6
    0 2 4 2 1
    0 0 2 1 7
    3 3
    1 4
    3 1
    
    Expected output
    13
    4
    6