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: Runtime Error

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 cumsum(a):
    """l[i] = sum(a[:i]) なるlを返す
    sum(a[i:j]) == l[j+1] - l[i]
    """
    c = 0
    l = [None] * (len(a)+1)
    for i,num in enumerate(a):
        l[i] = c
        c += num
    l[-1] = c
    return l

def cumsum2(v):
    # v: h*wの2次元リスト
    h,w = len(v), len(v[0])
    ans = [[0]*(w+1) for _ in range(h+1)]
    val = [cumsum(vv) for vv in v]
    for y in range(w+1):
        tmp = cumsum([val[i][y] for i in range(h)])
        for x in range(h+1):
            ans[x][y] = tmp[x]
    return ans
c0 = cumsum2(s)
c1 = cumsum2(e1)
c2 = cumsum2(e2)
ans = [None]*q
for i in range(q):
    x1,y1,x2,y2 = map(lambda x: int(x)-1, input().split())
    val = c0[x2+1][y2+1] - c0[x1][y2+1] - c0[x2+1][y1] + c0[x1][y1]
    val2 = c1[x2][y2+1] - c1[x2][y1] - c1[x1][y2+1] + c1[x1][y1]
    val3 = c2[x2+1][y2] - c2[x2+1][y1] - c2[x1][y2] + c2[x1][y1]
    ans[i] = val - (val2+val3)
write("\n".join(map(str, ans)))

Submission status: Runtime Error

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

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

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

#print(cs)

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

Submission status: Runtime Error

Solution code:
n,m,q = map(int, input().split())
s = []
for i in range(n):
    s.append(list((1 if x == '1' else 0 for x in input().strip())))

def g(s,x,y,n):
    s[x][y] += n
    if x > 0 and s[x-1][y]==1:
        g(s,x-1,y,n)
    if x < len(s)-1 and s[x+1][y]==1:
        g(s,x+1,y,n)
    if y > 0 and s[x][y-1]==1:
        g(s,x,y-1,n)
    if y < len(s[x])-1 and s[x][y+1]==1:
        g(s,x,y+1,n)

def f(s):
    n = 1
    for x,u in enumerate(s):
        for y,v in enumerate(u):
            if v == 1:
                g(s,x,y,n)
                n += 1
    return n-1

for i in range(q):
    x1,y1,x2,y2 = map(lambda x:x-1, map(int, input().split()))
    qs = []
    for x in s[x1:x2+1]:
        qs.append(x[y1:y2+1])
    print(f(qs))

