Problem:


Score : 700 points

Problem Statement

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

Phantom Thnook, Nuske's eternal rival, gives Q queries to Nuske. The i-th query consists of four integers x_{i,1}, y_{i,1}, x_{i,2} and y_{i,2} and asks him the following: when the rectangular region of the grid bounded by (and including) the x_{i,1}-th row, x_{i,2}-th row, y_{i,1}-th column and y_{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

1 ≤ N,M ≤ 2000

1 ≤ Q ≤ 200000

S_{i,j} is either 0 or 1.

S_{i,j} satisfies the condition explained in the statement.

1 ≤ x_{i,1} ≤ x_{i,2} ≤ N(1 ≤ i ≤ Q)

1 ≤ y_{i,1} ≤ y_{i,2} ≤ M(1 ≤ i ≤ Q)

Input

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

N M Q
S_{1,1}..S_{1,M}
:
S_{N,1}..S_{N,M}
x_{1,1} y_{i,1} x_{i,2} y_{i,2}
:
x_{Q,1} y_{Q,1} x_{Q,2} y_{Q,2}

Output

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

Sample Input 1

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

Sample Output 1

3
2
2
2

In the first query, the whole grid is specified. There are three components consisting of blue squares, and thus 3 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 2 should be printed.
Note that squares that belong to the same component in the original grid may belong to different components.

Sample Input 2

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

Sample Output 2

3
2
1
1
3
2



Sample input:
3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4


Sample output:
3
2
2
2

Submission status: Memory Limit Exceeded

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


# MOD = 998244353


def cumsum(it):
    """
    累積和
    :param collections.Iterable it:
    """
    cs = 0
    ret = [0]
    for v in it:
        cs += v
        ret.append(cs)
    return ret


def cumsum_mat(mat):
    h = len(mat)
    w = len(mat[0])

    ret = [[0] * (w + 1) for _ in range(h + 1)]
    tmp = []
    for row in mat:
        tmp.append(cumsum(row))

    for c in range(w + 1):
        col = [row[c] for row in tmp]
        for r, a in enumerate(cumsum(col)):
            ret[r][c] = a
    return ret


N, M, Q = list(map(int, sys.stdin.buffer.readline().split()))
S = [list(map(int, sys.stdin.buffer.readline().decode().rstrip())) for _ in range(N)]
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]

# つながってる場所の数
edges_v = [[0] * M for _ in range(N)]
for h, w in itertools.product(range(1, N), range(M)):
    edges_v[h][w] = S[h][w] & S[h - 1][w]
edges_h = [[0] * M for _ in range(N)]
for h, w in itertools.product(range(N), range(1, M)):
    edges_h[h][w] = S[h][w] & S[h][w - 1]

counts_cum = cumsum_mat(S)
edges_v_cum = cumsum_mat(edges_v)
edges_h_cum = cumsum_mat(edges_h)


def solve(x1, y1, x2, y2):
    v = counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]
    ev = edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]
    eh = edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]
    # 森なので 頂点数 - 辺数
    return v - ev - eh


ans = []
for x1, y1, x2, y2 in XY:
    a = solve(x1, y1, x2, y2)
    ans.append(a)
print(*ans, sep='\n')

Submission status: Memory Limit Exceeded

Solution code:
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


N, M, Q = list(map(int, sys.stdin.buffer.readline().split()))
S = [list(sys.stdin.buffer.readline().decode().rstrip()) for _ in range(N)]
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]

S = np.array(S, dtype=int)
counts_cum = np.zeros((N + 1, M + 1), dtype=int)
counts_cum[1:, 1:] = S.cumsum(axis=0).cumsum(axis=1)

# つながってる場所の数
edges_v = np.zeros((N, M), dtype=int)
edges_v[1:] += S[1:] & S[:-1]
edges_h = np.zeros((N, M), dtype=int)
edges_h[:, 1:] += S[:, 1:] & S[:, :-1]
del S
edges_v_cum = np.zeros((N + 1, M + 1), dtype=int)
edges_v_cum[1:, 1:] = edges_v.cumsum(axis=0).cumsum(axis=1)
del edges_v
edges_h_cum = np.zeros((N + 1, M + 1), dtype=int)
edges_h_cum[1:, 1:] = edges_h.cumsum(axis=0).cumsum(axis=1)
del edges_h

counts_cum = counts_cum.tolist()
edges_v_cum = edges_v_cum.tolist()
edges_h_cum = edges_h_cum.tolist()


def solve(x1, y1, x2, y2):
    v = counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]
    ev = edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]
    eh = edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]
    # 森なので 頂点数 - 辺数
    return v - ev - eh


ans = []
for x1, y1, x2, y2 in XY:
    a = solve(x1, y1, x2, y2)
    ans.append(a)
