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: Wrong Answer

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(bool, 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] = True
        if j<m-1 and s[i][j]==s[i][j+1]==1:
            e2[i][j] = True
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]
    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: Wrong Answer

Solution code:
import copy

n, m, q = map(int, input().split())

s = [[0 for i in range(m+1)] for j in range(n+1)]

ans = 0
for i in range(1,n+1):
    s[i] =[0]+ [int(x) for x in input()]


acc = [[0 for i in range(m+1)] for j in range(n+1)]

for i in range(1,n+1):
    acc[i][1] += acc[i-1][1]
    if s[i-1][1]==0 and s[i][1] == 1:
        acc[i][1] += 1

for j in range(2,m+1):
    acc[1][j] += acc[1][j-1]
    if s[1][j-1]==0 and s[1][j] == 1:
        acc[1][j] += 1

for i in range(2,n+1):
    for j in range(2,m+1):
        acc[i][j] = acc[i][j-1] + acc[i-1][j]- acc[i-1][j-1]
        if s[i][j] == 1 and s[i][j-1] == s[i-1][j] == 0:
            acc[i][j]+=1
        if s[i-1][j-1] == 0 and s[i][j] == s[i][j-1] == s[i-1][j] == 1:
            acc[i][j]-=1

xyxy = [tuple(map(int,input().split())) for i in range(q)]

ans = []
for x1,y1,x2,y2 in xyxy:
    ans.append(acc[x2][y2]-acc[x1-1][y1-1] )

print(*ans,sep='\n')

Submission status: Wrong Answer

Solution code:
import copy

n, m, q = map(int, input().split())

s = [[0 for i in range(m+1)] for j in range(n+1)]

ans = 0
for i in range(1,n+1):
    s[i] =[0]+ [int(x) for x in input()]


acc = [[0 for i in range(m+1)] for j in range(n+1)]

for i in range(1,n+1):
    acc[i][1] += acc[i-1][1]
    if s[i-1][1]==0 and s[i][1] == 1:
        acc[i][1] += 1

for j in range(2,m+1):
    acc[1][j] += acc[1][j-1]
    if s[1][j-1]==0 and s[1][j] == 1:
        acc[1][j] += 1

for i in range(2,n+1):
    for j in range(2,m+1):
        acc[i][j] = acc[i][j-1] + acc[i-1][j]- acc[i-1][j-1]
        if s[i][j] == 1 and s[i][j-1] == s[i-1][j] == 0:
            acc[i][j]+=1
        if s[i-1][j-1] == 0 and s[i][j] == s[i][j-1] == s[i-1][j] == 1:
            acc[i][j]-=1

xyxy = [tuple(map(int,input().split())) for i in range(q)]

ans = []
for x1,y1,x2,y2 in xyxy:
    print(x1,y1,x2,y2)
    ans.append(acc[x2][y2]-acc[x1-1][y1-1] )

print(*ans,sep='\n')

Submission status: Wrong Answer

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.int16)
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.int16)
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

del S

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

Submission status: Wrong Answer

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

N, M, Q = map(int, input().split())
state = [[int(a) for a in list(input().rstrip())] for _ in range(N)]
Query = [list(map(int, input().split())) for _ in range(Q)]
updown = [[0]*(M+1) for _ in range(N)]
for h in range(N-1):
    st = 0
    for w in range(M):
        if state[h][w] and state[h+1][w]:
            st += 1
        updown[h+1][w+1] = st

rileft = [[0]*M for _ in range(N+1)]
for w in range(M-1):
    st = 0
    for h in range(N):
        if state[h][w] and state[h][w+1]:
            st += 1
        rileft[h+1][w+1] = st

dp = [[0]*(M+1) for _ in range(N+1)]
for h in range(N):
    have = False
    connected = 0
    for w in range(M):
        if state[h][w]:
            if not have:
                connected += 1
                have = True
        else:
            if have:
                have = False
        dp[h+1][w+1] = dp[h][w+1] + connected - updown[h][w+1]

for n1, m1, n2, m2 in Query:
    upcon = dp[n1-1][m2] - dp[n1-1][m1-1] + rileft[n1-1][m1-1]
    lecon = dp[n2][m1-1] - dp[n1-1][m1-1] + updown[n1-1][m1-1]
    ans = dp[n2][m2] - upcon  - lecon + (updown[n1-1][m2] - updown[n1-1][m1-1]) + (rileft[n2][m1-1]-rileft[n1-1][m1-1])
    print(ans)

