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: Time Limit Exceeded

Solution code:
import numpy as np

N, M, Q = map(int, input().split())

S = np.zeros((N+1, M+1), dtype='int')
for n in range(1, N+1):
    S[n, 1:] = list(map(int, list(input())))

# count nodes
N_cum = np.cumsum(np.cumsum(S, axis=0), axis=1) 
# count edges(row)
ER_cum = np.cumsum(np.cumsum(S[:N, :]*S[1:, :], axis=0), axis=1) 
# count edges(col)
EC_cum = np.cumsum(np.cumsum(S[:, :M]*S[:, 1:], axis=0), axis=1) 

for _ in range(Q):
    x1, y1, x2, y2 = map(int, input().split())
    # nodes
    N_nodes = N_cum[x2, y2] - N_cum[x1-1, y2] - N_cum[x2, y1-1] + N_cum[x1-1, y1-1]
    # edges(row)
    N_edges1 = ER_cum[x2-1, y2] - ER_cum[x1-1, y2] - ER_cum[x2-1, y1-1] + ER_cum[x1-1, y1-1]
    # edges(col)
    N_edges2 = EC_cum[x2, y2-1] - EC_cum[x1-1, y2-1] - EC_cum[x2, y1-1] + EC_cum[x1-1, y1-1]
    
    print(N_nodes - N_edges1 - N_edges2)

Submission status: Time Limit Exceeded

Solution code:
N, M, Q = list(map(int, input().split()))

grid = []
acc_node = []
acc_v_edge = []
acc_h_edge = []
for i in range(N):
  node = []
  v_edge = []
  h_edge = []
  n = list(map(str, input()))
  for j in range(M):
    num_node = 0
    num_v_edge = 0
    num_h_edge = 0
    if i > 0 and j > 0:
      num_node += acc_node[i - 1][j] + node[j - 1] - acc_node[i - 1][j - 1]
      num_v_edge += acc_v_edge[i - 1][j] + v_edge[j - 1] - acc_v_edge[i - 1][j - 1]
      num_h_edge += acc_h_edge[i - 1][j] + h_edge[j - 1] - acc_h_edge[i - 1][j - 1]
    elif i > 0:
      num_node += acc_node[i - 1][j]
      num_v_edge += acc_v_edge[i - 1][j]
      num_h_edge += acc_h_edge[i - 1][j]
    elif j > 0:
      num_node += node[j - 1]
      num_v_edge += v_edge[j - 1]
      num_h_edge += h_edge[j - 1]
    if n[j] == "1":
      num_node += 1
      if i > 0 and grid[i - 1][j] == "1":
        num_v_edge += 1
      if j > 0 and n[j - 1] == "1":
        num_h_edge += 1
    node.append(num_node)
    v_edge.append(num_v_edge)
    h_edge.append(num_h_edge)
  acc_node.append(node)
  acc_v_edge.append(v_edge)
  acc_h_edge.append(h_edge)
  grid.append(n)

for i in range(Q):
  x1, y1, x2, y2 = list(map(int, input().split()))
  if x1 > 1 and y1 > 1:
    num_node = acc_node[x2 - 1][y2 - 1] - acc_node[x1 - 2][y2 - 1] - acc_node[x2 - 1][y1 - 2] + acc_node[x1 - 2][y1 - 2]
    num_v_edge = acc_v_edge[x2 - 1][y2 - 1] - acc_v_edge[x1 - 1][y2 - 1] - acc_v_edge[x2 - 1][y1 - 2] + acc_v_edge[x1 - 1][y1 - 2]
    num_h_edge = acc_h_edge[x2 - 1][y2 - 1] - acc_h_edge[x1 - 2][y2 - 1] - acc_h_edge[x2 - 1][y1 - 1] + acc_h_edge[x1 - 2][y1 - 1]
  elif x1 > 1:
    num_node = acc_node[x2 - 1][y2 - 1] - acc_node[x1 - 2][y2 - 1]
    num_v_edge = acc_v_edge[x2 - 1][y2 - 1] - acc_v_edge[x1 - 1][y2 - 1]
    num_h_edge = acc_h_edge[x2 - 1][y2 - 1] - acc_h_edge[x1 - 2][y2 - 1]
  elif y1 > 1:
    num_node = acc_node[x2 - 1][y2 - 1] - acc_node[x2 - 1][y1 - 2]
    num_v_edge = acc_v_edge[x2 - 1][y2 - 1] - acc_v_edge[x2 - 1][y1 - 2]
    num_h_edge = acc_h_edge[x2 - 1][y2 - 1] - acc_h_edge[x2 - 1][y1 - 1]
  else:
    num_node = acc_node[x2 - 1][y2 - 1]
    num_v_edge = acc_v_edge[x2 - 1][y2 - 1]
    num_h_edge = acc_h_edge[x2 - 1][y2 - 1]
  print(num_node - num_v_edge - num_h_edge)

