Problem:


Score : 700 points

Problem Statement

Nuske has a grid with N rows and M columns of squares. The rows are numbered 1 through N from top to bottom, and the columns are numbered 1 through M from left to right.
Each square in the grid is painted in either blue or white. If S_{i,j} is 1, the square at the i-th row and j-th column is blue; if S_{i,j} is 0, the square is white.
For every pair of two blue square a and b, there is at most one path that starts from a, repeatedly proceeds to an adjacent (side by side) blue square and finally reaches b, without traversing the same square more than once.

Phantom Thnook, Nuske's eternal rival, gives Q queries to Nuske. The i-th query consists of four integers x_{i,1}, y_{i,1}, x_{i,2} and y_{i,2} and asks him the following: when the rectangular region of the grid bounded by (and including) the x_{i,1}-th row, x_{i,2}-th row, y_{i,1}-th column and y_{i,2}-th column is cut out, how many connected components consisting of blue squares there are in the region?

Process all the queries.

Constraints

1 ≤ N,M ≤ 2000

1 ≤ Q ≤ 200000

S_{i,j} is either 0 or 1.

S_{i,j} satisfies the condition explained in the statement.

1 ≤ x_{i,1} ≤ x_{i,2} ≤ N(1 ≤ i ≤ Q)

1 ≤ y_{i,1} ≤ y_{i,2} ≤ M(1 ≤ i ≤ Q)

Input

The input is given from Standard Input in the following format:

N M Q
S_{1,1}..S_{1,M}
:
S_{N,1}..S_{N,M}
x_{1,1} y_{i,1} x_{i,2} y_{i,2}
:
x_{Q,1} y_{Q,1} x_{Q,2} y_{Q,2}

Output

For each query, print the number of the connected components consisting of blue squares in the region.

Sample Input 1

3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4

Sample Output 1

3
2
2
2

In the first query, the whole grid is specified. There are three components consisting of blue squares, and thus 3 should be printed.

In the second query, the region within the red frame is specified. There are two components consisting of blue squares, and thus 2 should be printed.
Note that squares that belong to the same component in the original grid may belong to different components.

Sample Input 2

5 5 6
11010
01110
10101
11101
01010
1 1 5 5
1 2 4 5
2 3 3 4
3 3 3 3
3 1 3 5
1 1 3 4

Sample Output 2

3
2
1
1
3
2



Sample input:
3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4


Sample output:
3
2
2
2

Submission status: Time Limit Exceeded

Solution code:
import fileinput

iterator = fileinput.input()


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

# INIT
h_crossing_edges = [[0]*(m+1) for _ in range(n+1)]
v_crossing_edges = [[0]*(n+1) for _ in range(m+1)]
lr_comp = [[0]*(m+1) for _ in range(n+1)]

for a in range(1, n):
    for b in range(m-1, -1, -1):
        has_crossing_edge = board[a][b] == '1' and board[a-1][b] == '1'
        h_crossing_edges[a][b] = h_crossing_edges[a][b+1] + (1 if has_crossing_edge else 0)

for b in range(1, m):
    for a in range(n-1, -1, -1):
        has_crossing_edge = board[a][b] == '1' and board[a][b-1] == '1'
        v_crossing_edges[b][a] = v_crossing_edges[b][a+1] + (1 if has_crossing_edge else 0)

def lr_crossings(ai, bi, aj, bj):
    h = h_crossing_edges[aj][bi] - h_crossing_edges[aj][bj]
    v = v_crossing_edges[bj][ai] - v_crossing_edges[bj][aj]
    return h + v

def components(ai, bi, aj, bj):
    t = lr_comp[ai][bi]
    bc = lr_comp[ai][bj]
    c = lr_comp[aj][bj]
    ac = lr_comp[aj][bi]
    return t + c - bc - ac + lr_crossings(ai, bi, aj, bj)

for i in range(n-1, -1, -1):
    for j in range(m-1, -1, -1):
        comp_without_upper_left_square = (
            components(i+1, j, n, m) + components(i, j+1, i+1, m) - h_crossing_edges[i+1][j+1])
        upper_left_square = int(board[i][j])
        lr_comp[i][j] = upper_left_square + comp_without_upper_left_square - lr_crossings(i, j, i+1, j+1)

for _ in range(q):
    query = iterator.next()
    ai, bi, aj, bj = map(int, query.split())
    print components(ai-1, bi-1, aj, bj)

Submission status: Time Limit Exceeded

Solution code:
N, M, Q = map(int,raw_input().split())
S = list()
for c in range(N):
	line = map(int,list(raw_input()))
	S.append(line)
x = list()
for c in range(Q):
	line = map(int,raw_input().split())
	x.append(line)

