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

def cusum(g):
    s = g.cumsum(axis=0).cumsum(axis=1)
    return s

def cusum_edge_row(g):
    gn = np.array(g[:,:-1])
    gn = np.hstack((np.zeros((len(grid), 1), dtype=int), gn))
    s = g & gn
    s = s.cumsum(axis=0).cumsum(axis=1)
    return s

def cusum_edge_col(g):
    gn = np.array(g[:-1])
    gn = np.vstack((np.zeros((1, len(grid[0])), dtype=int), gn))
    s = g & gn
    s = s.cumsum(axis=0).cumsum(axis=1)
    return s

def count_elems(s, lx, ly, hx, hy):
    if lx == 0 and ly == 0:
        return s[hx][hy]
    elif lx == 0:
        return s[hx][hy] - s[hx][ly - 1]
    elif ly == 0:
        return s[hx][hy] - s[lx - 1][hy]
    else:
        return s[hx][hy] - s[hx][ly - 1] - s[lx - 1][hy] + s[lx - 1][ly - 1]

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

grid = np.zeros((N, M), dtype=int)
for i in range(N):
    grid[i] = list(map(int, list(input())))

cusums_nodes = cusum(grid)
cusums_edges_row = cusum_edge_row(grid)
cusums_edges_col = cusum_edge_col(grid)

s_list = []
for _ in range(Q):
    x1, y1, x2, y2 = map(lambda x : int(x) - 1, input().split())
    s_list.append(count_elems(cusums_nodes, x1, y1, x2, y2) - count_elems(cusums_edges_row, x1, y1 + 1, x2, y2) - count_elems(cusums_edges_col, x1 + 1, y1, x2, y2))

for s in s_list:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def cusum(g):
    s = g.cumsum(axis=0).cumsum(axis=1)
    return s

def cusum_edge_row(g):
    gn = np.array(g[:,:-1])
    gn = np.hstack((np.zeros((len(grid), 1), dtype=int), gn))
    s = g & gn
    s = s.cumsum(axis=0).cumsum(axis=1)
    return s

def cusum_edge_col(g):
    gn = np.array(g[:-1])
    gn = np.vstack((np.zeros((1, len(grid[0])), dtype=int), gn))
    s = g & gn
    s = s.cumsum(axis=0).cumsum(axis=1)
    return s

def count_elems(s, lx, ly, hx, hy):
    if lx == 0 and ly == 0:
        return s[hx][hy]
    elif lx == 0:
        return s[hx][hy] - s[hx][ly - 1]
    elif ly == 0:
        return s[hx][hy] - s[lx - 1][hy]
    else:
        return s[hx][hy] - s[hx][ly - 1] - s[lx - 1][hy] + s[lx - 1][ly - 1]

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

grid = np.zeros((N, M), dtype=int)
for i in range(N):
    grid[i] = list(map(int, list(input())))

cusums_nodes = cusum(grid)
cusums_edges_row = cusum_edge_row(grid)
cusums_edges_col = cusum_edge_col(grid)

for _ in range(Q):
    x1, y1, x2, y2 = map(lambda x : int(x) - 1, input().split())
    print(count_elems(cusums_nodes, x1, y1, x2, y2) - count_elems(cusums_edges_row, x1, y1 + 1, x2, y2) - count_elems(cusums_edges_col, x1 + 1, y1, x2, y2))

Submission status: Time Limit Exceeded

Solution code:
import time
import numpy as np

def cusum(g):
    s = g.cumsum(axis=0).cumsum(axis=1)
    return list(s)

def cusum_edge_row(g):
    gn = np.array(g[:,:-1])
    gn = np.hstack((np.zeros((len(grid), 1), dtype=int), gn))
    s = g & gn
    s = s.cumsum(axis=0).cumsum(axis=1)
    return list(s)

def cusum_edge_col(g):
    gn = np.array(g[:-1])
    gn = np.vstack((np.zeros((1, len(grid[0])), dtype=int), gn))
    s = g & gn
    s = s.cumsum(axis=0).cumsum(axis=1)
    return list(s)