Submission status: Time Limit Exceeded

Solution code:
N, M, Q = list(map(int, input().split()))

grid = []
for i in range(N):
   grid.append(list(map(str, input())))

for i in range(Q):
  num_node = 0
  num_edge = 0
  x1, y1, x2, y2 = list(map(int, input().split()))
  for j in range(x1 - 1, x2):
    for k in range(y1 - 1, y2):
      if grid[j][k] == "1":
        num_node += 1
        if x2 > j + 1 and grid[j + 1][k] == "1":
          num_edge  += 1
        if y2 > k + 1 and grid[j][k + 1] == "1":
          num_edge  += 1
  #ノード数が木はエッジ数より１多い
  print(num_node - num_edge)

Submission status: Time Limit Exceeded

Solution code:
def c():
    import numpy as np
    n, m, q = map(int, input().split())
    grid = np.zeros([n*2-1, m*2-1])

    for i in range(n):
        s = list(map(int, input()))
        for j in range(m):
            grid[i*2][j*2] = s[j]

    for i in range(n): # 0,1,2
        # i = i*2 # 0,2,4
        for j in range(m-1): # 0,1,2,3
            # j = j*2 # 0,2,4,6
            if grid[i*2][j*2]*grid[i*2][j*2+2] == 1:
                grid[i*2][j*2+1] = -1
    for j in range(m):
        for i in range(n-1):
            if grid[i*2][j*2]*grid[i*2+2][j*2] == 1:
                grid[i*2+1][j*2] = -1

    # print(grid)

    ans = []
    for _ in range(q):
        x1, y1, x2, y2 = map(lambda i: (int(i)-1)*2, input().split())
        s = grid[x1:x2+1, y1:y2+1]
        res = s.sum()
        ans.append(res)
        # print(s)
        # print(res)

    for a in ans:
        print(int(a))
    pass

c()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys
import os

N, M, Q = map(int, input().split())

def printM(A):
    for a in A:
        print(a)

A = []
for i in range(N):
    lst = list(map(int, list(input().strip())))
    A.append(lst)

def slice(A, x1, y1, x2, y2):
    B = []
    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1
    for x in range(x1, x2+1):
        B.append(A[x][y1:y2+1])
    return B

arounds = [(1, 0), (-1, 0), (0, 1), (0, -1)]

def connected_component(A):
    H = len(A)
    W = len(A[0])
    num = 0
    Q = []

    for i in range(H):
        for j in range(W):
            if A[i][j] == 1:
                num += 1
                Q.append((j, i))

            # paint to zero
            while Q:
                x, y = Q.pop(0)
                A[y][x] = 0
                for around in arounds:
                    next_x = x + around[0]
                    next_y = y + around[1]
                    if 0 <= next_x < W and 0 <= next_y < H and A[next_y][next_x] == 1:
                        Q.append((next_x, next_y))

    return num

for i in range(Q):
    x1, y1, x2, y2 = map(int, input().split())
    B = slice(A, x1, y1, x2, y2)
    print(connected_component(B))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