print(*ans, sep='\n')

Submission status: Memory Limit Exceeded

Solution code:
import os
import sys

import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


N, M, Q = list(map(int, sys.stdin.buffer.readline().split()))
S = [list(sys.stdin.buffer.readline().decode().rstrip()) for _ in range(N)]
XY = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]

S = np.array(S, dtype=int)

counts_cum = np.zeros((N + 1, M + 1), dtype=int)
counts_cum[1:, 1:] = S.cumsum(axis=0).cumsum(axis=1)

# つながってる場所の数
edges_v = np.zeros((N, M), dtype=int)
edges_v[1:] += S[1:] & S[:-1]
edges_h = np.zeros((N, M), dtype=int)
edges_h[:, 1:] += S[:, 1:] & S[:, :-1]

edges_v_cum = np.zeros((N + 1, M + 1), dtype=int)
edges_v_cum[1:, 1:] = edges_v.cumsum(axis=0).cumsum(axis=1)
edges_h_cum = np.zeros((N + 1, M + 1), dtype=int)
edges_h_cum[1:, 1:] = edges_h.cumsum(axis=0).cumsum(axis=1)


def solve(x1, y1, x2, y2):
    # print(counts_cum[x2, y2] , counts_cum[x1, y2] , counts_cum[x2, y1] , counts_cum[x1, y1])
    v = counts_cum[x2, y2] - counts_cum[x1 - 1, y2] - counts_cum[x2, y1 - 1] + counts_cum[x1 - 1, y1 - 1]
    ev = edges_v_cum[x2, y2] - edges_v_cum[x1, y2] - edges_v_cum[x2, y1 - 1] + edges_v_cum[x1, y1 - 1]
    eh = edges_h_cum[x2, y2] - edges_h_cum[x1 - 1, y2] - edges_h_cum[x2, y1] + edges_h_cum[x1 - 1, y1]
    # 森なので 頂点数 - 辺数
    return v - ev - eh


ans = []
for x1, y1, x2, y2 in XY:
    a = solve(x1, y1, x2, y2)
    ans.append(a)
print(*ans, sep='\n')

Submission status: Memory Limit Exceeded

Solution code:
class Ruiseki2D():
    def __init__(self, matrix):
        self.h = len(matrix)
        self.w = len(matrix[0])
        self.ruiseki = [[0] * (self.w + 1) for _ in range(self.h + 1)]

        for i in range(self.h):
            for j in range(self.w):
                self.ruiseki[i + 1][j + 1] = self.ruiseki[i + 1][j] + matrix[i][j]
        for i in range(self.h):
            for j in range(self.w):
                self.ruiseki[i + 1][j + 1] += self.ruiseki[i][j + 1]

    def get_sum(self, hl, hr, wl, wr):
        """[hl, hr), [wl, wr)"""
        return self.ruiseki[hr][wr] + self.ruiseki[hl][wl] - self.ruiseki[hr][wl] - self.ruiseki[hl][wr]


n, m, q = map(int, input().split())
s = [list(input()) for i in range(n)]
query = [list(map(int, input().split())) for i in range(q)]
for i in range(n):
    for j in range(m):
        s[i][j] = int(s[i][j])

matrix = [[1 if s[i][j] == 1 else 0 for j in range(m)] for i in range(n)]
ruiseki = Ruiseki2D(matrix)

for i in range(n):
    for j in range(m):
        matrix[i][j] = 0
for i in range(n):
    for j in range(m - 1):
        if s[i][j] == 1 and s[i][j + 1] == 1:
            matrix[i][j] = 1
ruiseki_w = Ruiseki2D(matrix)

for i in range(n):
    for j in range(m):
        matrix[i][j] = 0
for i in range(n - 1):
    for j in range(m):
        if s[i][j] == 1 and s[i + 1][j] == 1:
            matrix[i][j] = 1
ruiseki_h = Ruiseki2D(matrix)

for hl, wl, hr, wr in query:
    hl -= 1
    wl -= 1
    print(ruiseki.get_sum(hl, hr, wl, wr) - ruiseki_w.get_sum(hl, hr, wl, wr - 1) - ruiseki_h.get_sum(hl, hr - 1, wl, wr))

Submission status: Memory Limit Exceeded

Solution code:
class Ruiseki2D():
    def __init__(self, matrix):
        self.h = len(matrix)
        self.w = len(matrix[0])
        self.ruiseki = [[0] * (self.w + 1) for _ in range(self.h + 1)]

        for i in range(self.h):
            for j in range(self.w):
                self.ruiseki[i + 1][j + 1] = self.ruiseki[i + 1][j] + matrix[i][j]
        for i in range(self.h):
            for j in range(self.w):
                self.ruiseki[i + 1][j + 1] += self.ruiseki[i][j + 1]

    def get_sum(self, hl, hr, wl, wr):
        """[hl, hr), [wl, wr)"""
        return self.ruiseki[hr][wr] + self.ruiseki[hl][wl] - self.ruiseki[hr][wl] - self.ruiseki[hl][wr]