def count_elems(s, lx, ly, hx, hy):
    if lx == 0 and ly == 0:
        return s[hx][hy]
    elif lx == 0:
        return s[hx][hy] - s[hx][ly - 1]
    elif ly == 0:
        return s[hx][hy] - s[lx - 1][hy]
    else:
        return s[hx][hy] - s[hx][ly - 1] - s[lx - 1][hy] + s[lx - 1][ly - 1]

start = time.time()

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

grid_l = []
for i in range(N):
    grid_l.append([int(c) for c in input()])
grid = np.array(grid_l)

#print(time.time() - start)

cusums_nodes = cusum(grid)
#print(time.time() - start)
cusums_edges_row = cusum_edge_row(grid)
#print(time.time() - start)
cusums_edges_col = cusum_edge_col(grid)

#print(time.time() - start)

for _ in range(Q):
    x1, y1, x2, y2 = map(lambda x : int(x) - 1, input().split())
    print(count_elems(cusums_nodes, x1, y1, x2, y2) - count_elems(cusums_edges_row, x1, y1 + 1, x2, y2) - count_elems(cusums_edges_col, x1 + 1, y1, x2, y2))

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

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

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

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


    # q
    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:
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
            grid[i*2][j*2+1] = grid[i*2][j*2]*grid[i*2][j*2+2]*(-1)

    for j in range(m):
        for i in range(n-1):
            grid[i*2+1][j*2] = grid[i*2][j*2]*grid[i*2+2][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:
def cusum(grid):
    s = [[0] * len(row) for row in grid]
    s[0][0] = grid[0][0]
    for i, row in enumerate(grid[1:], 1):
        s[i][0] += s[i - 1][0] + row[0] 
    for j, n in enumerate(grid[0][1:], 1):
        s[0][j] += s[0][j - 1] + n
    for i, row in enumerate(grid[1:], 1):
        for j, n in enumerate(row[1:], 1):
            s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + n

    return s

def cusum_edge_row(grid):
    s = [[0] * len(row) for row in grid]
    s[0][0] = 0
    for i, row in enumerate(grid[1:], 1):
        s[i][0] = s[i - 1][0]
    for j, n in enumerate(grid[0][1:], 1):
        if n == 1 and grid[0][j - 1] == 1:
            s[0][j] = s[0][j - 1] + 1
        else:
            s[0][j] = s[0][j - 1]
    for i, row in enumerate(grid[1:], 1):
        for j, n in enumerate(row[1:], 1):
            if n == 1 and grid[i][j - 1] == 1:
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + 1
            else:
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1]
    return s

def cusum_edge_col(grid):
    s = [[0] * len(row) for row in grid]
    s[0][0] = 0
    for i, row in enumerate(grid[1:], 1):
        if row[0] == 1 and grid[i - 1][0] == 1:
            s[i][0] = s[i - 1][0] + 1
        else:
            s[i][0] = s[i - 1][0]
    for j, n in enumerate(grid[0][1:], 1):
        s[0][j] = s[0][j - 1]
    for i, row in enumerate(grid[1:], 1):
        for j, n in enumerate(row[1:], 1):
            if n == 1 and grid[i - 1][j] == 1:
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + 1
            else:
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1]
    return s

def count_elems(s, lx, ly, hx, hy):
    if lx == 0 and ly == 0:
        return s[hx][hy]
    elif lx == 0:
        return s[hx][hy] - s[hx][ly - 1]
    elif ly == 0:
        return s[hx][hy] - s[lx - 1][hy]
    else:
        return s[hx][hy] - s[hx][ly - 1] - s[lx - 1][hy] + s[lx - 1][ly - 1]

#start = time.time()

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

grid = []
for i in range(N):
    grid.append([int(c) for c in input()])

#print(time.time() - start)

cusums_nodes = cusum(grid)
#print(time.time() - start)
cusums_edges_row = cusum_edge_row(grid)
#print(time.time() - start)
cusums_edges_col = cusum_edge_col(grid)

#print(time.time() - start)

for _ in range(Q):
    x1, y1, x2, y2 = map(lambda x : int(x) - 1, input().split())
    #print(x1, y1, x2, y2)
    #a = count_elems(cusums_nodes, x1, y1, x2, y2) - count_elems(cusums_edges_row, x1, y1 + 1, x2, y2) - count_elems(cusums_edges_col, x1 + 1, y1, x2, y2)
    print(count_elems(cusums_nodes, x1, y1, x2, y2) - count_elems(cusums_edges_row, x1, y1 + 1, x2, y2) - count_elems(cusums_edges_col, x1 + 1, y1, x2, y2))