from itertools import repeat
def main():
    n, m, q = map(int, stdin.readline().split())
    s = [stdin.readline().strip() for _ in xrange(n)]
    dat = map(int, stdin.read().split(), repeat(10, 4 * q))
    ar = [[0] * (m + 1) for _ in xrange(n + 1)]
    ac = [[0] * (m + 1) for _ in xrange(n + 1)]
    b = [[0] * (m + 1) for _ in xrange(n + 1)]
    for i, r in enumerate(s):
        for j, c in enumerate(r):
            ar[i+1][j+1] = ar[i+1][j] + ar[i][j+1] - ar[i][j] + (i and c == s[i-1][j] == '1')
            ac[i+1][j+1] = ac[i+1][j] + ac[i][j+1] - ac[i][j] + (j and c == s[i][j-1] == '1')
            b[i+1][j+1] = b[i+1][j] + b[i][j+1] - b[i][j] + (c == '1')
    ans = [0] * q
    for i in xrange(q):
        x1, y1, x2, y2 = dat[i*4:i*4+4]
        ans[i] = b[x2][y2] - b[x2][y1-1] - b[x1-1][y2] + b[x1-1][y1-1]
        ans[i] -= ac[x2][y2] - ac[x2][y1] - ac[x1-1][y2] + ac[x1-1][y1]
        ans[i] -= ar[x2][y2] - ar[x2][y1-1] - ar[x1][y2] + ar[x1][y1-1]
    stdout.write('\n'.join(map(str, ans)))
    stdout.write('\n')
main()

Submission status: Time Limit Exceeded

Solution code:
import itertools

if __name__ == '__main__':
    n, m, q = map(int, input().split())
    grid = tuple(tuple(map(int, input())) for _ in range(n))
    answers = []

    for _ in range(q):
        x1, y1, x2, y2 = (int(token) - 1 for token in input().split())

        blues = {}
        for x, y in itertools.product(range(x1, x2 + 1), range(y1, y2 + 1)):
            if grid[x][y] == 1: blues[(x, y)] = 0

        stack = list(blues.keys())
        cnt = 0
        while stack:
            x, y = stack.pop()

            if blues[(x, y)] == 0:
                cnt += 1
                blues[(x, y)] = cnt

            for i, j in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
                if (i, j) in blues and blues[(i, j)] == 0:
                    blues[(i, j)] = blues[(x, y)]
                    stack.append((i, j))

        answers.append(cnt)

    for answer in answers: print(answer)

Submission status: Memory Limit Exceeded

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])
    ans = [[0]*(w+1) for _ in range(h+1)]
    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: Memory Limit Exceeded

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])
    ans = [[0]*(w+1) for _ in range(h+1)]
    for i in range(1,h+1):
        for j in range(1,w+1):
            ans[i][j] = ans[i-1][j] + ans[i][j-1] - ans[i-1][j-1] + v[i-1][j-1]
    del v
    return ans
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: Memory Limit Exceeded

Solution code:
import sys

n, m, q = map(int, input().split())
dp1 = [[0] * (m + 1) for _ in range(n + 1)]
dpv = [[0] * (m + 1) for _ in range(n + 1)]
dph = [[0] * (m + 1) for _ in range(n + 1)]

prev_s = '0' * m

for i in range(n):
    s = input()
    for j in range(m):
        is1 = s[j] == '1'
        additional = 0

        if is1:
            dp1[i + 1][j + 1] = 1

            if i > 0 and prev_s[j] == '1':
                dpv[i + 1][j + 1] = 1
            if j > 0 and s[j - 1] == '1':
                dph[i + 1][j + 1] = 1
    prev_s = s

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]

mp = map(int, sys.stdin.read().split())
buf = []
for x1, y1, x2, y2 in zip(mp, mp, mp, mp):
    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.append(cnt1 - ver1 - hor1)

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

Submission status: Memory Limit Exceeded

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]

#print(cs)
qs = []
resq = [0] * Q
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]
  res = cs[d + 1][r + 1] - cs[d + 1][l] - cs[u][r + 1] + cs[u][l]
  qs.append((u, l, d, r))
  resq[i] = res - rese
  #print(res, rese)

T = [[S[i][j] for i in range(N)] for j in range(M)]
N, M = M, 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] + ((T[i - 1][j] == 1) and (T[i - 1][j + 1] == 1))
for i in range(1, N):
  for j in range(M): e[i + 1][j] += e[i][j]