for q in range(Q):
 	blueSquare = 0
	blueLine = 0
	for i in range(x[q][0]-1,x[q][2]):
		for j in range(x[q][1]-1,x[q][3]):
			if S[i][j]==1:
				blueSquare += 1
				if i > x[q][0]-1 and S[i-1][j]==1: blueLine += 1
				if i < x[q][2]-1 and S[i+1][j]==1: blueLine += 1
				if j > x[q][1]-1 and S[i][j-1]==1: blueLine += 1
				if j < x[q][3]-1 and S[i][j+1]==1: blueLine += 1
	print blueSquare-blueLine/2

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()

class Ruiwa():
    def __init__(self, a):
        self.H = h = len(a)
        self.W = w = len(a[0])
        self.R = r = a
        for i in range(h):
            for j in range(1,w):
                r[i][j] += r[i][j-1]

        for i in range(1,h):
            for j in range(w):
                r[i][j] += r[i-1][j]

    def search(self, x1, y1, x2, y2):
        if x1 > x2 or y1 > y2:
            return 0

        r = self.R
        rr = r[y2][x2]
        if x1 > 0 and y1 > 0:
            return rr - r[y1-1][x2] - r[y2][x1-1] + r[y1-1][x1-1]
        if x1 > 0:
            rr -= r[y2][x1-1]
        if y1 > 0:
            rr -= r[y1-1][x2]

        return rr


def main():
    n,m,q = LI()
    a = [[1 if c == '1' else 0 for c in S()] for _ in range(n)]
    b = [[0] * m for _ in range(n)]
    c = [[0] * m for _ in range(n)]
    for i in range(n):
        for j in range(m):
            if a[i][j] == 0:
                continue
            if i > 0 and a[i-1][j]:
                b[i][j] += 1
            if j > 0 and a[i][j-1]:
                c[i][j] += 1
    A = Ruiwa(a)
    B = Ruiwa(b)
    C = Ruiwa(c)
    rr = []
    for i in range(q):
        y1,x1,y2,x2 = LI_()
        r = A.search(x1,y1,x2,y2) - B.search(x1,y1+1,x2,y2) - C.search(x1+1,y1,x2,y2)
        rr.append(r)

    return '\n'.join(map(str,rr))


print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()

class Ruiwa():
    def __init__(self, a):
        self.H = h = len(a)
        self.W = w = len(a[0])
        self.R = r = [[a[i][j] for j in range(w)] for i in range(h)]
        for i in range(h):
            for j in range(1,w):
                r[i][j] += r[i][j-1]

        for i in range(1,h):
            for j in range(w):
                r[i][j] += r[i-1][j]

    def search(self, x1, y1, x2, y2):
        if x1 > x2 or y1 > y2:
            return 0

        r = self.R
        rr = r[y2][x2]
        if x1 > 0 and y1 > 0:
            return rr - r[y1-1][x2] - r[y2][x1-1] + r[y1-1][x1-1]
        if x1 > 0:
            rr -= r[y2][x1-1]
        if y1 > 0:
            rr -= r[y1-1][x2]

        return rr


def main():
    n,m,q = LI()
    a = [[1 if c == '1' else 0 for c in S()] for _ in range(n)]
    b = [[0] * m for _ in range(n)]
    c = [[0] * m for _ in range(n)]
    for i in range(n):
        for j in range(m):
            if a[i][j] == 0:
                continue
            if i > 0 and a[i-1][j]:
                b[i][j] += 1
            if j > 0 and a[i][j-1]:
                c[i][j] += 1
    A = Ruiwa(a)
    B = Ruiwa(b)
    C = Ruiwa(c)
    rr = []
    for i in range(q):
        y1,x1,y2,x2 = LI_()
        r = A.search(x1,y1,x2,y2) - B.search(x1,y1+1,x2,y2) - C.search(x1+1,y1,x2,y2)
        rr.append(r)

    return '\n'.join(map(str,rr))


print(main())

Submission status: Time Limit Exceeded

Solution code:
def num_of_edges(grid, row, col, x2, y2):
    edges = 0
    if col + 1 < y2 and int(grid[row][col + 1]) == 1:
        edges += 1
    if row + 1 < x2 and int(grid[row + 1][col]) == 1:
        edges += 1
    return edges


n, m, q = [int(x) for x in input().split()]
grid = []

for line in range(n):
    grid.append(input().rstrip())

for query in range(q):
    vertices, edges = 0, 0
    x1, y1, x2, y2 = [int(x) - 1 for x in input().split()]
    for row in range(x1, x2 + 1):
        for col in range(y1, y2 + 1):
            if int(grid[row][col]) == 1:
                vertices += 1
                edges += num_of_edges(grid, row, col, x2 + 1, y2 + 1)
    print(vertices - edges)