Submission status: Runtime Error

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(n):
        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 = [[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[i][j] = 1
ruiseki_w = Ruiseki2D(matrix)

matrix = [[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[i][j] = 1
ruiseki_h = Ruiseki2D(matrix)

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

Submission status: Runtime Error

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(n):
        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: Runtime Error

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

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

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


n, m, q = map(int, input().split())
s = [list(input()) for i in range(n)]
query = [list(map(int, input().split())) for i in range(q)]
for i in range(n):
    for j in range(n):
        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 = query[i]
    hl -= 1
    wl -= 1
    print(ruiseki.get_sum(hl, hr, wl, wr) - ruiseki_w.get_sum(hl, hr, wl, wr - 1) - ruiseki_h.get_sum(hl, hr - 1, wl, wr))

Submission status: Runtime Error

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
    del S

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

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

main()

Submission status: Runtime Error

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

from itertools import accumulate
from operator import add

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

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

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

    accAss = getAccAss(Ass)
    accNumXss = getAccAss(numXss)
    accNumYss = getAccAss(numYss)

    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(accAss, x1, x2, y1, y2)
        ans -= getRangeSum2D(accNumXss, x1, x2-1, y1, y2)
        ans -= getRangeSum2D(accNumYss, x1, x2, y1, y2-1)
        anss.append(ans)

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

solve()

Submission status: Runtime Error

Solution code:
#include <iostream>

using namespace std;
#define REP(i,n) for (int i = 0; i < n; ++i)
#define FOR(i,m,n) for (int i = m; i < n; ++i)

const int MAX = 2222;

int N, M, Q;
int grid[MAX][MAX], cumulative[MAX][MAX];
int hedge[MAX][MAX], vedge[MAX][MAX];

int main() {
    cin >> N >> M >> Q;
    REP(n, N) {
        string s;
        cin >> s;
        REP (m, M) grid[n+1][m+1] = s[m] == '1';
    }

    FOR (n, 1, N+1) FOR (m, 1, M) if (grid[n][m] == 1 && grid[n][m+1] == 1) hedge[n][m+1] = 1;
    FOR (m, 1, M+1) FOR (n, 1, N) if (grid[n][m] == 1 && grid[n+1][m] == 1) vedge[n+1][m] = 1;
    FOR (n, 1, N+1) FOR (m, 1, M+1) {
        grid[n][m+1] += grid[n][m];
        hedge[n][m+1] += hedge[n][m];
        vedge[n][m+1] += vedge[n][m];
    }
    FOR (n, 1, N+1) FOR (m, 1, M+1) {
        grid[n+1][m] += grid[n][m];
        hedge[n+1][m] += hedge[n][m];
        vedge[n+1][m] += vedge[n][m];
    }


    REP (q, Q) {
        int x, y, xx, yy;
        cin >> x >> y >> xx >> yy;
        int node = grid[xx][yy] - grid[xx][y-1] - grid[x-1][yy] + grid[x-1][y-1];
        int ve = vedge[xx][yy] - vedge[xx][y-1] - vedge[x][yy] + vedge[x][y-1];
        int he = hedge[xx][yy] - hedge[xx][y] - hedge[x-1][yy] + hedge[x-1][y];
        cout << node-ve-he << endl;
    }     
}

Submission status: Runtime Error

Solution code:
n, m, q=map(int, raw_input().split())
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: Runtime Error

Solution code:
import fileinput

iterator = fileinput.input()


n, m, q = map(int, iterator.next().split())
board = [list(iterator.next()) for _ in range(n)]


def flood_fill(visited, i, j, ai, bi, aj, bj):
    if i < ai or i > aj or j < bi or j > bj:
        return
    if board[i][j] != '1' or (i,j) in visited:
        return

    visited[(i,j)] = True

    flood_fill(visited, i+1, j, ai, bi, aj, bj)
    flood_fill(visited, i, j+1, ai, bi, aj, bj)
    flood_fill(visited, i-1, j, ai, bi, aj, bj)
    flood_fill(visited, i, j-1, ai, bi, aj, bj)


for _ in range(q):
    query = iterator.next()
    ai, bi, aj, bj = map(int, query.split())
    ai, bi, aj, bj = ai-1, bi-1, aj-1, bj-1
    visited = {}
    comp = 0
    for i in range(ai, aj+1):
        for j in range(bi, bj+1):
            if board[i][j] == '1' and (i,j) not in visited:
                comp += 1
            flood_fill(visited, i, j, ai, bi, aj, bj)
    print comp

Submission status: Runtime Error

Solution code:
import fileinput

data = list(fileinput.input())

n, m, q = map(int, data[0].split())
board = map(lambda x: list(x), data[1:1+n])


def flood_fill(visited, i, j, ai, bi, aj, bj):
    if i < ai or i > aj or j < bi or j > bj:
        return
    if board[i][j] != '1' or (i,j) in visited:
        return

    visited[(i,j)] = True

    flood_fill(visited, i+1, j, ai, bi, aj, bj)
    flood_fill(visited, i, j+1, ai, bi, aj, bj)
    flood_fill(visited, i-1, j, ai, bi, aj, bj)
    flood_fill(visited, i, j-1, ai, bi, aj, bj)


for query in data[1+n:]:
    visited = {}
    ai, bi, aj, bj = map(int, query.split())
    ai, bi, aj, bj = ai-1, bi-1, aj-1, bj-1
    comp = 0
    for i in range(ai, aj+1):
        for j in range(bi, bj+1):
            if board[i][j] == '1' and (i,j) not in visited:
                comp += 1
            flood_fill(visited, i, j, ai, bi, aj, bj)
    print comp

Submission status: Runtime Error

Solution code:
import fileinput
from copy import deepcopy

data = list(fileinput.input())

n, m, q = map(int, data[0].split())
board = map(lambda x: list(x), data[1:1+n])
queries = map(lambda x: x.split(), data[1+n:])


def flood_fill(board, i, j, ai, bi, aj, bj):
    if i < ai or i > aj or j < bi or j > bj:
        return
    if board[i][j] != '1':
        return

    board[i][j] = '2'

    flood_fill(board, i+1, j, ai, bi, aj, bj)
    flood_fill(board, i, j+1, ai, bi, aj, bj)
    flood_fill(board, i-1, j, ai, bi, aj, bj)
    flood_fill(board, i, j-1, ai, bi, aj, bj)


def print_board(board):
    for row in board:
        print row


for query in queries:
    _board = deepcopy(board)
    ai, bi, aj, bj = map(int, query)
    ai, bi, aj, bj = ai-1, bi-1, aj-1, bj-1
    comp = 0
    for i in range(ai, aj+1):
        for j in range(bi, bj+1):
            if _board[i][j] == '1':
                comp += 1
            flood_fill(_board, i, j, ai, bi, aj, bj)
    print comp

Submission status: Runtime Error

Solution code:
import sys
import numpy as np
import copy

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

aaa = []

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 = i
	ans = devider(sa, x1, y1, x2, y2) - devider(sc, x1, y1, x2, y2)
	aaa.append(ans)

for i in aaa:
	print(i)

Submission status: Runtime Error

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-1][y1-1] + s[x2][y2] - s[x1-1][y2] - s[x2][y1-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: Runtime Error

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(2*n-1, 2): # 0,1,2
        for j in range(2*m-3, 2): # 0,1,2(,3)
            grid[i][j+1] = grid[i][j]*grid[i][j+2]*(-1)

    for j in range(2*m-1, 2):
        for i in range(2*n-3, 2):
            grid[i+1][j] = grid[i][j]*grid[i+2][j]*(-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: Runtime Error

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]
    
    N_nodes - N_edges1 - N_edges2

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

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from collections import Counter
from string import ascii_lowercase

r_map = []  # check
questions = []
result = ""

N, M, Q = [int(n) for n in input().split()]
for n_ in range(N):
    r_map.append([int(n) for n in list(input())])

for q in range(Q):
    questions.append([int(n) for n in input().split()])

for q in questions:
    H = q[2] - q[0] + 1
    W = q[3] - q[1] + 1 
    g_map = [[n for n in range(m*W,W*(m+1))] for m in range(H)]
    g_map0 = deepcopy(g_map)
    X = [n+q[0]-1 for n in range(W)]
    Y = [n+q[1]-1 for n in range(H)]
    for h in range(H):
        for w in range(W):
            if w < W-1:
                if r_map[Y[h]][X[w]] == r_map[Y[h]][X[w]+1] == 1:
                    g_map[h][w+1], g_map[h][w] = min(g_map[h][w+1], g_map[h][w]), min(g_map[h][w+1], g_map[h][w])
            if w > 0:
                if r_map[Y[h]][X[w]] == r_map[Y[h]][X[w]-1] == 1:
                    g_map[h][w-1], g_map[h][w] = min(g_map[h][w-1], g_map[h][w]), min(g_map[h][w-1], g_map[h][w])
            if h < H-1:
                if r_map[Y[h+1]][X[w]] == r_map[Y[h]+1][X[w]] == 1:
                    g_map[h+1][w], g_map[h][w] = min(g_map[h+1][w], g_map[h][w]), min(g_map[h+1][w], g_map[h][w])
            if h > 0:
                if r_map[Y[h]][X[w]] == r_map[Y[h]-1][X[w]] == 1:
                    g_map[h-1][w], g_map[h][w] = min(g_map[h-1][w], g_map[h][w]), min(g_map[h-1][w], g_map[h][w])
            if r_map[Y[h]][X[w]] == 0:
                g_map[h][w] = -1
    res = set()
    for g in g_map:
        res.update(g)
    if -1 in res:
        result += "{}\n".format(len(res)-1)
    else:
        result += "{}\n".format(len(res))
print(result[:-1])

Submission status: Runtime Error

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

dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def step(x, y, id, ids, xmin, xmax, ymin, ymax):
    ids[y - ymin][x - xmin] = id
    for d in dirs:
        next_x = x + d[0]
        next_y = y + d[1]
        if next_x < xmin or next_x > xmax:
            continue
        if next_y < ymin or next_y > ymax:
            continue
        if grid[next_y][next_x] == 0:
            continue
        if ids[next_y - ymin][next_x - xmin] != 0:
            continue
        step(next_x, next_y, id, ids, xmin, xmax, ymin, ymax)

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

for _ in range(Q):
    cids = []
    x1, y1, x2, y2 = map(int, input().split())
    ids = [[0 for _ in range(y2 - y1 + 1)] for _ in range(x2 - x1 + 1)]
    sid = 1
    for ix in range(0, x2 - x1 + 1):
        for iy in range(0, y2 - y1 + 1):
            x = x1 + ix - 1
            y = y1 + iy - 1
            if ids[ix][iy] == 0 and grid[x][y] == 1:
                step(y, x, sid, ids, y1 - 1, y2 - 1, x1 - 1, x2 - 1)
                sid += 1

    print(sid - 1)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from collections import Counter
from string import ascii_lowercase

r_map = []  # check
questions = []
result = ""

N, M, Q = [int(n) for n in input().split()]
for n_ in range(N):
    r_map.append([int(n) for n in list(input())])

for q in range(Q):
    questions.append([int(n) for n in input().split()])

for q in questions[0]:
    H = q[2] - q[0] + 1
    W = q[3] - q[1] + 1 
    g_map = [[n for n in range(m*W,W*(m+1))] for m in range(H)]
    g_map0 = deepcopy(g_map)
    X = [n+q[0]-1 for n in range(W)]
    Y = [n+q[1]-1 for n in range(H)]
    for h in range(H):
        for w in range(W):
            if w < W-1:
                if r_map[Y[h]][X[w]] == r_map[Y[h]][X[w]+1] == 1:
                    g_map[h][w+1], g_map[h][w] = min(g_map[h][w+1], g_map[h][w]), min(g_map[h][w+1], g_map[h][w])
            if w > 0:
                if r_map[Y[h]][X[w]] == r_map[Y[h]][X[w]-1] == 1:
                    g_map[h][w-1], g_map[h][w] = min(g_map[h][w-1], g_map[h][w]), min(g_map[h][w-1], g_map[h][w])
            if h < H-1:
                if r_map[Y[h+1]][X[w]] == r_map[Y[h]+1][X[w]] == 1:
                    g_map[h+1][w], g_map[h][w] = min(g_map[h+1][w], g_map[h][w]), min(g_map[h+1][w], g_map[h][w])
            if h > 0:
                if r_map[Y[h]][X[w]] == r_map[Y[h]-1][X[w]] == 1:
                    g_map[h-1][w], g_map[h][w] = min(g_map[h-1][w], g_map[h][w]), min(g_map[h-1][w], g_map[h][w])
            if r_map[Y[h]][X[w]] == 0:
                g_map[h][w] = -1
    res = set()
    for g in g_map:
        res.update(g)
    if -1 in res:
        result += "{}\n".format(len(res)-1)
    else:
        result += "{}\n".format(len(res))
print(result[:-1])

Submission status: Runtime Error

Solution code:

# -*- coding: utf-8 -*-
from collections import Counter
from string import ascii_lowercase

r_map = []  # check
questions = []
result = ""

N, M, Q = [int(n) for n in input().split()]
for n_ in range(N):
    r_map.append([int(n) for n in list(input())])

for q in range(Q):
    questions.append([int(n) for n in input().split()])

for q in questions[0:1]:
    H = q[2] - q[0] + 1
    W = q[3] - q[1] + 1 
    g_map = [[n for n in range(m*W,W*(m+1))] for m in range(H)]
    g_map0 = deepcopy(g_map)
    X = [n+q[0]-1 for n in range(W)]
    Y = [n+q[1]-1 for n in range(H)]
    for h in range(H):
        for w in range(W):
            if w < W-1:
                if r_map[Y[h]][X[w]] == r_map[Y[h]][X[w]+1] == 1:
                    g_map[h][w+1], g_map[h][w] = min(g_map[h][w+1], g_map[h][w]), min(g_map[h][w+1], g_map[h][w])
            if w > 0:
                if r_map[Y[h]][X[w]] == r_map[Y[h]][X[w]-1] == 1:
                    g_map[h][w-1], g_map[h][w] = min(g_map[h][w-1], g_map[h][w]), min(g_map[h][w-1], g_map[h][w])
            if h < H-1:
                if r_map[Y[h+1]][X[w]] == r_map[Y[h]+1][X[w]] == 1:
                    g_map[h+1][w], g_map[h][w] = min(g_map[h+1][w], g_map[h][w]), min(g_map[h+1][w], g_map[h][w])
            if h > 0:
                if r_map[Y[h]][X[w]] == r_map[Y[h]-1][X[w]] == 1:
                    g_map[h-1][w], g_map[h][w] = min(g_map[h-1][w], g_map[h][w]), min(g_map[h-1][w], g_map[h][w])
            if r_map[Y[h]][X[w]] == 0:
                g_map[h][w] = -1
    res = set()
    for g in g_map:
        res.update(g)
    if -1 in res:
        result += "{}\n".format(len(res)-1)
    else:
        result += "{}\n".format(len(res))
print(result[:-1])

Submission status: Runtime Error

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

direction = [(1, 0), (0, 1), (0, -1), (-1, 0)]
grid = []
checked = []
n = N
m = M

def search(x, y):
  for d in direction:
    i = x + d[0]
    j = y + d[1]
    if i < 0 or j < 0 or i >= n or j >= m:
      continue
    if not((i, j) in checked):
      checked.append((i, j))
      if grid[i][j] == "1":
        search(i, j)

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

for i in range(Q):
  checked = []
  result = 0
  x1, y1, x2, y2 = list(map(int, input().split()))
  n = x2
  m = y2
  for j in range(x1 - 1, x2):
    for k in range(y1 - 1, y2):
      if not((j, k) in checked):
        checked.append((j, k))
        if grid[j][k] == "1":
          result += 1
          search(j, k)
  print(result)

Submission status: Runtime Error

Solution code:
import numpy as np

def search(xt, yt, a):
	if a[xt, yt] == '1':
		a[xt, yt] = '2'
		search(xt - 1, yt, a)
		search(xt + 1, yt, a)
		search(xt, yt - 1, a)
		search(xt, yt + 1, a)

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

arr = []

for i in range(n):
	s = raw_input()
	arr.append(list(s))

arr_np = np.array(arr)

for i in range(q):
	y1, x1, y2, x2 = map(int, raw_input().split())
	arr_temp = arr_np[y1 - 1:y2, x1 - 1:x2]

	a = np.array(['0'] * (x2 - x1 + 1))
	arr_temp = np.vstack((a, arr_temp))
	arr_temp = np.vstack((arr_temp, a))

	b = np.array(['0'] * (y2 - y1 + 3))
	arr_temp = np.column_stack([b, arr_temp])
	arr_temp = np.column_stack([arr_temp, b])

	p = np.where(arr_temp == '1')
	s = 0
	while len(p[0]) >= 1:
		search(p[0][0], p[1][0], arr_temp)
		s += 1
		p = np.where(arr_temp == '1')

	print s