for i in range(Q):
  l, u, r, d = qs[i]
  resq[i] -= e[d + 1][r] - e[d + 1][l] - e[u][r] + e[u][l]
  print(resq[i])

Submission status: Memory Limit Exceeded

Solution code:
def main():
    from itertools import accumulate as ac
    n, m, q = map(int, input().split())
    ten = [list(map(lambda x:x == "1", list(input()))) for _ in [0]*n]
    hen1 = [[0]*m]+[None]*n
    for i in range(n):
        temp = [0]
        for j in range(m-1):
            temp.append(ten[i][j] & ten[i][j+1])
        hen1[i+1] = list(ac(temp))
    hen2 = [[0]*(m+1)]+[None]*(n-1)
    for i in range(n-1):
        temp = [0]
        for j in range(m):
            temp.append(ten[i][j] & ten[i+1][j])
        hen2[i+1] = list(ac(temp))
    ten = [[0]*(m+1)]+ten
    for i in range(1, n+1):
        ten[i] = [0]+list(ac(ten[i]))
    for i in range(n):
        for j in range(1, m+1):
            ten[i+1][j] += ten[i][j]
    for i in range(n):
        for j in range(1, m):
            hen1[i+1][j] += hen1[i][j]
    for i in range(n-1):
        for j in range(1, m+1):
            hen2[i+1][j] += hen2[i][j]

    for _ in range(q):
        x1, y1, x2, y2 = map(int, input().split())
        ans = ten[x2][y2]+ten[x1-1][y1-1]-ten[x2][y1-1]-ten[x1-1][y2]
        ans -= hen1[x2][y2-1]+hen1[x1-1][y1-1]-hen1[x2][y1-1]-hen1[x1-1][y2-1]
        ans -= hen2[x2-1][y2]+hen2[x1-1][y1-1]-hen2[x2-1][y1-1]-hen2[x1-1][y2]
        print(ans)


main()

Submission status: Memory Limit Exceeded

Solution code:
import gc


class Ruiseki2D():
    """二次元累積和を構築する
    構築O(HW), 区間取得クエリO(1)
    """
    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(map(int, input())) for i in range(n)]
query = [list(map(int, input().split())) for i in range(q)]

ru_col_cnt = Ruiseki2D(s)