n, m, q = map(int, input().split())
s = [list(input()) for i in range(n)]
for i in range(n):
    for j in range(m):
        s[i][j] = int(s[i][j])

matrix = [[1 if s[i][j] == 1 else 0 for j in range(m)] for i in range(n)]
ruiseki = Ruiseki2D(matrix)

for i in range(n):
    for j in range(m):
        matrix[i][j] = 0
for i in range(n):
    for j in range(m - 1):
        if s[i][j] == 1 and s[i][j + 1] == 1:
            matrix[i][j] = 1
ruiseki_w = Ruiseki2D(matrix)

for i in range(n):
    for j in range(m):
        matrix[i][j] = 0
for i in range(n - 1):
    for j in range(m):
        if s[i][j] == 1 and s[i + 1][j] == 1:
            matrix[i][j] = 1
ruiseki_h = Ruiseki2D(matrix)

for i in range(q):
    hl, wl, hr, wr = list(map(int, input().split()))
    hl -= 1
    wl -= 1
    print(ruiseki.get_sum(hl, hr, wl, wr) - ruiseki_w.get_sum(hl, hr, wl, wr - 1) - ruiseki_h.get_sum(hl, hr - 1, wl, wr))

Submission status: Memory Limit Exceeded

Solution code:
class Ruiseki2D():
    def __init__(self, matrix):
        self.h = len(matrix)
        self.w = len(matrix[0])
        self.ruiseki = [[0] * (self.w + 1) for _ in range(self.h + 1)]

        for i in range(self.h):
            for j in range(self.w):
                self.ruiseki[i + 1][j + 1] = self.ruiseki[i + 1][j] + matrix[i][j]
        for i in range(self.h):
            for j in range(self.w):
                self.ruiseki[i + 1][j + 1] += self.ruiseki[i][j + 1]

    def get_sum(self, hl, hr, wl, wr):
        """[hl, hr), [wl, wr)"""
        return self.ruiseki[hr][wr] + self.ruiseki[hl][wl] - self.ruiseki[hr][wl] - self.ruiseki[hl][wr]

n, m, q = map(int, input().split())
s = [input() for i in range(n)]
query = [list(map(int, input().split())) for i in range(q)]

matrix = [[1 if s[i][j] == "1" else 0 for j in range(m)] for i in range(n)]
ruiseki = Ruiseki2D(matrix)

matrix_w = [[0]*m for i in range(n)]
for i in range(n):
    for j in range(m - 1):
        if s[i][j] == "1" and s[i][j + 1] == "1" :
            matrix_w[i][j] = 1
ruiseki_w = Ruiseki2D(matrix_w)

matrix_h = [[0]*m for i in range(n)]
for i in range(n - 1):
    for j in range(m):
        if s[i][j] == "1" and s[i + 1][j] == "1" :
            matrix_h[i][j] = 1
ruiseki_h = Ruiseki2D(matrix_h)

for i in range(q):
    hl, wl, hr, wr = query[i]
    hl -= 1
    wl -= 1
    print(ruiseki.get_sum(hl, hr, wl, wr) - ruiseki_w.get_sum(hl, hr, wl, wr - 1) - ruiseki_h.get_sum(hl, hr - 1, wl, wr))

Submission status: Memory Limit Exceeded

Solution code:
import sys
from itertools import accumulate
readline = sys.stdin.readline

N, M, Q = map(int, readline().split())
direc = [(-1, 0), (1, 0), (0, -1), (0, 1)]
G = [[0]*(M+2)] + [[0] + list(map(int, readline().strip())) + [0] for _ in range(N)] + [[0]*(M+2)]
V = [[0]*(M+2) for _ in range(N+2)]
U = [[0]*(M+2) for _ in range(N+2)]
L = [[0]*(M+2) for _ in range(N+2)]
for i in range(1, N+1):
    for j in range(1, M+1):
        if G[i][j]:
            V[i][j] = 1
            if G[i-1][j]:
                U[i][j] += 1
            if G[i][j-1]:
                L[i][j] += 1