Submission status: Wrong Answer

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(ans//2))
    #print("\n".join(map(str, Ans)))

main()

Submission status: Wrong Answer

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
    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(ans//2))
    #print("\n".join(map(str, Ans)))

main()

Submission status: Wrong Answer

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

    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(ans//2))
    #print("\n".join(map(str, Ans)))

main()

Submission status: Wrong Answer

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

    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(ans//2))
    #print("\n".join(map(str, Ans)))

main()

Submission status: Wrong Answer

Solution code:
def input_test():
    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)]
    for _ in range(Q):
        x1, y1, x2, y2 = map(int, input().split())
        
input_test()

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
import copy

n, m, q = [int(x) for x in sys.stdin.readline().split()]

def lister(n):
	s = []
	for _ in range(n):
		a = input()
		s.append(list(map(int, a)))
	return s

def normal_accumulator(s):
	for i in s:
		for j,k in enumerate(i):
			if j != 0:
				i[j] = k + i[j-1]
	for i in range(m):
		for j in range(n):
			if j != 0:
				s[j][i] += s[j-1][i]
	return s

def horizontal_accumulator(s):
	sh = []
	for i in s:
		st = []
		for j,k in enumerate(i):
			if j == 0:
				st.append(0)
			else:
				if k == 1 and i[j-1] == 1:
					st.append(st[j-1]+1)
				else:
					st.append(st[j-1])
		sh.append(st)
	for i in range(m):
			for j in range(n):
				if j != 0:
					sh[j][i] += sh[j-1][i]
	return sh

def vertical_accumulator(s):	
	sv = np.zeros((n,m),dtype=int)
	for i in range(m):
		for j in range(1,n):
			if s[j][i] == 1 and s[j-1][i] == 1:
					sv[j][i] = sv[j-1][i] + 1
	for i in sv:
		for j,k in enumerate(i):
			if j != 0:
				i[j] = k + i[j-1]
	return sv

def devider(s,x1,y1,x2,y2):
	if x1 != 1 and y1 != 1:
		return s[x1-2][y1-2] + s[x2-1][y2-1] - s[x1-2][y2-1] - s[x2-1][y1-2]
	elif x1 == 1 and y1 != 1:
		return s[x2-1][y2-1] - s[x2-1][y1-1]
	elif x1 != 1 and y1 == 1:
		return s[x2-1][y2-1] - s[x1-1][y2-1]
	else:
		return s[x2-1][y2-1]


s = lister(n)
s_copy = copy.deepcopy(s)

sa = normal_accumulator(s_copy)
sh = horizontal_accumulator(s)
sv = vertical_accumulator(s)
sc = sh + sv

for _ in range(q):
	x1,y1,x2,y2 = [int(x) for x in sys.stdin.readline().split()]
	ans = devider(sa, x1, y1, x2, y2) - devider(sc, x1, y1, x2, y2)
	print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
import copy

n, m, q = [int(x) for x in sys.stdin.readline().split()]

def lister(n):
	s = []
	for _ in range(n):
		a = input()
		s.append(list(map(int, a)))
	return s

def normal_accumulator(s):
	for i in s:
		for j,k in enumerate(i):
			if j != 0:
				i[j] = k + i[j-1]
	for i in range(m):
		for j in range(n):
			if j != 0:
				s[j][i] += s[j-1][i]
	return s

def horizontal_accumulator(s):
	sh = []
	for i in s:
		st = []
		for j,k in enumerate(i):
			if j == 0:
				st.append(0)
			else:
				if k == 1 and i[j-1] == 1:
					st.append(st[j-1]+1)
				else:
					st.append(st[j-1])
		sh.append(st)
	for i in range(m):
			for j in range(n):
				if j != 0:
					sh[j][i] += sh[j-1][i]
	return sh

def vertical_accumulator(s):	
	sv = np.zeros((n,m),dtype=int)
	for i in range(m):
		for j in range(1,n):
			if s[j][i] == 1 and s[j-1][i] == 1:
					sv[j][i] = sv[j-1][i] + 1
	for i in sv:
		for j,k in enumerate(i):
			if j != 0:
				i[j] = k + i[j-1]
	return sv

def devider(s,x1,y1,x2,y2):
	return s[x1-2][y1-2] + s[x2-1][y2-1] - s[x1-2][y2-1] - s[x2-1][y1-2]

s = lister(n)
s_copy = copy.deepcopy(s)

sa = normal_accumulator(s_copy)
sh = horizontal_accumulator(s)
sv = vertical_accumulator(s)
sc = sh + sv

for _ in range(q):
	x1,y1,x2,y2 = [int(x) for x in sys.stdin.readline().split()]
	ans = devider(sa, x1, y1, x2, y2) - devider(sc, x1, y1, x2, y2)
	print(ans)

Submission status: Wrong Answer

Solution code:
A,B=raw_input,range;n,m,q=map(int,A().split());s=[map(int,A())for _ in[0]*n]
def f(a):
 z=[[x*y for(x,y)in zip(t,u)]+[0,0]for(t,u)in zip(s,a)]+[[0]*m,[0]*m]
 def g(p):
	for i in B(n):
	 for j in B(m):z[i][j]+=z[i-p][j-1+p]
 g(1);g(0);print z;return z
a,b,c=f([[1]*m]*n),f(t[1:]for t in s),f(s[1:])
for _ in[0]*q:x,y,z,w=map(int,A().split());g=lambda d,p,q:d[x-2][y-2]+d[z-p][w-q]-d[x-2][w-q]-d[z-p][y-2];print g(a,1,1)-g(b,1,2)-g(c,2,1)

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

Solution code:
import sys

n, m, q = map(int, input().split())
sss = [input() for _ in range(n)]
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)]

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

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

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

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

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

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

