#P8875. Infinite Matrix Mask Sum

    ID: 22039 Type: Default 1000ms 256MiB

Infinite Matrix Mask Sum

Infinite Matrix Mask Sum

Given an n×m matrix \(A\) and an \(r\)×\(c\) binary (0-1) matrix \(B\), we construct an infinite matrix \(M\) by tiling \(B\) infinitely:

[ M = \begin{pmatrix} B & B & B & \cdots \ B & B & B & \cdots \ B & B & B & \cdots \ \vdots & \vdots & \vdots & \ddots \end{pmatrix} ]

Here a cell in \(B\) with value 1 is considered black (opaque) and with value 0 is transparent. We then answer \(q\) queries. In each query, you are given two pairs of coordinates \((x_1, y_1)\) and \((x_2, y_2)\), which denote the top‐left and bottom‐right corners of a submatrix of \(A\). Before answering the query, align the infinite mask \(M\) so that its top‐left cell coincides with \(A_{x_1,y_1}\). A cell \(A_{i,j}\) is visible if and only if the corresponding mask cell \(M_{i-x_1+1, j-y_1+1}\) is transparent (i.e. equal to 0).

Your task is to compute the sum

[ S = \left(\sum_{i=x_1}^{x_2}\sum_{j=y_1}^{y_2} a_{i,j} \cdot \Bigl[ M_{i-x_1+1, j-y_1+1} = 0 \Bigr]\right) \bmod 998,244,353, ]

where ([P]) is the Iverson bracket (equals 1 if (P) is true and 0 otherwise).

Input/Output details are provided below.

inputFormat

The first line contains two integers \(n\) and \(m\) — the dimensions of matrix \(A\). The following \(n\) lines each contain \(m\) integers representing the matrix \(A\).

The next line contains two integers \(r\) and \(c\) — the dimensions of matrix \(B\). The following \(r\) lines each contain \(c\) integers (each either 0 or 1) representing \(B\).

The next line contains an integer \(q\) representing the number of queries. Each of the following \(q\) lines contains four integers \(x_1, y_1, x_2, y_2\) describing a query. All indices are 1-indexed.

outputFormat

For each query, output one line containing the value of \(S\) modulo \(998\,244\,353\).

sample

4 7
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
2 3
0 1 0
1 0 1
1
2 3 4 7
47