V = [list(accumulate(k)) for k in V]
V = list(map(list, zip(*V)))
V = [list(accumulate(k)) for k in V]
V = list(map(list, zip(*V)))
U = [list(accumulate(k)) for k in U]
U = list(map(list, zip(*U)))
U = [list(accumulate(k)) for k in U]
U = list(map(list, zip(*U)))
L = [list(accumulate(k)) for k in L]
L = list(map(list, zip(*L)))
L = [list(accumulate(k)) for k in L]
L = list(map(list, zip(*L)))
Ans = [None]*Q 
for qu in range(Q):
    x1, y1, x2, y2 = map(int, readline().split())
    u = U[x1][y1-1] + U[x2][y2] - U[x1][y2] - U[x2][y1-1]
    l = L[x1-1][y1] + L[x2][y2] - L[x1-1][y2] - L[x2][y1]
    v = V[x1-1][y1-1] + V[x2][y2] - V[x1-1][y2] - V[x2][y1-1]
    Ans[qu] = v - u - l
print('\n'.join(map(str, Ans)))

Submission status: Memory Limit Exceeded

Solution code:
def main():
    import sys
    import numpy as np
    input = sys.stdin.readline
    H, W, Q = map(int, input().split())
    S = [list(map(lambda x: x=="1", input())) for _ in range(H)] + [[False]*(W+1)]
    S = np.array(S, dtype=np.int16)
    M = np.zeros((H + 1, W + 1), dtype=np.int32)

    UD = S[1:, :] * S[:-1, :]
    M[1:, :] += UD
    M[:-1, :] += UD

    LR = S[:, 1:] * S[:, :-1]
    M[:, 1:] += LR
    M[:, :-1] += LR

    M = S * 2 - M
    M = M.cumsum(axis=0).cumsum(axis=1)
    UD = UD.cumsum(axis=1)
    LR = LR.cumsum(axis=0)
    M[:, -1] = 0
    M[-1, :] = 0

    del S

    UD = np.pad(UD, ((0, 1), (0, 1)), mode="constant")
    LR = np.pad(LR, ((0, 1), (0, 1)), mode="constant")
    x1, y1, x2, y2 = np.array(list(map(int, sys.stdin.read().split())), dtype=np.int16).reshape(-1, 4).T
    Ans = M[x2-1, y2-1] + M[x1-2, y1-2] - M[x2-1, y1-2] - M[x1-2, y2-1]
    Ans += LR[x2-1, y1-2] - LR[x1-2, y1-2]
    Ans += LR[x2-1, y2-1] - LR[x1-2, y2-1]
    Ans += UD[x1-2, y2-1] - UD[x1-2, y1-2]
    Ans += UD[x2-1, y2-1] - UD[x2-1, y1-2]
    Ans //= 2
    print("\n".join(str(int(a)) for a in Ans))

main()

Submission status: Memory Limit Exceeded

Solution code:
def main():
    import sys
    import numpy as np
    input = sys.stdin.readline
    H, W, Q = map(int, input().split())
    S = [list(map(lambda x: x=="1", input())) for _ in range(H)] + [[False]*(W+1)]
    S = np.array(S, dtype=np.int32)
    M = np.zeros((H + 1, W + 1), dtype=np.int32)

    UD = S[1:, :] * S[:-1, :]
    M[1:, :] += UD
    M[:-1, :] += UD

    LR = S[:, 1:] * S[:, :-1]
    M[:, 1:] += LR
    M[:, :-1] += LR

    M = S * 2 - M
    M = M.cumsum(axis=0).cumsum(axis=1)
    UD = UD.cumsum(axis=1)
    LR = LR.cumsum(axis=0)
    M[:, -1] = 0
    M[-1, :] = 0

    UD = np.pad(UD, ((0, 1), (0, 1)), mode="constant")
    LR = np.pad(LR, ((0, 1), (0, 1)), mode="constant")
    x1, y1, x2, y2 = np.array(list(map(int, sys.stdin.read().split())), dtype=np.int16).reshape(-1, 4).T
    Ans = M[x2-1, y2-1] + M[x1-2, y1-2] - M[x2-1, y1-2] - M[x1-2, y2-1]
    Ans += LR[x2-1, y1-2] - LR[x1-2, y1-2]
    Ans += LR[x2-1, y2-1] - LR[x1-2, y2-1]
    Ans += UD[x1-2, y2-1] - UD[x1-2, y1-2]
    Ans += UD[x2-1, y2-1] - UD[x2-1, y1-2]
    Ans //= 2
    print("\n".join(str(int(a)) for a in Ans))

main()

Submission status: Memory Limit Exceeded