Submission status: Time Limit Exceeded

Solution code:
w, h, q = map(int, input().split())

field = [input() for x in range(w)]
x_edge_map = [[0 for x in range(h + 1)] for x in range(w)]
y_edge_map = list(map(lambda x: x[:], x_edge_map))
node_map = list(map(lambda x: x[:], x_edge_map))

for row_index, row in enumerate(field):
    for index, cell in enumerate(row):
        x_edge_map[row_index][index] = x_edge_map[row_index][index - 1] - (1 if index != 0 and cell == "1" == row[index - 1] else 0)
        y_edge_map[row_index][index] = y_edge_map[row_index - 1][index] - (1 if row_index != 0 and cell == "1" == field[row_index - 1][index] else 0)

        node_map[row_index][index] = node_map[row_index][index - 1] + (1 if cell == "1" else 0)


def y_accumulation(array):
    for i, v in enumerate(array[1:]):
        for j in range(len(v)):
            v[j] += array[i][j]
    return array


def x_accumulation(array):
    for v in array:
        for i in range(1, len(v) - 1):
            v[i] += v[i - 1]
    return array


y_accumulation(x_edge_map).append([0 for x in range(h + 1)])
x_accumulation(y_edge_map).append([0 for x in range(h + 1)])
y_accumulation(node_map).append([0 for x in range(h + 1)])
query = [list(map(lambda x: int(x) - 1, input().split())) for x in range(q)]

for sy, sx, ey, ex in query:
    print(sum((
    x_edge_map[ey][ex] - x_edge_map[sy - 1][ex] - (x_edge_map[ey][sx] - x_edge_map[sy - 1][sx]),
    y_edge_map[ey][ex] - y_edge_map[sy][ex] - (y_edge_map[ey][sx - 1] - y_edge_map[sy][sx - 1]),
    node_map[ey][ex] - node_map[sy - 1][ex] - (node_map[ey][sx - 1] - node_map[sy - 1][sx - 1]),
    )))

Submission status: Time Limit Exceeded

Solution code:
w, h, q = map(int, input().split())

field = [input() for x in range(w)]
x_edge_map = [[0 for x in range(h)] for x in range(w)]
y_edge_map = list(map(lambda x: x[:], x_edge_map))
x_node_map = [[0 for x in range(h + 1)] for x in range(w)]
for row_index, row in enumerate(field):
    for index, cell in enumerate(row):
        x_edge_map[row_index][index] = x_edge_map[row_index][index - 1] + (1 if index != 0 and cell == "1" == row[index - 1] else 0)
        y_edge_map[row_index][index] = y_edge_map[row_index - 1][index] + (1 if row_index != 0 and cell == "1" == field[row_index - 1][index] else 0)

        x_node_map[row_index][index] = x_node_map[row_index][index - 1] + (1 if cell == "1" else 0)

query = [list(map(lambda x: int(x) - 1, input().split())) for x in range(q)]

for sy, sx, ey, ex in query:
    print(sum([xs[ex] - xs[sx - 1] for xs in x_node_map[sy : ey + 1]]) - sum([xs[ex] - xs[sx] for xs in x_edge_map[sy : ey + 1]]) - sum([y_edge_map[ey][xi] - y_edge_map[sy][xi] for xi in range(sx, ex + 1)]))

Submission status: Time Limit Exceeded

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

