atcoder#AGC015C. [AGC015C] Nuske vs Phantom Thnook

[AGC015C] Nuske vs Phantom Thnook

Score : 700700 points

Problem Statement

Nuske has a grid with NN rows and MM columns of squares. The rows are numbered 11 through NN from top to bottom, and the columns are numbered 11 through MM from left to right. Each square in the grid is painted in either blue or white. If Si,jS_{i,j} is 11, the square at the ii-th row and jj-th column is blue; if Si,jS_{i,j} is 00, the square is white. For every pair of two blue square aa and bb, there is at most one path that starts from aa, repeatedly proceeds to an adjacent (side by side) blue square and finally reaches bb, without traversing the same square more than once.

Phantom Thnook, Nuske's eternal rival, gives QQ queries to Nuske. The ii-th query consists of four integers xi,1x_{i,1}, yi,1y_{i,1}, xi,2x_{i,2} and yi,2y_{i,2} and asks him the following: when the rectangular region of the grid bounded by (and including) the xi,1x_{i,1}-th row, xi,2x_{i,2}-th row, yi,1y_{i,1}-th column and yi,2y_{i,2}-th column is cut out, how many connected components consisting of blue squares there are in the region?

Process all the queries.

Constraints

  • 1N,M20001 \leq N,M \leq 2000
  • 1Q2000001 \leq Q \leq 200000
  • Si,jS_{i,j} is either 00 or 11.
  • Si,jS_{i,j} satisfies the condition explained in the statement.
  • $1 \leq x_{i,1} \leq x_{i,2} \leq N(1 \leq i \leq Q)$
  • $1 \leq y_{i,1} \leq y_{i,2} \leq M(1 \leq i \leq Q)$

Input

The input is given from Standard Input in the following format:

NN MM QQ

S1,1S_{1,1}..S1,MS_{1,M}

:

SN,1S_{N,1}..SN,MS_{N,M}

x1,1x_{1,1} yi,1y_{i,1} xi,2x_{i,2} yi,2y_{i,2}

:

xQ,1x_{Q,1} yQ,1y_{Q,1} xQ,2x_{Q,2} yQ,2y_{Q,2}

Output

For each query, print the number of the connected components consisting of blue squares in the region.

3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4
3
2
2
2

In the first query, the whole grid is specified. There are three components consisting of blue squares, and thus 33 should be printed.

In the second query, the region within the red frame is specified. There are two components consisting of blue squares, and thus 22 should be printed. Note that squares that belong to the same component in the original grid may belong to different components.

5 5 6
11010
01110
10101
11101
01010
1 1 5 5
1 2 4 5
2 3 3 4
3 3 3 3
3 1 3 5
1 1 3 4
3
2
1
1
3
2