#P11053. Mosaic Coloring Queries

    ID: 13107 Type: Default 1000ms 256MiB

Mosaic Coloring Queries

Mosaic Coloring Queries

Salma wants to color a mosaic made up of N×NN \times N square tiles. There are a total of N2N^2 tiles, each with dimensions 1×11 \times 1, and initially none of them are colored. The rows are numbered from 00 to N1N-1 from top to bottom and the columns from 00 to N1N-1 from left to right. The tile at row ii and column jj is denoted by (i,j)(i,j). Each tile is painted either white (denoted by 00) or black (denoted by 11).

Initially, Salma selects two binary arrays XX and YY, each of length NN, with the condition that X[0]=Y[0]X[0]=Y[0]. She paints the top row (row 00) according to the array XX, setting the color of tile (0,j)(0,j) to X[j]X[j] for 0j<N0\le j<N. Similarly, she paints the leftmost column (column 00) according to the array YY, so that the color of tile (i,0)(i,0) is Y[i]Y[i] for 0i<N0\le i<N.

Then, she repeatedly colors an uncolored tile (i,j)(i,j) for which both the tile directly above (i1,j)(i-1,j) and the tile directly to the left (i,j1)(i,j-1) are already colored. The rule is as follows: [ \text{color}(i,j)=\begin{cases} 1, & \text{if } \text{color}(i-1,j)=0 \text{ and } \text{color}(i,j-1)=0,\ 0, & \text{otherwise.} \end{cases} ] It can be proven that the final coloring of the mosaic is independent of the order in which Salma colors the tiles.

Yasmin is curious about the final colors and asks QQ queries. In the kk-th query (0k<Q0\le k<Q), a subrectangle of the mosaic is specified by its top row T[k]T[k], bottom row B[k]B[k], left column L[k]L[k], and right column R[k]R[k], where 0T[k]B[k]<N0\le T[k]\le B[k]<N and 0L[k]R[k]<N0\le L[k]\le R[k]<N. The answer to the query is the number of black tiles (tiles with color 11) contained in the specified subrectangle.

Your task is to implement a function that efficiently answers these queries.

inputFormat

Input is given as follows:

  • The first line contains two integers NN and QQ, where NN is the size of the mosaic and QQ is the number of queries.
  • The second line contains NN integers (each 00 or 11) representing the array XX, which gives the colors for the top row.
  • The third line contains NN integers (each 00 or 11) representing the array YY, which gives the colors for the left column (X[0]=Y[0]X[0]=Y[0]).
  • Then QQ lines follow; each line contains four integers T[k]T[k], B[k]B[k], L[k]L[k], and R[k]R[k], defining a query.

outputFormat

For each query, output the number of black tiles in the specified subrectangle. Each answer should be printed on a separate line.

sample

3 3
0 1 0
0 0 1
0 1 0 1
1 2 1 2
0 2 0 2
1

1 3

</p>