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:
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]+[[0]+list(ac([ten[i][j] & ten[i][j+1] for j in range(m-1)]))
                    for i in range(n)]
    hen2 = [[0]*(m+1)]+[[0]+list(ac([ten[i][j] & ten[i+1][j] for j in range(m)]))
                        for i in range(n-1)]

    ten = [[0]*(m+1)]+[[0]+list(ac(j)) for j in ten]
    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: Time Limit Exceeded

Solution code:
N,M,Q = map(int,input().split())
S = [[0]*(M+2)]+[list(map(int,"0"+input()+"0")) for _ in [0]*N] + [[0]*(M+2)]
XYXY = [list(map(int,input().split())) for _ in [0]*Q]

Root = [[-1]*(M+2) for _ in [0]*(N+2)]
Rmap =  [[0]*(M+2) for _ in [0]*(N+2)]
Elmap = [[0]*(M+2) for _ in [0]*(N+2)]
Ermap = [[0]*(M+2) for _ in [0]*(N+2)]
Eumap = [[0]*(M+2) for _ in [0]*(N+2)]
Edmap = [[0]*(M+2) for _ in [0]*(N+2)]

for i in range(1,N+2):
    for j in range(1,M+2):
        if Root[i][j] != -1: continue
        if S[i][j] == 0 : continue
        r = i*N+j
        Root[i][j] = r
        Rmap[i][j] = 1
        q = [(i,j)]
        while q:
            i1,j1 = q.pop()
            for di,dj in ((1,0),(-1,0),(0,1),(0,-1)):
                i2 = i1+di
                j2 = j1+dj
                if S[i2][j2] == 0 : continue
                if Root[i2][j2] != -1: continue
                Root[i2][j2] = r
                if di==1:
                    Eumap[i2][j2] = 1
                elif di==-1:
                    Edmap[i2][j2] = 1
                elif dj==1:
                    Elmap[i2][j2] = 1
                elif dj==-1:
                    Ermap[i2][j2] = 1
                q.append((i2,j2))

for i in range(1,N+1):
    for j in range(1,M+2):
        Elmap[i+1][j] += Elmap[i][j]
        Ermap[i+1][j] += Ermap[i][j]
        Rmap[i+1][j] += Rmap[i][j]

for i in range(1,N+2):
    for j in range(1,M+1):
        Eumap[i][j+1] += Eumap[i][j]
        Edmap[i][j+1] += Edmap[i][j]
        Rmap[i][j+1] += Rmap[i][j]

for x1,y1,x2,y2 in XYXY:
    ans = 0
    ans += Elmap[x2][y1] - Elmap[x1-1][y1]
    ans += Ermap[x2][y2] - Ermap[x1-1][y2]
    ans += Eumap[x1][y2] - Eumap[x1][y1-1]
    ans += Edmap[x2][y2] - Edmap[x2][y1-1]
    ans += Rmap[x2][y2] + Rmap[x1-1][y1-1] - Rmap[x2][y1-1] - Rmap[x1-1][y2]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import sys
    input = sys.stdin.readline

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

    numVertexss = [[0]*(M+1)] + [[0] + list(map(int, Ss)) for Ss in Sss]
    numEdgeVss = [[0]*(M+1) for _ in range(N+1)]
    numEdgeHss = [[0]*(M+1) for _ in range(N+1)]
    for i in range(1, N):
        for j in range(1, M+1):
            if numVertexss[i][j] and numVertexss[i+1][j]:
                numEdgeVss[i][j] = 1
    for i in range(1, N+1):
        for j in range(1, M):
            if numVertexss[i][j] and numVertexss[i][j+1]:
                numEdgeHss[i][j] = 1

    def getAccAss(Ass):
        for x in range(1, N+1):
            for y in range(M+1):
                Ass[x][y] += Ass[x-1][y]
        for x in range(N+1):
            for y in range(1, M+1):
                Ass[x][y] += Ass[x][y-1]
    def getRangeSum2D(accAss, xFr, xTo, yFr, yTo):
        return accAss[xTo+1][yTo+1] - accAss[xTo+1][yFr] - accAss[xFr][yTo+1] + accAss[xFr][yFr]

    getAccAss(numVertexss)
    getAccAss(numEdgeVss)
    getAccAss(numEdgeHss)

    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(numVertexss, x1, x2, y1, y2)
        ans -= getRangeSum2D(numEdgeVss, x1, x2-1, y1, y2)
        ans -= getRangeSum2D(numEdgeHss, x1, x2, y1, y2-1)
        anss.append(ans)

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