for inpt in sys.stdin.read().splitlines():
    # x1, y1, x2, y2 = [int(i) for i in input().split()]
    x1, y1, x2, y2 = map(int, inpt.split())
    node = nblue[x2][y2] - nblue[x1-1][y2] - nblue[x2][y1-1] + nblue[x1-1][y1-1]
    edge = (nb_yoko[x2][y2] - nb_yoko[x1-1][y2] - nb_yoko[x2][y1] + nb_yoko[x1-1][y1])
    edge += (nb_tate[x2][y2] - nb_tate[x1][y2] - nb_tate[x2][y1-1] + nb_tate[x1][y1-1])
    print(node - edge)

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
def solve() :
  N,M,Q = raw_input().split()
  N = int(N)
  M = int(M)
  Q = int(Q)
  
  grid = []
  for i in range(N):
    raw = raw_input()
    grid.append(raw)
  qs = []
  for ii in range(Q):
    raw = raw_input()
    qs.append(raw)

  for q in qs:
    qq = q.split()
    #print 'q=',q
    y1 = int(qq[0]) - 1
    x1 = int(qq[1]) - 1
    y2 = int(qq[2]) - 1
    x2 = int(qq[3]) - 1
    w = x2 - x1 + 1
    h = y2 - y1 + 1

    mapp = [[0 for col in range(w)] for row in range(h)]
    eqs = 0
    next = 1
    for y in range(h):
      for x in range(w):
        c = grid[y+y1][x+x1]
        if c == '0': continue
        up = -1 if y == 0 else mapp[y-1][x]
        left = -1 if x == 0 else mapp[y][x-1]
        #print 'y=',y,'x=',x,'up=',up,',left=',left
        if up > 0:
          if left > 0:
            if up == left : mapp[y][x] = up
            else :
              #print 'eq! :up=',up,',left=',left
              eqs += 1
              mapp[y][x] = left
          else :
            mapp[y][x] = up
        else:
          if left > 0:
            mapp[y][x] = left
          else: 
            mapp[y][x] = next
            next += 1
        #print 'up=',up,',left=',left,',mapp[',y,'][',x,']=',mapp[y][x]
    #print 'mapp=',mapp

    #sett = set()
    #for y in range(h) :
    #  for x in range(w) :
    #    #print 'y,x=',y,x
    #    if(mapp[y][x] > 0):  sett.add(mapp[y][x])
    #print 'sett=',sett,',eqs=',eqs
    print next-1-eqs

if __name__ == '__main__' :
  solve()

Submission status: Time Limit Exceeded

Solution code:
def solve() :
  N,M,Q = raw_input().split()
  N = int(N)
  M = int(M)
  Q = int(Q)
  
  grid = []
  for i in range(N):
    raw = raw_input()
    grid.append(raw)
  qs = []
  for ii in range(Q):
    raw = raw_input()
    qs.append(raw)

  for q in qs:
    qq = q.split()
    #print 'q=',q
    y1 = int(qq[0]) - 1
    x1 = int(qq[1]) - 1
    y2 = int(qq[2]) - 1
    x2 = int(qq[3]) - 1
    w = x2 - x1 + 1
    h = y2 - y1 + 1

    mapp = [[0 for col in range(w)] for row in range(h)]
    eqs = 0
    next = 1
    for y in range(h):
      for x in range(w):
        c = grid[y+y1][x+x1]
        if c == '0': continue
        up = -1 if y == 0 else mapp[y-1][x]
        left = -1 if x == 0 else mapp[y][x-1]
        #print 'y=',y,'x=',x,'up=',up,',left=',left
        if up > 0:
          if left > 0:
            if up == left : mapp[y][x] = up
            else :
              #print 'eq! :up=',up,',left=',left
              eqs += 1
              mapp[y][x] = left
          else :
            mapp[y][x] = up
        else:
          if left > 0:
            mapp[y][x] = left
          else: 
            mapp[y][x] = next
            next += 1
        #print 'up=',up,',left=',left,',mapp[',y,'][',x,']=',mapp[y][x]
    #print 'mapp=',mapp

    sett = set()
    for y in range(h) :
      for x in range(w) :
        #print 'y,x=',y,x
        if(mapp[y][x] > 0):  sett.add(mapp[y][x])
    #print 'sett=',sett,',eqs=',eqs
    print len(sett)-eqs

if __name__ == '__main__' :
  solve()

Submission status: Time Limit Exceeded

Solution code:
Y, X, Q = map(int, input().split())
a = [[(0, 0, 0, 0) for i in range(X + 1)]]
for y in range(Y):
    _a = [(0, 0, 0, 0)]
    current_row = [int(c) for c in input()]
    csum_row = [0, 0, 0]
    for x, n in enumerate(current_row, start=1):
        above_cell, left_cell = (a[-1][x], _a[-1])
        csum_row[0] += n
        csum_row[1] += left_cell[3] & n
        csum_row[2] += above_cell[3] & n
        vertices = csum_row[0] + above_cell[0]
        sides_row = csum_row[1] + above_cell[1]
        sides_col = csum_row[2] + above_cell[2]
        _a.append((vertices, sides_row, sides_col, n))
    a.append(_a)
 
for q in range(Q):
    y1, x1, y2, x2 = map(int, input().split())
    vertices = a[y2][x2][0] - a[y2][x1-1][0] - a[y1-1][x2][0] + a[y1-1][x1-1][0]
    sides_row = a[y2][x2][1] - a[y2][x1][1] - a[y1-1][x2][1] + a[y1-1][x1][1]
    sides_col = a[y2][x2][2] - a[y1][x2][2] - a[y2][x1-1][2] + a[y1][x1-1][2]
    print(vertices - sides_row - sides_col)

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

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

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

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

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

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

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

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

for s in s_list:
    print(int(s))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

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

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

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

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

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

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

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

for s in s_list:
    print(s)