Submission status: Time Limit Exceeded

Solution code:
def cusum(grid):
    s = [[0 for _ in row] for row in grid]
    for i, row in enumerate(grid):
        for j, n in enumerate(row):
            if i == 0 and j == 0:
                s[i][j] = n 
            elif i == 0:
                s[i][j] = s[i][j - 1] + n
            elif j == 0:
                s[i][j] = s[i - 1][j] + n
            else:
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j- 1] + n
    return s

def cusum_edge_row(grid):
    s = [[0 for _ in row] for row in grid]
    for i, row in enumerate(grid):
        for j, n in enumerate(row):
            if i == 0 and j == 0:
                s[i][j] = 0 
            elif i == 0:
                if n == 1 and grid[i][j - 1] == 1:
                    s[i][j] = s[i][j - 1] + 1
                else:
                    s[i][j] = s[i][j - 1]
            elif j == 0:
                s[i][j] = s[i - 1][j]
            else:
                if n == 1 and grid[i][j - 1] == 1:
                    s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j- 1] + 1
                else:
                    s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j- 1]
    return s

def cusum_edge_col(grid):
    s = [[0 for _ in row] for row in grid]
    for i, row in enumerate(grid):
        for j, n in enumerate(row):
            if i == 0 and j == 0:
                s[i][j] = 0 
            elif i == 0:
                s[i][j] = s[i][j - 1]
            elif j == 0:
                if n == 1 and grid[i - 1][j] == 1:
                    s[i][j] = s[i - 1][j] + 1
                else:
                    s[i][j] = s[i - 1][j]
            else:
                if n == 1 and grid[i - 1][j] == 1:
                    s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j- 1] + 1
                else:
                    s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j- 1]
    return s

def count_elems(s, lx, ly, hx, hy):
    if lx == 0 and ly == 0:
        return s[hx][hy]
    elif lx == 0:
        return s[hx][hy] - s[hx][ly - 1]
    elif ly == 0:
        return s[hx][hy] - s[lx - 1][hy]
    else:
        return s[hx][hy] - s[hx][ly - 1] - s[lx - 1][hy] + s[lx - 1][ly - 1]

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

grid = []
for i in range(N):
    grid.append([int(c) for c in input()])
cusums_nodes = cusum(grid)
cusums_edges_row = cusum_edge_row(grid)
cusums_edges_col = cusum_edge_col(grid)
for _ in range(Q):
    x1, y1, x2, y2 = map(lambda x : int(x) - 1, input().split())
    #print(x1, y1, x2, y2)
    print(count_elems(cusums_nodes, x1, y1, x2, y2) - count_elems(cusums_edges_row, x1, y1 + 1, x2, y2) - count_elems(cusums_edges_col, x1 + 1, y1, x2, y2))

Submission status: Time Limit Exceeded

Solution code:
n,m,q=map(int,input().split())
s=[input() for _ in range(n)]
a=[map(int,input().split()) for _ in range(q)]
for k in range(q):
    x1,y1,x2,y2=a[k]
    v=e=0
    for i in range(x1-1,x2):
        for j in range(y1-1,y2):
            if s[i][j]=='1':
                v+=1
                if i!=x2-1 and s[i+1][j]=='1':
                    e+=1
                if j!=y2-1 and s[i][j+1]=='1':
                    e+=1
    print(v-e)

Submission status: Time Limit Exceeded

Solution code:
n, m, q = [int(i) for i in input().split()]
ss = []
for i in range(n):
    ss.append([int(i) for i in input()])