solve()

Submission status: Time Limit Exceeded

Solution code:
def solve():
    from itertools import accumulate
    from operator import add
    import sys
    input = sys.stdin.readline

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

    numVertexss = [list(map(int, Ss)) for Ss in Sss]
    numEdgeVss = [[0]*(M) for _ in range(N)]
    numEdgeHss = [[0]*(M) for _ in range(N)]
    for i in range(N-1):
        for j in range(M):
            if numVertexss[i][j] and numVertexss[i+1][j]:
                numEdgeVss[i][j] = 1
    for i in range(N):
        for j in range(M-1):
            if numVertexss[i][j] and numVertexss[i][j+1]:
                numEdgeHss[i][j] = 1

    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]

    accNumVertexss = getAccAss(numVertexss)
    accNumEdgeVss = getAccAss(numEdgeVss)
    accNumEdgeHss = getAccAss(numEdgeHss)

    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(accNumVertexss, x1, x2, y1, y2)
        ans -= getRangeSum2D(accNumEdgeVss, x1, x2-1, y1, y2)
        ans -= getRangeSum2D(accNumEdgeHss, x1, x2, y1, y2-1)
        anss.append(ans)

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


solve()

Submission status: Time 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)
del S
edges_v_cum = cumsum_mat(edges_v)
del edges_v
edges_h_cum = cumsum_mat(edges_h)
del 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: Time Limit Exceeded

Solution code:
import sys
 
stdin = sys.stdin
inf = 1 << 60
mod = 1000000007
 
ni = lambda: int(ns())
nin = lambda x: [ni() for _ in range(x)]
na = lambda: list(map(int, stdin.readline().split()))
nan = lambda x: [na() for _ in range(x)]
ns = lambda: stdin.readline().rstrip()
nsn = lambda x: [ns() for _ in range(x)]
nas = lambda: stdin.readline().split()

from collections import deque

n, m, q = na()
s = nsn(n)
xy = nan(q)

for i in range(q):
    x1, y1, x2, y2 = xy[i][1] - 1, xy[i][0] - 1, xy[i][3], xy[i][2]
    v = 0
    e = 0
    for j in range(x1, x2):
        for k in range(y1, y2):
            v += int(s[k][j])
            if j + 1 < x2 and s[k][j] == '1' and s[k][j + 1] == '1':
                e += 1
            if k + 1 < y2 and s[k][j] == '1' and s[k + 1][j] == '1':
                e += 1
    print(v - e)

Submission status: Time 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)

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 = 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: Time 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)]
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]:
            if G[i-1][j]:
                U[i][j] += 1
            if G[i][j-1]:
                L[i][j] += 1
G = [list(accumulate(k)) for k in G]
G = list(map(list, zip(*G)))
G = [list(accumulate(k)) for k in G]
G = list(map(list, zip(*G)))
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]
    g = G[x1-1][y1-1] + G[x2][y2] - G[x1-1][y2] - G[x2][y1-1]
    Ans[qu] = g - u - l
print('\n'.join(map(str, Ans)))

