Under construction

Still being built. Things may change

Square Queries

Time limit4.5sMemory limit1024 MB

Summary
For each query, count the distinct values still present in the grid after blanking out the K by K square with the given top-left corner.
Level

Medium6 of 10

Topics
Hash map, Prefix sum, Array
Solved
No attempts yet

Problem

There is a grid with HH rows and WW columns. Each cell is denoted (i,j)(i, j), meaning the cell in row ii from the top and column jj from the left. Cell (i,j)(i, j) contains an integer AijA_{ij}, and each value satisfies 1≤Aij≤H×W1 \le A_{ij} \le H \times W.

An integer KK and QQ queries are given. Each query gives coordinates (y,x)(y, x), which denote a square with its top-left cell at (y,x)(y, x) and side length KK. For each query, erase the numbers in the cells inside the given square, then count the distinct numbers in the remaining cells of the grid.

All queries are independent. A previous query does not affect the next one.

Input

The first line contains HH, WW, KK, and QQ. (1≤H,W≤2 0001 \le H, W \le 2\,000, 1≤K≤min⁡(H,W)1 \le K \le \min(H, W), 1≤Q≤3×1051 \le Q \le 3 \times 10^5)

The next HH lines each contain WW integers AijA_{ij}, separated by spaces. (1≤Aij≤H×W1 \le A_{ij} \le H \times W)

The next QQ lines each contain two integers yy and xx, the top-left cell of the square. (1≤y≤H−K+11 \le y \le H - K + 1, 1≤x≤W−K+11 \le x \le W - K + 1)

Output

For each query, print on its own line the number of distinct values in the grid that remain after removing the given square.

Examples1

  1. Example 1

    Input
    3 4 2 4
    1 1 8 8
    7 2 2 3
    5 7 2 8
    1 1
    1 2
    2 2
    1 3
    
    Expected output
    5
    6
    5
    5