Solution code:
def main():
    import sys
    import numpy as np
    input = sys.stdin.readline
    H, W, Q = map(int, input().split())
    S = [list(map(lambda x: x=="1", input())) for _ in range(H)] + [[False]*(W+1)]
    S = np.array(S, dtype=np.int8)
    M = np.zeros((H + 1, W + 1), dtype=np.int32)
    L = np.zeros((H + 1, W + 1), dtype=np.int16)
    R = np.zeros((H + 1, W + 1), dtype=np.int16)
    U = np.zeros((H + 1, W + 1), dtype=np.int16)
    D = np.zeros((H + 1, W + 1), dtype=np.int16)

    ud = S[1:, :] * S[:-1, :]
    M[1:, :] += ud
    U[1:, :] -= ud
    M[:-1, :] += ud
    D[:-1, :] -= ud
    del ud
    lr = S[:, 1:] * S[:, :-1]
    M[:, 1:] += lr
    L[:, 1:] -= lr
    M[:, :-1] += lr
    R[:, :-1] -= lr
    del lr
    M = S * 2 - M
    del S

    M = M.cumsum(axis=0).cumsum(axis=1)
    L = L.cumsum(axis=0)
    R = R.cumsum(axis=0)
    U = U.cumsum(axis=1)
    D = D.cumsum(axis=1)
    M[:, -1] = 0
    M[-1, :] = 0
    L[-1, :] = 0
    R[-1, :] = 0
    U[:, -1] = 0
    D[:, -1] = 0

    x1, y1, x2, y2 = np.array(list(zip(*[iter(map(int, sys.stdin.read().split()))]*4)), dtype=np.int16).T
    Ans = M[x2-1, y2-1] + M[x1-2, y1-2] - M[x2-1, y1-2] - M[x1-2, y2-1]
    Ans -= L[x2-1, y1-1] - L[x1-2, y1-1]
    Ans -= R[x2-1, y2-1] - R[x1-2, y2-1]
    Ans -= U[x1-1, y2-1] - U[x1-1, y1-2]
    Ans -= D[x2-1, y2-1] - D[x2-1, y1-2]
    Ans //= 2
    print("\n".join(str(int(a)) for a in Ans))

main()