Submission status: Time 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

    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

    #exit()

    #Ans = []
    #for x1, y1, x2, y2 in XYXY:
    for _ in range(Q):
        x1, y1, x2, y2 = map(int, input().split())
        ans = 0
        ans += M[x2-1][y2-1] + M[x1-2][y1-2] - M[x2-1][y1-2] - M[x1-2][y2-1]
        #print(ans)
        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(str(int(ans//2)))
    #print("\n".join(map(str, Ans)))

main()

Submission status: Time 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)
    L = np.zeros((H + 1, W + 1), dtype=np.int32)
    R = np.zeros((H + 1, W + 1), dtype=np.int32)
    U = np.zeros((H + 1, W + 1), dtype=np.int32)
    D = np.zeros((H + 1, W + 1), dtype=np.int32)

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

    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

    #Ans = []
    #for x1, y1, x2, y2 in XYXY:
    for _ in range(Q):
        x1, y1, x2, y2 = map(int, input().split())
        ans = 0
        ans += M[x2-1][y2-1] + M[x1-2][y1-2] - M[x2-1][y1-2] - M[x1-2][y2-1]
        #print(ans)
        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(str(ans//2))
    #print("\n".join(map(str, Ans)))

main()

Submission status: Time 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)]
    M = np.zeros((H + 1, W + 1), dtype=np.int32)
    L = np.zeros((H + 1, W + 1), dtype=np.int32)
    R = np.zeros((H + 1, W + 1), dtype=np.int32)
    U = np.zeros((H + 1, W + 1), dtype=np.int32)
    D = np.zeros((H + 1, W + 1), dtype=np.int32)

    for x, s in enumerate(S):
        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
                M[x, y] = m
                L[x, y] = l
                R[x, y] = r
                U[x, y] = u
                D[x, y] = d

    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

    #Ans = []
    #for x1, y1, x2, y2 in XYXY:
    for _ in range(Q):
        x1, y1, x2, y2 = map(int, input().split())
        ans = 0
        ans += M[x2-1][y2-1] + M[x1-2][y1-2] - M[x2-1][y1-2] - M[x1-2][y2-1]
        #print(ans)
        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(str(ans//2))
    #print("\n".join(map(str, Ans)))

main()

Submission status: Time 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:
    for _ in range(Q):
        x1, y1, x2, y2 = map(int, input().split())
        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(ans//2)
    #print("\n".join(map(str, Ans)))

main()

Submission status: Time 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]
    
    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
        print(ans // 2)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]

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

block = [[0 for _ in range(m+1)] for _ in range(n+1)]
for i in range(1, n+1):
	for j in range(1, m+1):
		block[i][j] = block[i][j-1] + block[i-1][j] - block[i-1][j-1] + int(s[i][j])

def block_num(x1, y1, x2, y2):
	return block[x2][y2] - block[x1-1][y2] - block[x2][y1-1] + block[x1-1][y1-1]

edge_h = [[0 for _ in range(m)] for _ in range(n+1)]
edge_v = [[0 for _ in range(m+1)] for _ in range(n)]

for i in range(1, n+1):
	for j in range(1, m):
		edge_h[i][j] = edge_h[i][j-1] + edge_h[i-1][j] - edge_h[i-1][j-1] + (int(s[i][j]) + int(s[i][j+1]) == 2)

for i in range(1, n):
	for j in range(1, m+1):
		edge_v[i][j] = edge_v[i][j-1] + edge_v[i-1][j] - edge_v[i-1][j-1] + (int(s[i][j]) + int(s[i+1][j]) == 2)

def edge_num(x1, y1, x2, y2):
	h = edge_h[x2][y2-1] - edge_h[x1-1][y2-1] - edge_h[x2][y1-1] + edge_h[x1-1][y1-1]
	v = edge_v[x2-1][y2] - edge_v[x1-1][y2] - edge_v[x2-1][y1-1] + edge_v[x1-1][y1-1]
	return h+v

for _ in range(q):
	x1, y1, x2, y2 = map(int, input().split())
	b = block_num(x1, y1, x2, y2)
	e = edge_num(x1, y1, x2, y2)
	print(b-e)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
(n, m, q) = list(map(int, input().split()))
mapa = [[0 for _ in range(m + 1)]] + [[0] + list(map(int, list(input()))) for _ in range(n)]
mapa = np.array(mapa)
mapa_h = np.cumsum(np.cumsum(mapa[:n,:] * mapa[1:,:], axis=0), axis=1)
mapa_w = np.cumsum(np.cumsum(mapa[:,:m] * mapa[:, 1:], axis=0), axis=1)
mapa = np.cumsum(np.cumsum(mapa, axis=0), axis=1)

for _ in range(q):
    (x1, y1, x2, y2) = list(map(int, input().split()))
    count = mapa[x2][y2] - mapa[x1 - 1][y2] - mapa[x2][y1 - 1] + mapa[x1 - 1][y1 - 1]
    count -= mapa_h[x2-1][y2] - mapa_h[x1-1][y2] - mapa_h[x2-1][y1-1] + mapa_h[x1-1][y1-1]
    count -= mapa_w[x2][y2-1] - mapa_w[x1-1][y2-1] - mapa_w[x2][y1-1] + mapa_w[x1-1][y1-1]
    print(count)

Submission status: Time Limit Exceeded

Solution code:
import sys
n, m, q=map(int, raw_input().split())
sys.setrecursionlimit(n*m+1000)
s=["0"*(m+2)]+["0"+raw_input()+"0" for i in range(n)]+["0"*(m+2)]
vertex_cnt=[[0]*(m+2) for i in range(n+2)]
x_edge_cnt=[[0]*(m+2) for i in range(n+2)]
y_edge_cnt=[[0]*(m+2) for i in range(n+2)]
def dfs(cur_x, cur_y):
	vertex_cnt[cur_x][cur_y]=1
	for delta_x, delta_y, in ((-1, 0), (1, 0), (0, -1), (0, 1)):
		next_x, next_y=cur_x+delta_x, cur_y+delta_y
		if not vertex_cnt[next_x][next_y] and s[next_x][next_y]=="1":
			#dfs(next_x, next_y)
			if delta_x:
				x_edge_cnt[max(cur_x, next_x)][cur_y]+=1
			else:
				y_edge_cnt[cur_x][max(cur_y, next_y)]+=1
for i in range(n+2):
	for j in range(m+2):
		if s[i][j]=="1" and not vertex_cnt[i][j]:
			dfs(i, j)
for i in range(n+2):
	for j in range(1, m+2):
		vertex_cnt[i][j]+=vertex_cnt[i][j-1]
		x_edge_cnt[i][j]+=x_edge_cnt[i][j-1]
		y_edge_cnt[i][j]+=y_edge_cnt[i][j-1]
for i in range(1, n+2):
	for j in range(0, m+2):
		vertex_cnt[i][j]+=vertex_cnt[i-1][j]
		x_edge_cnt[i][j]+=x_edge_cnt[i-1][j]
		y_edge_cnt[i][j]+=y_edge_cnt[i-1][j]
for i in range(q):
	x1, y1, x2, y2=map(int, raw_input().split())
	vertex_result=vertex_cnt[x2][y2]+vertex_cnt[x1-1][y1-1]-vertex_cnt[x2][y1-1]-vertex_cnt[x1-1][y2]
	x_edge_result=x_edge_cnt[x2][y2]+x_edge_cnt[x1][y1-1]-x_edge_cnt[x2][y1-1]-x_edge_cnt[x1][y2]
	y_edge_result=y_edge_cnt[x2][y2]+y_edge_cnt[x1-1][y1]-y_edge_cnt[x2][y1]-y_edge_cnt[x1-1][y2]
	#print vertex_result, x_edge_result, y_edge_result
	print vertex_result-x_edge_result-y_edge_result

Submission status: Time Limit Exceeded

Solution code:
import sys
n, m, q=map(int, raw_input().split())
sys.setrecursionlimit(n*m+1000)
s=["0"*(m+2)]+["0"+raw_input()+"0" for i in range(n)]+["0"*(m+2)]
vertex_cnt=[[0]*(m+2) for i in range(n+2)]
x_edge_cnt=[[0]*(m+2) for i in range(n+2)]
y_edge_cnt=[[0]*(m+2) for i in range(n+2)]
def dfs(cur_x, cur_y):
	vertex_cnt[cur_x][cur_y]=1
	for delta_x, delta_y, in ((-1, 0), (1, 0), (0, -1), (0, 1)):
		next_x, next_y=cur_x+delta_x, cur_y+delta_y
		if not vertex_cnt[next_x][next_y] and s[next_x][next_y]=="1":
			dfs(next_x, next_y)
			if delta_x:
				x_edge_cnt[max(cur_x, next_x)][cur_y]+=1
			else:
				y_edge_cnt[cur_x][max(cur_y, next_y)]+=1
for i in range(n+2):
	for j in range(m+2):
		if s[i][j]=="1" and not vertex_cnt[i][j]:
			dfs(i, j)
for i in range(n+2):
	for j in range(1, m+2):
		vertex_cnt[i][j]+=vertex_cnt[i][j-1]
		x_edge_cnt[i][j]+=x_edge_cnt[i][j-1]
		y_edge_cnt[i][j]+=y_edge_cnt[i][j-1]
for i in range(1, n+2):
	for j in range(0, m+2):
		vertex_cnt[i][j]+=vertex_cnt[i-1][j]
		x_edge_cnt[i][j]+=x_edge_cnt[i-1][j]
		y_edge_cnt[i][j]+=y_edge_cnt[i-1][j]
for i in range(q):
	x1, y1, x2, y2=map(int, raw_input().split())
	vertex_result=vertex_cnt[x2][y2]+vertex_cnt[x1-1][y1-1]-vertex_cnt[x2][y1-1]-vertex_cnt[x1-1][y2]
	x_edge_result=x_edge_cnt[x2][y2]+x_edge_cnt[x1][y1-1]-x_edge_cnt[x2][y1-1]-x_edge_cnt[x1][y2]
	y_edge_result=y_edge_cnt[x2][y2]+y_edge_cnt[x1-1][y1]-y_edge_cnt[x2][y1]-y_edge_cnt[x1-1][y2]
	#print vertex_result, x_edge_result, y_edge_result
	print vertex_result-x_edge_result-y_edge_result

Submission status: Time Limit Exceeded

Solution code:
import sys
n, m, q=map(int, raw_input().split())
sys.setrecursionlimit(n*m+1000)
s=["0"*(m+2)]+["0"+raw_input()+"0" for i in range(n)]+["0"*(m+2)]
visited=[[False]*(m+2) for i in range(n+2)]
cnt=[[0]*(m+2) for i in range(n+2)]
father=[[(-1, -1)]*(m+2) for i in range(n+2)]
def dfs(cur_x, cur_y):
	visited[cur_x][cur_y]=True
	for delta_x, delta_y in ((-1, 0), (1, 0), (0, -1), (0, 1)):
		next_x, next_y=cur_x+delta_x, cur_y+delta_y
		if not visited[next_x][next_y] and s[next_x][next_y]=="1":
			dfs(next_x, next_y)
			father[next_x][next_y]=(cur_x, cur_y)
for i in range(n+2):
	for j in range(m+2):
		if s[i][j]=="1" and not visited[i][j]:
			cnt[i][j]+=1
			dfs(i, j)
for i in range(n+2):
	for j in range(1, m+2):
		cnt[i][j]+=cnt[i][j-1]
for i in range(1, n+2):
	for j in range(0, m+2):
		cnt[i][j]+=cnt[i-1][j]
for i in range(q):
	x1, y1, x2, y2=map(int, raw_input().split())
	result=cnt[x2][y2]+cnt[x1-1][y1-1]-cnt[x2][y1-1]-cnt[x1-1][y2]
	#print result,
	for i in range(x1, x2+1):
		if father[i][y1]==(i, y1-1):
			result+=1
		if father[i][y2]==(i, y2+1):
			result+=1
	for i in range(y1, y2+1):
		if father[x1][i]==(x1-1, i):
			result+=1
		if father[x2][i]==(x2+1, i):
			result+=1
	print result

Submission status: Time Limit Exceeded

Solution code:
N,M,Q = map(int,input().split())
src = [input() for i in range(N)]
qs = [tuple(map(int,input().split())) for i in range(Q)]

blue_cum = [[0 for j in range(M+1)] for i in range(N+1)]
for i in range(N):
    for j in range(M):
        blue_cum[i+1][j+1] += blue_cum[i+1][j] + int(src[i][j])
for i in range(N):
    for j in range(M+1):
        blue_cum[i+1][j] += blue_cum[i][j]

h_edge = [[0 for j in range(M)] for i in range(N+1)]
for i in range(N):
    for j in range(M-1):
        h_edge[i+1][j+1] += h_edge[i+1][j] + int(src[i][j:j+2]=='11')
for i in range(N):
    for j in range(M):
        h_edge[i+1][j] += h_edge[i][j]

v_edge = [[0 for j in range(M+1)] for i in range(N)]
for i in range(N-1):
    for j in range(M):
        v_edge[i+1][j+1] += v_edge[i+1][j] + int(src[i][j]=='1' and src[i+1][j]=='1')
for i in range(N-1):
    for j in range(M+1):
        v_edge[i+1][j] += v_edge[i][j]

ans = []
for y1,x1,y2,x2 in qs:
    y1 -= 1
    x1 -= 1
    blue = blue_cum[y1][x1] - blue_cum[y1][x2] - blue_cum[y2][x1] + blue_cum[y2][x2]
    edge = h_edge[y1][x1] - h_edge[y1][x2-1] - h_edge[y2][x1] + h_edge[y2][x2-1]
    edge+= v_edge[y1][x1] - v_edge[y1][x2] - v_edge[y2-1][x1] + v_edge[y2-1][x2]
    ans.append(blue - edge)
print(*ans, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
n,m,q= list(map(int, input().split()))
fie = []
for i in range(n):
    fie.append(list(map(int, input())))
ques = [[int(i) for i in input().split()] for i in range(q)]
k=0
while k<q:
    x1=ques[k][0]
    x2=ques[k][2]
    y1=ques[k][1]
    y2=ques[k][3]
    i=0
    j=0
    while y1<=y2:
        while x1<=x2:
            if fie[x1-1][y1-1]==1:
                i+=1
                if x1+1<=x2 and fie[x1][y1-1]==1:
                    j+=1
                if y1+1<=y2 and fie[x1-1][y1]==1:
                    j+=1
            x1+=1
        y1+=1
        x1=ques[k][0]
    print(i-j)
    k+=1