# nblue_tate = [[0]*m] # 青タイルの累積和（タテ）
# nblue_yoko = [[0]*m] # 青タイルの累積和（ヨコ）
nblue = [[0]*(m+1)]
nb_tate = [[0]*(m+1)] # 隣接する青タイルの累積和（タテ）
nb_yoko = [[0]*(m+1)] # 隣接する青タイルの累積和（ヨコ）
for i in range(1, (n+1)):
    # nblue_tate.append(nblue_tate[i-1])
    # nblue_yoko.append(nblue_yoko[i-1])
    nblue.append(nblue[i-1].copy())
    nb_tate.append(nb_tate[i-1].copy())
    nb_yoko.append(nb_yoko[i-1].copy())
    for j in range(1, (m+1)):
        # nblue_tate[i][j] += nblue_tate[i-1][j]
        # nblue_yoko[i][j] += nblue_yoko[i][j-1]
        # nb_tate[i][j] += nb_tate[i-1][j])
        # nb_yoko[i][j] += nb_yoko[i-1][j])
        nblue[i][j] += nblue[i][j-1]
        nb_tate[i][j] += nb_tate[i][j-1]
        nb_yoko[i][j] += nb_yoko[i][j-1]
        # print(i,j, nblue[i])
        nblue[i][j] -= nblue[i-1][j-1]
        nb_tate[i][j] -= nb_tate[i-1][j-1]
        nb_yoko[i][j] -= nb_yoko[i-1][j-1]
        # print(i,j, nblue[i], nblue[i-1])
        if(ss[i-1][j-1] == 1):
            # nblue_tate[i][j] += 1
            # nblue_yoko[i][j] += 1
            # print(i,j, nblue[i])
            nblue[i][j] += 1
            # print(i,j, nblue[i])
            if(i != 1 and ss[i-2][j-1] == 1):
                nb_tate[i][j] += 1
            if(j != 1 and ss[i-1][j-2] ==1):
                nb_yoko[i][j] += 1
        # nblue[i][j] += nblue_yoko[i][j]
# for i in range(1,(n+1)):
#      print(nblue[i][1:m+1])
# for i in range(1,(n+1)):
#      print(nb_tate[i][1:m+1])
# for i in range(1,(n+1)):
#      print(nb_yoko[i][1:m+1])