Solution code:

"""

https://atcoder.jp/contests/agc015/tasks/agc015_c

2*2にマスを拡張

#.
..

青がつながってる場合、右と下につける
あとは2次元累積和

"""

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

V = [ [0] * (M*2+1) for i in range(N*2+1) ]
L = [ [0] * (M*2+1) for i in range(N*2+1) ]

S = []
for i in range(N):
    tmp = input()
    S.append(tmp)

for i in range(N):
    for j in range(M):

        if S[i][j] == "1":
            V[i*2][j*2] = 1
        if i != N-1 and S[i][j] == "1" and S[i+1][j] == "1":
            L[i*2+1][j*2] = 1
        if j != M-1 and S[i][j] == "1" and S[i][j+1] == "1":
            L[i*2][j*2+1] = 1


for i in range(2*N):
        for j in range(2*M-1):

            V[i][j+1] += V[i][j]
            L[i][j+1] += L[i][j]

for j in range(2*M):
        for i in range(2*N-1):
            V[i+1][j] += V[i][j]
            L[i+1][j] += L[i][j]



"""
for i in V:
    print (i)
print ("")
for i in L:
    print (i)
"""

for loop in range(Q):

    x1,y1,x2,y2 = map(int,input().split())
    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1

    numV = V[x2*2][y2*2] - V[x1*2-1][y2*2]+ - V[x2*2][y1*2-1] + V[x1*2-1][y1*2-1]
    numL = L[x2*2][y2*2] - L[x1*2-1][y2*2] - L[x2*2][y1*2-1] + L[x1*2-1][y1*2-1]

    print (numV - numL)

Submission status: Time 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)]
for i in range(N):
  for j in range(M - 1): e[i][j + 1] = e[i][j] + ((S[i][j] == 1) and (S[i][j + 1] == 1))
for i in range(N - 1):
  for j in range(M): e[i + 1][j] += e[i][j]
e = [[0] * M] + e


cs = [[0] * (M + 1) for _ in range(N)]
for i in range(N):
  for j in range(M): cs[i][j + 1] = cs[i][j] + (S[i][j] == 1)
for i in range(N - 1):
  for j in range(M + 1): cs[i + 1][j] += cs[i][j]
cs = [[0] * (M + 1)] + cs
#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)]
for i in range(N):
  for j in range(M - 1): e[i][j + 1] = e[i][j] + ((T[i][j] == 1) and (T[i][j + 1] == 1))
for i in range(N - 1):
  for j in range(M): e[i + 1][j] += e[i][j]
e = [[0] * M] + e
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: Time Limit Exceeded

Solution code:

"""

https://atcoder.jp/contests/agc015/tasks/agc015_c

3*3にマスを拡張
...
.#.
...

青がつながってる場合、右と下につける
あとは2次元累積和

"""

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

V = [ [0] * (M*3) for i in range(N*3) ]
L = [ [0] * (M*3) for i in range(N*3) ]

S = []
for i in range(N):
    tmp = input()
    S.append(tmp)

for i in range(N):
    for j in range(M):

        if S[i][j] == "1":
            V[i*3+1][j*3+1] = 1
        if i != N-1 and S[i][j] == "1" and S[i+1][j] == "1":
            L[i*3+2][j*3+1] = 1
        if j != M-1 and S[i][j] == "1" and S[i][j+1] == "1":
            L[i*3+1][j*3+2] = 1