yoko_edge = [[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:
            yoko_edge[i][j] = 1
ru_yoko_cnt = Ruiseki2D(yoko_edge)

del yoko_edge
gc.collect()

tate_edge = [[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:
            tate_edge[i][j] = 1
ru_tate_cnt = Ruiseki2D(tate_edge)

del tate_edge
gc.collect()
         
for hl, wl, hr, wr in query:
    hl, wl = hl - 1, wl - 1
    ans = ru_col_cnt.get_sum(hl, hr, wl, wr)
    ans -= ru_yoko_cnt.get_sum(hl, hr, wl, wr - 1) + ru_tate_cnt.get_sum(hl, hr - 1, wl, wr)
    print(ans)

Submission status: Memory Limit Exceeded

Solution code:
class Ruiseki2D():
    """二次元累積和を構築する
    構築O(HW), 区間取得クエリO(1)
    """
    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(map(int, input())) for i in range(n)]
query = [list(map(int, input().split())) for i in range(q)]

ru_col_cnt = Ruiseki2D(s)

yoko_edge = [[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:
            yoko_edge[i][j] = 1
ru_yoko_cnt = Ruiseki2D(yoko_edge)

tate_edge = [[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:
            tate_edge[i][j] = 1
ru_tate_cnt = Ruiseki2D(tate_edge)
         
for hl, wl, hr, wr in query:
    hl, wl = hl - 1, wl - 1
    ans = ru_col_cnt.get_sum(hl, hr, wl, wr)
    ans -= ru_yoko_cnt.get_sum(hl, hr, wl, wr - 1) + ru_tate_cnt.get_sum(hl, hr - 1, wl, wr)
    print(ans)

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)]


def count_v(x1, y1, x2, y2):
    return counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]


def count_ev(x1, y1, x2, y2):
    return edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]


def count_eh(x1, y1, x2, y2):
    return edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]


S = np.array(S, dtype=int) == 1
vs = []
e1 = []
e2 = []

counts_cum = np.pad(S.cumsum(axis=0).cumsum(axis=1), [(1, 0), (1, 0)], 'constant')
for x1, y1, x2, y2 in XY:
    vs.append(count_v(x1, y1, x2, y2))
del counts_cum

edges_v_cum = np.pad((S[1:] & S[:-1]).cumsum(axis=0).cumsum(axis=1), [(2, 0), (1, 0)], 'constant')
for x1, y1, x2, y2 in XY:
    e1.append(count_ev(x1, y1, x2, y2))
del edges_v_cum

edges_h_cum = np.pad((S[:, 1:] & S[:, :-1]).cumsum(axis=0).cumsum(axis=1), [(1, 0), (2, 0)], 'constant')
for x1, y1, x2, y2 in XY:
    e2.append(count_eh(x1, y1, x2, y2))
del edges_h_cum

ans = (np.array(vs) - np.array(e1) - np.array(e2)).astype(int)
print(*ans, sep='\n')

Submission status: Memory Limit Exceeded

Solution code:
def main():
    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)]


    def count_v(x1, y1, x2, y2):
        return counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]


    def count_ev(x1, y1, x2, y2):
        return edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]


    def count_eh(x1, y1, x2, y2):
        return edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]


    S = np.array(S, dtype=int) == 1
    vs = []
    e1 = []
    e2 = []

    counts_cum = np.zeros((N + 1, M + 1), dtype=np.int32)
    counts_cum[1:, 1:] = S.cumsum(axis=0).cumsum(axis=1)
    counts_cum = counts_cum.tolist()
    for x1, y1, x2, y2 in XY:
        vs.append(count_v(x1, y1, x2, y2))
    del counts_cum

    edges_v_cum = np.zeros((N + 1, M + 1), dtype=np.int32)
    edges_v_cum[2:, 1:] = (S[1:] & S[:-1]).cumsum(axis=0).cumsum(axis=1)
    edges_v_cum = edges_v_cum.tolist()
    for x1, y1, x2, y2 in XY:
        e1.append(count_ev(x1, y1, x2, y2))
    del edges_v_cum

    edges_h_cum = np.zeros((N + 1, M + 1), dtype=np.int32)
    edges_h_cum[1:, 2:] = (S[:, 1:] & S[:, :-1]).cumsum(axis=0).cumsum(axis=1)
    edges_h_cum = edges_h_cum.tolist()
    for x1, y1, x2, y2 in XY:
        e2.append(count_eh(x1, y1, x2, y2))
    del edges_h_cum

    ans = (np.array(vs) - np.array(e1) - np.array(e2)).astype(int)
    print(*ans, sep='\n')

main()

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])

    tmp = []
    for row in mat:
        tmp.append(cumsum(row))
    del mat

    ret = [[0] * (w + 1) for _ in range(h + 1)]
    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)]


def count_v(x1, y1, x2, y2):
    return counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]


def count_ev(x1, y1, x2, y2):
    return edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]


def count_eh(x1, y1, x2, y2):
    return edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]


vs = []
e1 = []
e2 = []

counts_cum = cumsum_mat(S)
for x1, y1, x2, y2 in XY:
    vs.append(count_v(x1, y1, x2, y2))
del counts_cum

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_v_cum = cumsum_mat(edges_v)
for x1, y1, x2, y2 in XY:
    e1.append(count_ev(x1, y1, x2, y2))
del edges_v
del edges_v_cum

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]
edges_h_cum = cumsum_mat(edges_h)
for x1, y1, x2, y2 in XY:
    e2.append(count_eh(x1, y1, x2, y2))
del edges_h
del edges_h_cum

ans = [v - e1 - e2 for v, e1, e2 in zip(vs, e1, e2)]
print(*ans, sep='\n')

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)]


def count_v(x1, y1, x2, y2):
    return counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]


def count_ev(x1, y1, x2, y2):
    return edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]


def count_eh(x1, y1, x2, y2):
    return edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]


vs = []
e1 = []
e2 = []