Submission status: Memory Limit Exceeded

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    H, W, Q = map(int, input().split())
    S = [list(map(lambda x: x=="1", input())) for _ in range(H)]
    XYXY = zip(*[iter(map(int, sys.stdin.read().split()))]*4)

    M, L, R, U, D = [], [], [], [], []
    for x, s in enumerate(S):
        M_, L_, R_, U_, D_ = [], [], [], [], []
        for y, c in enumerate(s):
            m = l = r = u = d = 0
            if c:
                if x >= 1:
                    m += S[x-1][y]
                    u -= S[x-1][y]
                if x < H-1:
                    m += S[x+1][y]
                    d -= S[x+1][y]
                if y >= 1:
                    m += s[y-1]
                    l -= s[y-1]
                if y < W-1:
                    m += s[y+1]
                    r -= s[y+1]
                m = 2 - m
                # l = m - l
                # r = m - r
                # u = m - u
                # d = m - d
            M_.append(m)
            L_.append(l)
            R_.append(r)
            U_.append(u)
            D_.append(d)
        M.append(M_)
        L.append(L_)
        R.append(R_)
        U.append(U_)
        D.append(D_)
    M.append([0]*(W+1))
    L.append([0]*(W+1))
    R.append([0]*(W+1))
    U.append([0]*(W+1))
    D.append([0]*(W+1))

    #for m in M:
    #    print(m)
    for x in range(H):
        m = 0
        for y in range(W):
            m += M[x][y]
            M[x][y] = m + M[x-1][y]
            L[x][y] += L[x-1][y]
            R[x][y] += R[x-1][y]
            U[x][y] += U[x][y-1]
            D[x][y] += D[x][y-1]

    Ans = []
    for x1, y1, x2, y2 in XYXY:
        ans = 0
        ans += M[x2-1][y2-1] + M[x1-2][y1-2] - M[x2-1][y1-2] - M[x1-2][y2-1]
        ans -= L[x2-1][y1-1] - L[x1-2][y1-1]
        ans -= R[x2-1][y2-1] - R[x1-2][y2-1]
        ans -= U[x1-1][y2-1] - U[x1-1][y1-2]
        ans -= D[x2-1][y2-1] - D[x2-1][y1-2]
        assert ans % 2 == 0, ans
        Ans.append(ans//2)
    print("\n".join(map(str, Ans)))

main()

Submission status: Memory Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

from itertools import accumulate
from operator import add

def solve():
    def getAccAss(Ass):
        accAss = [[0] * (len(Ass[0])+1)] + [accumulate([0] + As) for As in Ass]
        for x in range(1, len(accAss)):
            accAss[x] = list(map(add, accAss[x], accAss[x-1]))
        return accAss
    def getRangeSum2D(accAss, xFr, xTo, yFr, yTo):
        return accAss[xTo+1][yTo+1] - accAss[xTo+1][yFr] - accAss[xFr][yTo+1] + accAss[xFr][yFr]

    N, M, Q = map(int, input().split())
    Ass = [list(map(int, list(input().rstrip()))) for _ in range(N)]

    numXss = [[0]*(M) for _ in range(N-1)]
    for x, (A1s, A2s) in enumerate(zip(Ass, Ass[1:])):
        for y, (A1, A2) in enumerate(zip(A1s, A2s)):
            if A1*A2:
                numXss[x][y] = 1
    numYss = [[0]*(M-1) for _ in range(N)]
    for x, As in enumerate(Ass):
        for y in range(M-1):
            if As[y]*As[y+1]:
                numYss[x][y] = 1

    Ass = getAccAss(Ass)
    numXss = getAccAss(numXss) if numXss else [[0]*(M+1)]
    numYss = getAccAss(numYss) if numYss else [[0] for _ in range(N+1)]

    anss = []
    for _ in range(Q):
        x1, y1, x2, y2 = map(int, input().split())
        x1, y1, x2, y2 = x1-1, y1-1, x2-1, y2-1
        ans = getRangeSum2D(Ass, x1, x2, y1, y2)
        ans -= getRangeSum2D(numXss, x1, x2-1, y1, y2)
        ans -= getRangeSum2D(numYss, x1, x2, y1, y2-1)
        anss.append(ans)

    print('\n'.join(map(str, anss)))

solve()

Submission status: Memory Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

from itertools import accumulate
from operator import add

def solve():
    def getAccAss(Ass):
        accAss = [[0] * (len(Ass[0])+1)] + [accumulate([0] + As) for As in Ass]
        for x in range(1, len(accAss)):
            accAss[x] = list(map(add, accAss[x], accAss[x-1]))
        return accAss
    def getRangeSum2D(accAss, xFr, xTo, yFr, yTo):
        return accAss[xTo+1][yTo+1] - accAss[xTo+1][yFr] - accAss[xFr][yTo+1] + accAss[xFr][yFr]

    N, M, Q = map(int, input().split())
    Ass = [list(map(int, list(input().rstrip()))) for _ in range(N)]

    numXss = [[0]*(M) for _ in range(N-1)]
    for x, (A1s, A2s) in enumerate(zip(Ass, Ass[1:])):
        for y, (A1, A2) in enumerate(zip(A1s, A2s)):
            if A1*A2:
                numXss[x][y] = 1
    numYss = [[0]*(M-1) for _ in range(N)]
    for x, As in enumerate(Ass):
        for y in range(M-1):
            if As[y]*As[y+1]:
                numYss[x][y] = 1

    Ass = getAccAss(Ass)
    NumXss = getAccAss(numXss) if numXss else [[0]*(M+1)]
    NumYss = getAccAss(numYss) if numYss else [[0] for _ in range(N+1)]

    anss = []
    for _ in range(Q):
        x1, y1, x2, y2 = map(int, input().split())
        x1, y1, x2, y2 = x1-1, y1-1, x2-1, y2-1
        ans = getRangeSum2D(Ass, x1, x2, y1, y2)
        ans -= getRangeSum2D(NumXss, x1, x2-1, y1, y2)
        ans -= getRangeSum2D(NumYss, x1, x2, y1, y2-1)
        anss.append(ans)

    print('\n'.join(map(str, anss)))

solve()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N, M, Q = map(int, input().split())
S = [input().rstrip() for _ in range(N)]
cum = [[0] * (M + 1) for _ in range(N + 1)]
for i in range(N):
    for j in range(M):
        cum[i+1][j+1] = int(S[i][j]) + cum[i][j+1] + cum[i+1][j] - cum[i][j]
cumh = [[0] * M for _ in range(N + 1)]
for i in range(N):
    for j in range(M-1):
        cumh[i+1][j+1] = cumh[i][j+1] + cumh[i+1][j] - cumh[i][j]
        if S[i][j] == S[i][j+1] == '1':
            cumh[i+1][j+1] += 1
cumv = [[0] * (M + 1) for _ in range(N)]
for i in range(N-1):
    for j in range(M):
        cumv[i+1][j+1] = cumv[i][j+1] + cumv[i+1][j] - cumv[i][j]
        if S[i][j] == S[i+1][j] == '1':
            cumv[i+1][j+1] += 1
for _ in range(Q):
    x1, y1, x2, y2 = map(lambda x: int(x) - 1, input().split())
    a = cum[x2+1][y2+1] - cum[x2+1][y1] - cum[x1][y2+1] + cum[x1][y1]
    b = cumh[x2+1][y2] - cumh[x1][y2] - cumh[x2+1][y1] + cumh[x1][y1]
    c = cumv[x2][y2+1] - cumv[x2][y1] - cumv[x1][y2+1] + cumv[x1][y1]
    print(a - b - c)

Submission status: Accepted

Solution code:
import numpy as np

N, M, Q = map(int, input().split())
field = np.array([list(map(int, input())) for _ in range(N)], dtype = np.int64)
xyxys = [tuple(map(int, input().split())) for _ in range(Q)]

above = np.zeros((N+1, M+1), dtype = np.int64)
np.logical_and(field[1:], field[:-1], out = above[2:, 1:])
np.cumsum(above, axis = 0, out = above)
np.cumsum(above, axis = 1, out = above)

right = np.zeros((N+1, M+1), dtype = np.int64)
np.logical_and(field[:, 1:], field[:, :-1], out = right[1:, 2:])
np.cumsum(right, axis = 0, out = right)
np.cumsum(right, axis = 1, out = right)

field_csum = np.zeros((N+1, M+1), dtype = np.int64)
field_csum[1:, 1:] = np.cumsum(np.cumsum(field, axis = 1), axis = 0)

for x1, y1, x2, y2 in xyxys:
    x1 -= 1
    y1 -= 1
    ans = field_csum[x2][y2] - field_csum[x1][y2] - field_csum[x2][y1] + field_csum[x1][y1]
    
    y1 += 1
    ans -= right[x2][y2] - right[x1][y2] - right[x2][y1] + right[x1][y1]
    y1 -= 1
    
    x1 += 1
    ans -= above[x2][y2] - above[x1][y2] - above[x2][y1] + above[x1][y1]
    x1 -= 1
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n,m,q = list(map(int, input().split()))
s = [None]*n
for i in range(n):
    s[i] = list(map(int, input()))
e1 = [[0]*(m) for _ in range(n-1)]
e2 = [[0]*(m-1) for _ in range(n)]
for i in range(n):
    for j in range(m):
        if i<n-1 and s[i][j]==s[i+1][j]==1:
            e1[i][j] = 1
        if j<m-1 and s[i][j]==s[i][j+1]==1:
            e2[i][j] = 1
def cumsum2(v):
    # v: h*wの2次元リスト
    h,w = len(v), len(v[0])
    v.insert(0, [0]*w)
    for l in v:
        l.insert(0, 0)
    for i in range(1,h+1):
        for j in range(1,w+1):
            v[i][j] = v[i-1][j] + v[i][j-1] - v[i-1][j-1] + v[i][j]
    return v
s = cumsum2(s)
if e1:
    e1 = cumsum2(e1)
if e2:
    e2 = cumsum2(e2)
ans = [None]*q
for i in range(q):
    x1,y1,x2,y2 = map(lambda x: int(x)-1, input().split())
    val = s[x2+1][y2+1] - s[x1][y2+1] - s[x2+1][y1] + s[x1][y1]
    if e1:
        val2 = e1[x2][y2+1] - e1[x2][y1] - e1[x1][y2+1] + e1[x1][y1]
    else:
        val2 = 0
    if e2:
        val3 = e2[x2+1][y2] - e2[x2+1][y1] - e2[x1][y2] + e2[x1][y1]
    else:
        val3 = 0
    ans[i] = val - (val2+val3)
write("\n".join(map(str, ans)))

Submission status: Accepted

Solution code:
import os
import sys

import numpy as np


def solve(n, m, q, sss, xy):
    dp1 = np.zeros((n + 1, m + 1), dtype=np.int64)
    dpv = np.zeros((n + 1, m + 1), dtype=np.int64)
    dph = np.zeros((n + 1, m + 1), dtype=np.int64)
    for i in range(n):
        for j in range(m):
            if sss[i, j] == 1:
                dp1[i + 1, j + 1] = 1

                if i > 0 and sss[i - 1, j] == 1:
                    dpv[i + 1, j + 1] = 1
                if j > 0 and sss[i, j - 1] == 1:
                    dph[i + 1, j + 1] = 1

    for i in range(1, n + 1):
        dp1[i] = dp1[i].cumsum()
        dpv[i] = dpv[i].cumsum()
        dph[i] = dph[i].cumsum()

    for j in range(1, m + 1):
        dp1[:, j] = dp1[:, j].cumsum()
        dpv[:, j] = dpv[:, j].cumsum()
        dph[:, j] = dph[:, j].cumsum()

    buf = np.zeros(q, dtype=np.int64)
    for i in range(q):
        x1 = xy[i * 4 + 0]
        y1 = xy[i * 4 + 1]
        x2 = xy[i * 4 + 2]
        y2 = xy[i * 4 + 3]
        cnt1 = dp1[x2, y2] - dp1[x1 - 1, y2] - dp1[x2, y1 - 1] + dp1[x1 - 1, y1 - 1]
        ver1 = dpv[x2, y2] - dpv[x1, y2] - dpv[x2, y1 - 1] + dpv[x1, y1 - 1]
        hor1 = dph[x2, y2] - dph[x1 - 1, y2] - dph[x2, y1] + dph[x1 - 1, y1]
        buf[i] = cnt1 - ver1 - hor1

    return buf


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8,i8,i8,i1[:,:],i8[:])')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8,i8,i8,i1[:,:],i8[:])', cache=True)(solve)