for i in range(3*N):
    for j in range(3*M-1):

        V[i][j+1] += V[i][j]
        L[i][j+1] += L[i][j]

for j in range(3*M):
    for i in range(3*N-1):
        V[i+1][j] += V[i][j]
        L[i+1][j] += L[i][j]

"""
for i in V:
    print (i)
print ("")
for i in L:
    print (i)
"""

for loop in range(Q):

    x1,y1,x2,y2 = map(int,input().split())
    x1 -= 1
    y1 -= 1
    x2 -= 1
    y2 -= 1

    numV = V[x2*3+1][y2*3+1] - V[x1*3][y2*3+1] - V[x2*3+1][y1*3] + V[x1*3][y1*3]
    numL = L[x2*3+1][y2*3+1] - L[x1*3][y2*3+1] - L[x2*3+1][y1*3] + L[x1*3][y1*3]

    print (numV - numL)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def precompute(S):
    H, W = S.shape
    V = np.zeros((H + 1, W + 1), np.int32)
    V[1:, 1:] = np.cumsum(S, axis=0).cumsum(axis=1)
    Ex = np.zeros((H, W + 1), np.int32)
    Ex[1:, 1:] = np.cumsum(S[:-1] & S[1:], axis=0).cumsum(axis=1)
    Ey = np.zeros((H + 1, W), np.int32)
    Ey[1:, 1:] = np.cumsum(S[:, :-1] & S[:, 1:], axis=0).cumsum(axis=1)
    return V, Ex, Ey