for i in range(q):
    x1, y1, x2, y2 = [int(i) for i in input().split()]
    node = nblue[x2][y2] - nblue[x1-1][y2] - nblue[x2][y1-1] + nblue[x1-1][y1-1]
    edge = (nb_yoko[x2][y2] - nb_yoko[x1-1][y2] - nb_yoko[x2][y1] + nb_yoko[x1-1][y1])
    edge += (nb_tate[x2][y2] - nb_tate[x1][y2] - nb_tate[x2][y1-1] + nb_tate[x1][y1-1])
    print(node - edge)

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import accumulate

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

    # 青マスの2次元累積和
    sxy = [list(accumulate(s[i])) for i in range(n)]

    for j in range(m):
        for i in range(n - 1):
            sxy[i + 1][j] += sxy[i][j]

    # 枝の2次元累積和(2n * 2mで管理)
    exy = [[0]*(2*m) for i in range(2*n)]

    for i in range(2*n - 1):
        if i % 2 == 0:
            for j in range(2*m - 1):
                exy[i][j + 1] += exy[i][j]
                if j % 2 == 0 and j < 2*m - 2:
                    exy[i][j + 1] += (s[i//2][j//2] == s[i//2][j//2 + 1] == 1)
        else:
            for j in range(2*m - 1):
                if j % 2 == 0:
                    exy[i][j] += (s[i//2][j//2] == s[i//2 + 1][j//2] == 1)

                exy[i][j + 1] += exy[i][j]

    for j in range(2*m):
        for i in range(2*n - 1):
            exy[i + 1][j] += exy[i][j]

    '''
    for i in range(2*n):
        print(exy[i], file=sys.stderr)
    '''

    for qi in range(q):
        x1, y1, x2, y2 = map(lambda x: x - 1, map(int, sys.stdin.readline().split()))

        nv = sxy[x2][y2]

        if x1 - 1 >= 0:
            nv -= sxy[x1 - 1][y2]
        if y1 - 1 >= 0:
            nv -= sxy[x2][y1 - 1]
        if x1 - 1 >= 0 and y1 - 1 >= 0:
            nv += sxy[x1 - 1][y1 - 1]

        ne = exy[2*x2][2*y2]

        if 2*x1 - 1 >= 0:
            ne -= exy[2*x1 - 1][2*y2]
        if 2*y1 - 1 >= 0:
            ne -= exy[2*x2][2*y1 - 1]
        if 2*x1 - 1 >= 0 and 2*y1 - 1 >= 0:
            ne += exy[2*x1 - 1][2*y1 - 1]

        ans = nv - ne

        print(ans)

if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
f=lambda s,y1,x1,y2,x2:s[y2][x2]-s[y2][x1-1]-s[y1-1][x2]+s[y1-1][x1-1]
H,W,N=map(int,raw_input().split())
a=[map(int,raw_input()) for _ in [0]*H]
s,s1,s2=[ [[0]*(W+1) for _ in [0]*-~H] for _ in [0]*3 ]
for h in range(H):
	for w in range(W):
		s[h+1][w+1]=s[h+1][w]+s[h][w+1]-s[h][w]+a[h][w]
		s1[h+1][w+1]=s1[h+1][w]+s1[h][w+1]-s1[h][w]+(a[h][w]*(w+1<W and a[h][w+1]))
		s2[h+1][w+1]=s2[h+1][w]+s2[h][w+1]-s2[h][w]+(a[h][w]*(h+1<H and a[h+1][w]))
for _ in [0]*N:
	y1,x1,y2,x2=map(int,raw_input().split())
	print f(s,y1,x1,y2,x2)-f(s1,y1,x1,y2,x2-1)-f(s2,y1,x1,y2-1,x2)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout

N, M, Q = map(int, stdin.readline().split())
S = ['_' * (M + 1) for _ in range(N + 1)]
for i in range(1, N + 1):
    S[i] = '_' + stdin.readline()
# print('S', S)

kuro = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
yoko = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
tate = [[0 for _ in range(M + 1)] for _ in range(N + 1)]

for i in range(1, N + 1):
    ki, ti, yi, = 0, 0, 0
    for j in range(1, M + 1):
        kuro[i][j] = kuro[i - 1][j]
        tate[i][j] = tate[i - 1][j]
        yoko[i][j] = yoko[i - 1][j]
        if S[i][j] == '1':
            ki += 1
            if S[i - 1][j] == '1':
                ti += 1
            if S[i][j - 1] == '1':
                yi += 1
        kuro[i][j] += ki
        tate[i][j] += ti
        yoko[i][j] += yi
# print('kuro', kuro)
# print('tate', tate)
# print('yoko', yoko)


# def cum(mat, x1, y1, x2, y2):
#     x1, y1 = x1 - 1, y1 - 1
#     # print(mat[x1][y1])
#     # print(mat[x2][y2])
#     # print(mat[x1][y2])
#     # print(mat[x2][y1])
#     return mat[x1][y1] + mat[x2][y2] - mat[x1][y2] - mat[x2][y1]

ans = [None for _ in range(Q)]
for q in range(Q):
    x1, y1, x2, y2 = map(int, stdin.readline().split())
    cum_kuro = kuro[x1 - 1][y1 - 1] + kuro[x2][y2] - kuro[x1 - 1][y2] - kuro[x2][y1 - 1]
    cum_tate = tate[x1][y1 - 1] + tate[x2][y2] - tate[x1][y2] - tate[x2][y1 - 1]
    cum_yoko = yoko[x1 - 1][y1] + yoko[x2][y2] - yoko[x1 - 1][y2] - yoko[x2][y1]
    # print('cums', cum_kuro, cum_tate, cum_yoko)

    # print(cum_kuro - cum_tate - cum_yoko)
    ans[q] = cum_kuro - cum_tate - cum_yoko
stdout.write('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout

N, M, Q = map(int, stdin.readline().split())
S = ['_' * (M + 1) for _ in range(N + 1)]
for i in range(1, N + 1):
    S[i] = '_' + stdin.readline()
# print('S', S)

kuro = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
yoko = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
tate = [[0 for _ in range(M + 1)] for _ in range(N + 1)]

for i in range(1, N + 1):
    ki, ti, yi, = 0, 0, 0
    for j in range(1, M + 1):
        kuro[i][j] = kuro[i - 1][j]
        tate[i][j] = tate[i - 1][j]
        yoko[i][j] = yoko[i - 1][j]
        if S[i][j] == '1':
            ki += 1
            if S[i - 1][j] == '1':
                ti += 1
            if S[i][j - 1] == '1':
                yi += 1
        kuro[i][j] += ki
        tate[i][j] += ti
        yoko[i][j] += yi
# print('kuro', kuro)
# print('tate', tate)
# print('yoko', yoko)


def cum(mat, x1, y1, x2, y2):
    x1, y1 = x1 - 1, y1 - 1
    # print(mat[x1][y1])
    # print(mat[x2][y2])
    # print(mat[x1][y2])
    # print(mat[x2][y1])
    return mat[x1][y1] + mat[x2][y2] - mat[x1][y2] - mat[x2][y1]

ans = [None for _ in range(Q)]
for q in range(Q):
    x1, y1, x2, y2 = map(int, stdin.readline().split())
    cum_kuro = cum(kuro, x1, y1, x2, y2)
    cum_tate = cum(tate, x1 + 1, y1, x2, y2)
    cum_yoko = cum(yoko, x1, y1 + 1, x2, y2)
    # print('cums', cum_kuro, cum_tate, cum_yoko)

    # print(cum_kuro - cum_tate - cum_yoko)
    ans[q] = cum_kuro - cum_tate - cum_yoko
stdout.write('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
N, M, Q = map(int, input().split())
S = ['_' * (M + 1) for _ in range(N + 1)]
for i in range(1, N + 1):
    S[i] = '_' + input()
# print('S', S)

kuro = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
yoko = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
tate = [[0 for _ in range(M + 1)] for _ in range(N + 1)]

for i in range(1, N + 1):
    ki, ti, yi, = 0, 0, 0
    for j in range(1, M + 1):
        kuro[i][j] = kuro[i - 1][j]
        tate[i][j] = tate[i - 1][j]
        yoko[i][j] = yoko[i - 1][j]
        if S[i][j] == '1':
            ki += 1
            if S[i - 1][j] == '1':
                ti += 1
            if S[i][j - 1] == '1':
                yi += 1
        kuro[i][j] += ki
        tate[i][j] += ti
        yoko[i][j] += yi
# print('kuro', kuro)
# print('tate', tate)
# print('yoko', yoko)


def cum(mat, x1, y1, x2, y2):
    x1, y1 = x1 - 1, y1 - 1
    # print(mat[x1][y1])
    # print(mat[x2][y2])
    # print(mat[x1][y2])
    # print(mat[x2][y1])
    return mat[x1][y1] + mat[x2][y2] - mat[x1][y2] - mat[x2][y1]

ans = [None for _ in range(Q)]
for q in range(Q):
    x1, y1, x2, y2 = map(int, input().split())
    cum_kuro = cum(kuro, x1, y1, x2, y2)
    cum_tate = cum(tate, x1 + 1, y1, x2, y2)
    cum_yoko = cum(yoko, x1, y1 + 1, x2, y2)
    # print('cums', cum_kuro, cum_tate, cum_yoko)

    # print(cum_kuro - cum_tate - cum_yoko)
    ans[q] = cum_kuro - cum_tate - cum_yoko
print('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
N, M, Q = map(int, input().split())
S = ['_' * (M + 1) for _ in range(N + 1)]
for i in range(1, N + 1):
    S[i] = '_' + input()
# print('S', S)

kuro = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
yoko = [[0 for _ in range(M + 1)] for _ in range(N + 1)]
tate = [[0 for _ in range(M + 1)] for _ in range(N + 1)]

for i in range(1, N + 1):
    ki, ti, yi, = 0, 0, 0
    for j in range(1, M + 1):
        kuro[i][j] = kuro[i - 1][j]
        tate[i][j] = tate[i - 1][j]
        yoko[i][j] = yoko[i - 1][j]
        if S[i][j] == '1':
            ki += 1
            if S[i - 1][j] == '1':
                ti += 1
            if S[i][j - 1] == '1':
                yi += 1
        kuro[i][j] += ki
        tate[i][j] += ti
        yoko[i][j] += yi
# print('kuro', kuro)
# print('tate', tate)
# print('yoko', yoko)


def cum(mat, x1, y1, x2, y2):
    x1, y1 = x1 - 1, y1 - 1
    # print(mat[x1][y1])
    # print(mat[x2][y2])
    # print(mat[x1][y2])
    # print(mat[x2][y1])
    return mat[x1][y1] + mat[x2][y2] - mat[x1][y2] - mat[x2][y1]


for _ in range(Q):
    x1, y1, x2, y2 = map(int, input().split())
    cum_kuro = cum(kuro, x1, y1, x2, y2)
    cum_tate = cum(tate, x1 + 1, y1, x2, y2)
    cum_yoko = cum(yoko, x1, y1 + 1, x2, y2)
    # print('cums', cum_kuro, cum_tate, cum_yoko)
    print(cum_kuro - cum_tate - cum_yoko)

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) 

sol_list = []

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]
    
    sol_list.append(N_nodes - N_edges1 - N_edges2)

for q in range(Q):
    print(sol_list[q])

Submission status: Time Limit Exceeded

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

grid = []
acc = []
for i in range(N):
  n = list(map(int, list(input())))
  params = []
  for j in range(M):
    num_node = 0
    num_v_edge = 0
    num_h_edge = 0
    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
    if i > 0 and j > 0:
      num_node += acc[i - 1][j][0] + params[j - 1][0] - acc[i - 1][j - 1][0]
      num_v_edge += acc[i - 1][j][1] + params[j - 1][1] - acc[i - 1][j - 1][1]
      num_h_edge += acc[i - 1][j][2] + params[j - 1][2] - acc[i - 1][j - 1][2]
    elif i > 0:
      num_node += acc[i - 1][j][0]
      num_v_edge += acc[i - 1][j][1]
      num_h_edge += acc[i - 1][j][2]
    elif j > 0:
      num_node += params[j - 1][0]
      num_v_edge += params[j - 1][1]
      num_h_edge += params[j - 1][2]
    params.append((num_node, num_v_edge, num_h_edge))
  acc.append(params)
  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[x2 - 1][y2 - 1][0] - acc[x1 - 2][y2 - 1][0] - acc[x2 - 1][y1 - 2][0] + acc[x1 - 2][y1 - 2][0]
    num_v_edge = acc[x2 - 1][y2 - 1][1] - acc[x1 - 1][y2 - 1][1] - acc[x2 - 1][y1 - 2][1] + acc[x1 - 1][y1 - 2][1]
    num_h_edge = acc[x2 - 1][y2 - 1][2] - acc[x1 - 2][y2 - 1][2] - acc[x2 - 1][y1 - 1][2] + acc[x1 - 2][y1 - 1][2]
    print(num_node - num_v_edge - num_h_edge)
  elif x1 > 1:
    num_node = acc[x2 - 1][y2 - 1][0] - acc[x1 - 2][y2 - 1][0]
    num_v_edge = acc[x2 - 1][y2 - 1][1] - acc[x1 - 1][y2 - 1][1]
    num_h_edge = acc[x2 - 1][y2 - 1][2] - acc[x1 - 2][y2 - 1][2]
    print(num_node - num_v_edge - num_h_edge)
  elif y1 > 1:
    num_node = acc[x2 - 1][y2 - 1][0] - acc[x2 - 1][y1 - 2][0]
    num_v_edge = acc[x2 - 1][y2 - 1][1] - acc[x2 - 1][y1 - 2][1]
    num_h_edge = acc[x2 - 1][y2 - 1][2] - acc[x2 - 1][y1 - 1][2]
    print(num_node - num_v_edge - num_h_edge)
  else:
    num_node = acc[x2 - 1][y2 - 1][0]
    num_v_edge = acc[x2 - 1][y2 - 1][1]
    num_h_edge = acc[x2 - 1][y2 - 1][2]
    print(num_node - num_v_edge - num_h_edge)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

S = np.empty((N+1, M+1), dtype='int')

for n in range(1, N+1):
    S[n, :] = [0] + 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) 

sol_list = []

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]
    
    sol_list.append(N_nodes - N_edges1 - N_edges2)

for q in range(Q):
    print(sol_list[q])

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):
  n = list(map(int, list(input())))
  node = []
  v_edge = []
  h_edge = []
  for j in range(M):
    num_node = 0
    num_v_edge = 0
    num_h_edge = 0
    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
    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]
    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:
import numpy as np

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

S = np.empty((N+1, M+1), dtype='int')

for n in range(1, N+1):
    S[n, :] = [0] + 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)