n, m, q = map(int, input().split())
sss = np.array([list(map(int, input())) for _ in range(n)], dtype=np.int8)
xy = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
ans = solve(n, m, q, sss, xy)
print('\n'.join(map(str, ans)))

Submission status: Accepted

Solution code:
import os
import sys

import numpy as np


def solve(n, m, q, sss, xy):
    dp1 = np.zeros((n + 1, m + 1), dtype=np.int64)
    dpv = np.zeros((n + 1, m + 1), dtype=np.int64)
    dph = np.zeros((n + 1, m + 1), dtype=np.int64)
    for i in range(n):
        for j in range(m):
            if sss[i, j] == 1:
                dp1[i + 1, j + 1] = 1

                if i > 0 and sss[i - 1, j] == 1:
                    dpv[i + 1, j + 1] = 1
                if j > 0 and sss[i, j - 1] == 1:
                    dph[i + 1, j + 1] = 1

    for i in range(1, n + 1):
        for j in range(1, m + 1):
            dp1[i, j] += dp1[i, j - 1]
            dpv[i, j] += dpv[i, j - 1]
            dph[i, j] += dph[i, j - 1]

    for j in range(1, m + 1):
        for i in range(1, n + 1):
            dp1[i, j] += dp1[i - 1, j]
            dpv[i, j] += dpv[i - 1, j]
            dph[i, j] += dph[i - 1, j]

    buf = np.zeros(q, dtype=np.int64)
    for i in range(q):
        x1 = xy[i * 4 + 0]
        y1 = xy[i * 4 + 1]
        x2 = xy[i * 4 + 2]
        y2 = xy[i * 4 + 3]
        cnt1 = dp1[x2][y2] - dp1[x1 - 1][y2] - dp1[x2][y1 - 1] + dp1[x1 - 1][y1 - 1]
        ver1 = dpv[x2][y2] - dpv[x1][y2] - dpv[x2][y1 - 1] + dpv[x1][y1 - 1]
        hor1 = dph[x2][y2] - dph[x1 - 1][y2] - dph[x2][y1] + dph[x1 - 1][y1]
        buf[i] = cnt1 - ver1 - hor1

    return buf


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8,i8,i8,i1[:,:],i8[:])')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8,i8,i8,i1[:,:],i8[:])', cache=True)(solve)