def main(V, Ex, Ey, query):
    for i in range(len(query) // 4):
        a, b, c, d = query[4 * i:4 * i + 4]
        v = V[c, d] + V[a - 1, b - 1] - V[a - 1, d] - V[c, b - 1]
        e1 = Ex[c - 1, d] + Ex[a - 1, b - 1] - Ex[a - 1, d] - Ex[c - 1, b - 1]
        e2 = Ey[c, d - 1] + Ey[a - 1, b - 1] - Ey[a - 1, d - 1] - Ey[c, b - 1]
        print(v - e1 - e2)

if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    i4 = numba.from_dtype(np.int64)
    signature = (i4[:, :], i4[:, :], i4[:, :], i4[:])

    cc = CC('my_module')
    cc.export('main', signature)(main)
    cc.compile()

H, W, Q = map(int, readline().split())
S = []
for _ in range(H):
    S.append(list(readline().rstrip()))
query = np.array(read().split(), np.int32)

S = (np.concatenate(S) - ord('0')).reshape(H, W)
V, Ex, Ey = precompute(S)

main(V, Ex, Ey, query)

Submission status: Time Limit Exceeded

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

n, m, q = map(int, input().split())
S = [[0]*(m+1)] + [[0] + list(map(int, list(input().rstrip()))) for _ in range(n)]
B = [[0]*(m+1) for _ in range(n+1)]
U = [[0]*(m+1) for _ in range(n+1)]
L = [[0]*(m+1) for _ in range(n+1)]
for i in range(1, n+1):
  for j in range(1, m+1):
    if S[i][j]:
      U[i][j] = S[i-1][j]
      L[i][j] = S[i][j-1]
for i in range(1, n+1):
  B[i] = tuple(accumulate(S[i]))
  U[i] = tuple(accumulate(U[i]))
  L[i] = tuple(accumulate(L[i]))
B = list(zip(*B))
U = list(zip(*U))
L = list(zip(*L))
for j in range(1, m+1):
  B[j] = tuple(accumulate(B[j]))
  U[j] = tuple(accumulate(U[j]))
  L[j] = tuple(accumulate(L[j]))
B = tuple(zip(*B))
U = tuple(zip(*U))
L = tuple(zip(*L))
def calc_b(x1, y1, x2, y2):
  return B[x2][y2] - B[x1-1][y2] - B[x2][y1-1] + B[x1-1][y1-1]
def calc_u(x1, y1, x2, y2):
  return U[x2][y2] - U[x1][y2] - U[x2][y1-1] + U[x1][y1-1]
def calc_l(x1, y1, x2, y2):
  return L[x2][y2] - L[x1-1][y2] - L[x2][y1] + L[x1-1][y1]

for _ in range(q):
  x1, y1, x2, y2 = map(int, input().split())
  res = calc_b(x1, y1, x2, y2) - (calc_u(x1, y1, x2, y2) + calc_l(x1, y1, x2, y2))
  print(res)

Submission status: Time Limit Exceeded

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

def main():
  n, m, q = map(int, input().split())
  S = [[0]*(m+1)] + [[0] + list(map(int, list(input().rstrip()))) for _ in range(n)]
  B = [[0]*(m+1) for _ in range(n+1)]
  U = [[0]*(m+1) for _ in range(n+1)]
  L = [[0]*(m+1) for _ in range(n+1)]
  for i in range(1, n+1):
    for j in range(1, m+1):
      if S[i][j]:
        U[i][j] = S[i-1][j]
        L[i][j] = S[i][j-1]
  for i in range(1, n+1):
    B[i] = list(accumulate(S[i]))
    U[i] = list(accumulate(U[i]))
    L[i] = list(accumulate(L[i]))
  B = list(zip(*B))
  U = list(zip(*U))
  L = list(zip(*L))
  for j in range(1, m+1):
    B[j] = list(accumulate(B[j]))
    U[j] = list(accumulate(U[j]))
    L[j] = list(accumulate(L[j]))
  B = list(zip(*B))
  U = list(zip(*U))
  L = list(zip(*L))
  def calc_b(x1, y1, x2, y2):
    return B[x2][y2] - B[x1-1][y2] - B[x2][y1-1] + B[x1-1][y1-1]
  def calc_u(x1, y1, x2, y2):
    return U[x2][y2] - U[x1][y2] - U[x2][y1-1] + U[x1][y1-1]
  def calc_l(x1, y1, x2, y2):
    return L[x2][y2] - L[x1-1][y2] - L[x2][y1] + L[x1-1][y1]

  for _ in range(q):
    x1, y1, x2, y2 = map(int, input().split())
    res = calc_b(x1, y1, x2, y2) - (calc_u(x1, y1, x2, y2) + calc_l(x1, y1, x2, y2))
    print(res)
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

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

n, m, q = map(int, input().split())
S = [[0]*(m+1)] + [[0] + list(map(int, list(input().rstrip()))) for _ in range(n)]
B = [[0]*(m+1) for _ in range(n+1)]
U = [[0]*(m+1) for _ in range(n+1)]
L = [[0]*(m+1) for _ in range(n+1)]
for i in range(1, n+1):
  for j in range(1, m+1):
    if S[i][j]:
      U[i][j] = S[i-1][j]
      L[i][j] = S[i][j-1]
for i in range(1, n+1):
  B[i] = list(accumulate(S[i]))
  U[i] = list(accumulate(U[i]))
  L[i] = list(accumulate(L[i]))
B = list(zip(*B))
U = list(zip(*U))
L = list(zip(*L))
for j in range(1, m+1):
  B[j] = list(accumulate(B[j]))
  U[j] = list(accumulate(U[j]))
  L[j] = list(accumulate(L[j]))
B = list(zip(*B))
U = list(zip(*U))
L = list(zip(*L))
def calc_b(x1, y1, x2, y2):
  return B[x2][y2] - B[x1-1][y2] - B[x2][y1-1] + B[x1-1][y1-1]
def calc_u(x1, y1, x2, y2):
  return U[x2][y2] - U[x1][y2] - U[x2][y1-1] + U[x1][y1-1]
def calc_l(x1, y1, x2, y2):
  return L[x2][y2] - L[x1-1][y2] - L[x2][y1] + L[x1-1][y1]

for _ in range(q):
  x1, y1, x2, y2 = map(int, input().split())
  res = calc_b(x1, y1, x2, y2) - (calc_u(x1, y1, x2, y2) + calc_l(x1, y1, x2, y2))
  print(res)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import numpy as np
    n, m, q = map(int, input().split())
    ten = np.zeros((n+1, m+1), dtype=np.int32)
    ten[1:, 1:] = np.array([list(map(lambda x:int(x), list(input())))
                            for _ in [0]*n], dtype=np.int32)

    hen1 = np.zeros((n+1, m), dtype=np.int32)
    hen1[1:, 1:] = ten[1:, 1:m] & ten[1:, 2:]
    hen1 = np.cumsum(hen1, axis=0)
    hen1 = np.cumsum(hen1, axis=1)
    hen2 = np.zeros((n, m+1), dtype=np.int32)
    hen2[1:, 1:] = ten[1:n, 1:] & ten[2:, 1:]
    hen2 = np.cumsum(hen2, axis=0)
    hen2 = np.cumsum(hen2, axis=1)
    ten = np.cumsum(ten, axis=0)
    ten = np.cumsum(ten, axis=1)

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


main()