counts_cum = cumsum_mat(S)
for x1, y1, x2, y2 in XY:
    vs.append(count_v(x1, y1, x2, y2))
del counts_cum

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_v_cum = cumsum_mat(edges_v)
for x1, y1, x2, y2 in XY:
    e1.append(count_ev(x1, y1, x2, y2))
del edges_v
del edges_v_cum

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]
edges_h_cum = cumsum_mat(edges_h)
for x1, y1, x2, y2 in XY:
    e2.append(count_eh(x1, y1, x2, y2))
del edges_h
del edges_h_cum

ans = [v - e1 - e2 for v, e1, e2 in zip(vs, e1, e2)]
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)]


def count_v(x1, y1, x2, y2):
    return counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]


def count_ev(x1, y1, x2, y2):
    return edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]


def count_eh(x1, y1, x2, y2):
    return edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]


S = np.array(S, dtype=int) == 1
vs = []
e1 = []
e2 = []

counts_cum = np.zeros((N + 1, M + 1), dtype=np.int32)
counts_cum[1:, 1:] = S.cumsum(axis=0).cumsum(axis=1)
counts_cum = counts_cum.tolist()
for x1, y1, x2, y2 in XY:
    vs.append(count_v(x1, y1, x2, y2))
del counts_cum

edges_v_cum = np.zeros((N + 1, M + 1), dtype=np.int32)
edges_v_cum[2:, 1:] = (S[1:] & S[:-1]).cumsum(axis=0).cumsum(axis=1)
edges_v_cum = edges_v_cum.tolist()
for x1, y1, x2, y2 in XY:
    e1.append(count_ev(x1, y1, x2, y2))
del edges_v_cum

edges_h_cum = np.zeros((N + 1, M + 1), dtype=np.int32)
edges_h_cum[1:, 2:] = (S[:, 1:] & S[:, :-1]).cumsum(axis=0).cumsum(axis=1)
edges_h_cum = edges_h_cum.tolist()
for x1, y1, x2, y2 in XY:
    e2.append(count_eh(x1, y1, x2, y2))
del edges_h_cum

ans = (np.array(vs) - np.array(e1) - np.array(e2)).astype(int)
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)]


def count_v(x1, y1, x2, y2):
    return counts_cum[x2][y2] - counts_cum[x1 - 1][y2] - counts_cum[x2][y1 - 1] + counts_cum[x1 - 1][y1 - 1]


def count_ev(x1, y1, x2, y2):
    return edges_v_cum[x2][y2] - edges_v_cum[x1][y2] - edges_v_cum[x2][y1 - 1] + edges_v_cum[x1][y1 - 1]


def count_eh(x1, y1, x2, y2):
    return edges_h_cum[x2][y2] - edges_h_cum[x1 - 1][y2] - edges_h_cum[x2][y1] + edges_h_cum[x1 - 1][y1]


S = np.array(S, dtype=int)
vs = []
e1 = []
e2 = []

counts_cum = np.zeros((N + 1, M + 1), dtype=int)
counts_cum[1:, 1:] = S.cumsum(axis=0).cumsum(axis=1)
counts_cum = counts_cum.tolist()
for x1, y1, x2, y2 in XY:
    vs.append(count_v(x1, y1, x2, y2))
del counts_cum

edges_v_cum = np.zeros((N + 1, M + 1), dtype=int)
edges_v_cum[2:, 1:] = (S[1:] & S[:-1]).cumsum(axis=0).cumsum(axis=1)
edges_v_cum = edges_v_cum.tolist()
for x1, y1, x2, y2 in XY:
    e1.append(count_ev(x1, y1, x2, y2))
del edges_v_cum

edges_h_cum = np.zeros((N + 1, M + 1), dtype=int)
edges_h_cum[1:, 2:] = (S[:, 1:] & S[:, :-1]).cumsum(axis=0).cumsum(axis=1)
edges_h_cum = edges_h_cum.tolist()
for x1, y1, x2, y2 in XY:
    e2.append(count_eh(x1, y1, x2, y2))
del edges_h_cum

ans = (np.array(vs) - np.array(e1) - np.array(e2)).astype(int)
print(*ans, sep='\n')