n, m, q = map(int, input().split())
sss = np.array([list(map(int, input())) for _ in range(n)], dtype=np.int8)
xy = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
ans = solve(n, m, q, sss, xy)
print('\n'.join(map(str, ans)))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, M, Q = map(int, input().split())
S = [list(map(int, list(input())[: -1])) for _ in range(N)]
e = [[0] * M for _ in range(N + 1)]
for i in range(1, N + 1):
  for j in range(M - 1): e[i][j + 1] = e[i][j] + ((S[i - 1][j] == 1) and (S[i - 1][j + 1] == 1))
for i in range(1, N):
  for j in range(M): e[i + 1][j] += e[i][j]

cs = [[0] * (M + 1) for _ in range(N + 1)]
for i in range(1, N + 1):
  for j in range(M): cs[i][j + 1] = cs[i][j] + (S[i - 1][j] == 1)
for i in range(1, N):
  for j in range(M + 1): cs[i + 1][j] += cs[i][j]

T = [[0] * N for _ in range(M)]
for i in range(N):
  for j in range(M): T[j][i] = S[i][j]

N, M = M, N
ee = [[0] * M for _ in range(N + 1)]
for i in range(1, N + 1):
  for j in range(M - 1): ee[i][j + 1] = ee[i][j] + ((T[i - 1][j] == 1) and (T[i - 1][j + 1] == 1))
for i in range(1, N):
  for j in range(M): ee[i + 1][j] += ee[i][j]


#print(cs)

for i in range(Q):
  u, l, d, r = map(lambda x: int(x) - 1, input().split())
  rese = e[d + 1][r] - e[d + 1][l] - e[u][r] + e[u][l]
  resee = ee[r + 1][d] - ee[r + 1][u] - ee[l][d] + ee[l][u]
  res = cs[d + 1][r + 1] - cs[d + 1][l] - cs[u][r + 1] + cs[u][l]
  print(res - rese - resee)