Under construction

Still being built. Things may change

Mosaic

Time limit1sMemory limit1024 MB

Summary
Given the top row and left column of an N by N grid filled by a NOR rule, answer Q queries counting black tiles in given subrectangles.
Level

Hard8 of 10

Topics
Dynamic programming, Prefix sum, Matrix
Solved
No attempts yet

Problem

Salma plans to colour a clay mosaic on a wall. The mosaic is an N×NN \times N grid, made of NN initially uncoloured 1×11 \times 1 square tiles. The rows of the mosaic are numbered from 00 to N−1N - 1 from top to bottom, and the columns are numbered from 00 to N−1N - 1 from left to right. The tile in row ii and column jj (0≤i<N0 \le i < N, 0≤j<N0 \le j < N) is denoted by (i,j)(i, j). Each tile must be coloured either white (denoted by 00) or black (denoted by 11).

To colour the mosaic, Salma first picks two arrays XX and YY of length NN, each consisting of values 00 and 11, such that X[0]=Y[0]X[0] = Y[0]. She colours the tiles of the topmost row (row 00) according to array XX, such that the colour of tile (0,j)(0, j) is X[j]X[j] (0≤j<N0 \le j < N). She also colours the tiles of the leftmost column (column 00) according to array YY, such that the colour of tile (i,0)(i, 0) is Y[i]Y[i] (0≤i<N0 \le i < N).

Then she repeats the following steps until all tiles are coloured:

  • She finds any uncoloured tile (i,j)(i, j) such that its up neighbor (tile (i−1,j)(i - 1, j)) and left neighbor (tile (i,j−1)(i, j - 1)) are both already coloured.
  • Then, she colours tile (i,j)(i, j) black if both of these neighbors are white; otherwise, she colours tile (i,j)(i, j) white.

It can be shown that the final colours of the tiles do not depend on the order in which Salma is colouring them.

Yasmin is very curious about the colours of the tiles in the mosaic. She asks Salma QQ questions, numbered from 00 to Q−1Q - 1. In question kk (0≤k<Q0 \le k < Q), Yasmin specifies a subrectangle of the mosaic by its:

  • Topmost row T[k]T[k] and bottommost row B[k]B[k] (0≤T[k]≤B[k]<N0 \le T[k] \le B[k] < N),
  • Leftmost column L[k]L[k] and rightmost column R[k]R[k] (0≤L[k]≤R[k]<N0 \le L[k] \le R[k] < N).

The answer to the question is the number of black tiles in this subrectangle. Specifically, Salma should find how many tiles (i,j)(i, j) exist, such that T[k]≤i≤B[k]T[k] \le i \le B[k], L[k]≤j≤R[k]L[k] \le j \le R[k], and the colour of tile (i,j)(i, j) is black.

Write a program that answers Yasmin's questions.

Constraints

  • 1≤N≤200 0001 \le N \le 200\,000
  • 1≤Q≤200 0001 \le Q \le 200\,000
  • X[i]∈{0,1}X[i] \in \{0, 1\} and Y[i]∈{0,1}Y[i] \in \{0, 1\} for each ii such that 0≤i<N0 \le i < N
  • X[0]=Y[0]X[0] = Y[0]
  • 0≤T[k]≤B[k]<N0 \le T[k] \le B[k] < N and 0≤L[k]≤R[k]<N0 \le L[k] \le R[k] < N for each kk such that 0≤k<Q0 \le k < Q

Examples1

  1. Example 1

    Input
    1 1
    1
    1
    0 0 0 0
    
    Expected output
    1