Problem:


Score: 600 points

Problem Statement

There is a grass field that stretches infinitely.

In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).

There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).

What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print INF instead.

Constraints

All values in input are integers between -10^9 and 10^9  (inclusive).

1 \leq N, M \leq 1000

A_i < B_i\ (1 \leq i \leq N)

E_j < F_j\ (1 \leq j \leq M)

The point (0, 0) does not lie on any of the given segments.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M

Output

If the area of the region the cow can reach is infinite, print INF; otherwise, print an integer representing the area in \mathrm{cm^2}.

(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)

Sample Input 1

5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4

Sample Output 1

13

The area of the region the cow can reach is 13\ \mathrm{cm^2}.

Sample Input 2

6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4

Sample Output 2

INF

The area of the region the cow can reach is infinite.



Sample input:
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4


Sample output:
13

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from itertools import chain


def inputs(func=lambda x: x, sep=None, maxsplit=-1):
	return map(func, sys.stdin.buffer.readline().split(sep=sep, maxsplit=maxsplit))

def input_row(n : int, type=np.int, **kwargs):
	return np.fromiter(inputs(type, **kwargs), dtype=type)

def input_2d(nrows : int, ncols : int, type=np.int, **kwargs):
	data = np.fromiter(
		chain.from_iterable(
			inputs(type) for _ in range(nrows)
		),
		dtype=type
	)
	return data.reshape(nrows, ncols)

from collections import deque
import numpy as np


N, M = inputs(int)
A, B, C = input_2d(N, 3).T
D, E, F = input_2d(M, 3).T
xs = np.fromiter({*C, *E, *F}, dtype=int)
ys = np.fromiter({*A, *B, *D}, dtype=int)
xs.sort()
ys.sort()
x_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)
y_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

A = np.searchsorted(ys, A, side='right')
B = np.searchsorted(ys, B, side='right')
C = np.searchsorted(xs, C, side='right')
D = np.searchsorted(ys, D, side='right')
E = np.searchsorted(xs, E, side='right')
F = np.searchsorted(xs, F, side='right')

for a, b, c in zip(A, B, C):
	x_guard[c, a:b] = True

for d, e, f in zip(D, E, F):
	y_guard[e:f, d] = True

nexts = deque()
nexts.append((
	np.searchsorted(xs, 0, side='right'),
	np.searchsorted(ys, 0, side='right')
))
visited = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

area = 0

while nexts:
	xi, yi = nexts.popleft()
	if not visited[xi, yi]:
		visited[xi, yi] = True
		if 0 < xi < len(xs) and 0 < yi < len(ys):
			area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1])
			if not x_guard[xi, yi]:
				nexts.append((xi-1, yi))
			if not x_guard[xi+1, yi]:
				nexts.append((xi+1, yi))
			if not y_guard[xi, yi]:
				nexts.append((xi, yi-1))
			if not y_guard[xi, yi+1]:
				nexts.append((xi, yi+1))
		else:
			area = 'INF'
			break

print(area)

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

from collections import defaultdict
from collections import deque
import sys
readline = sys.stdin.readline

N, M = map(int, readline().split())
INF = 2 * 10**9 + 1
W = defaultdict(int)

min_y = INF
max_y = INF * -1
for i in range(N):
    A, B, C = map(int, readline().split())
    A *= 2
    B *= 2
    C *= 2
    min_y = min(min_y, C)
    max_y = max(max_y, C)
    for j in range(A, B+1):
        W[(j, C)] = -1

min_x = INF
max_x = INF * -1
for i in range(M):
    D, E, F = map(int, readline().split())
    D *= 2
    E *= 2
    F *= 2
    min_x = min(min_x, D)
    max_x = max(max_x, D)
    for j in range(E, F+1):
        W[(D, j)] = -1

q = deque()
q.append((0, 0))
W[(0, 0)] = -1
ans = 0
b_ans = True
while len(q) > 0:
    x, y = q.pop()
    #print(x, y)
    if x > max_x or x < min_x or y > max_y or y < min_y:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if (nx, ny) not in W:
            if nx%2==1 and ny%2==1:
                ans += 1
            q.append((nx, ny))
            W[(nx, ny)] = -1

if b_ans == True:
    print(ans)
else:
    print('INF')

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    #x_dic = {val:idx for idx, val in enumerate(x_list)}
    #y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = deque(x_list)
    tmp1.appendleft(x_list[0])
    tmp2 = x_list[:]
    tmp2.append(x_list[-1])
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = deque(y_list)
    tmp1.appendleft(y_list[0])
    tmp2 = y_list[:]
    tmp2.append(y_list[-1])
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None

    while queue:
        x, y = queue.popleft()
        for w_i, i, j in ((1, 0, 1), (3, 0, -1), (0, 1, 0), (2, -1, 0)):
            n_x, n_y = x + i, y + j
            if not seen[n_x][n_y] and not walls[x][y] & (1 << w_i):
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                ret += x_grid[n_x] * y_grid[n_y]
                if x_grid[n_x] == 0 or y_grid[n_y] == 0:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    #x_dic = {val:idx for idx, val in enumerate(x_list)}
    #y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = deque(x_list)
    tmp1.appendleft(x_list[0])
    tmp2 = x_list[:]
    tmp2.append(x_list[-1])
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = deque(y_list)
    tmp1.appendleft(y_list[0])
    tmp2 = y_list[:]
    tmp2.append(y_list[-1])
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None
    dir = [(1,0), (0,1), (-1,0), (0,-1)]
    while queue:
        x, y = queue.popleft()
        wl = walls[x][y]
        tmp = [i for i in range(4) if (wl >> i) % 2 == 0]
        for i in tmp:
            i,j = dir[i]
            n_x, n_y = x+i, y+j
            if not seen[n_x][n_y]:
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                ret += x_grid[n_x] * y_grid[n_y]
                if not x_grid[n_x] * y_grid[n_y]:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    #x_dic = {val:idx for idx, val in enumerate(x_list)}
    #y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = deque(x_list)
    tmp1.appendleft(x_list[0])
    tmp2 = x_list[:]
    tmp2.append(x_list[-1])
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = deque(y_list)
    tmp1.appendleft(y_list[0])
    tmp2 = y_list[:]
    tmp2.append(y_list[-1])
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None
    dir = [(1,0), (0,1), (-1,0), (0,-1)]
    while queue:
        x, y = queue.popleft()
        tmp = [i for i in range(4) if (walls[x][y] >> i) % 2 == 0]
        for i in tmp:
            i,j = dir[i]
            n_x, n_y = x+i, y+j
            if not seen[n_x][n_y]:
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                ret += x_grid[n_x] * y_grid[n_y]
                if not x_grid[n_x] * y_grid[n_y]:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from itertools import chain


def inputs(func=lambda x: x, sep=None, maxsplit=-1):
	return map(func, sys.stdin.buffer.readline().split(sep=sep, maxsplit=maxsplit))

def input_row(n : int, type=np.int, **kwargs):
	return np.fromiter(inputs(type, **kwargs), dtype=type)

def input_2d(nrows : int, ncols : int, type=np.int, **kwargs):
	data = np.fromiter(
		chain.from_iterable(
			inputs(type) for _ in range(nrows)
		),
		dtype=type
	)
	return data.reshape(nrows, ncols)

from collections import deque
from bisect import bisect_right
import numpy as np


N, M = inputs(int)
A, B, C = input_2d(N, 3).T
D, E, F = input_2d(M, 3).T

xs = sorted({*C, *E, *F})
ys = sorted({*A, *B, *D})
x_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)
y_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

for i in range(N):
	c = bisect_right(xs, C[i])
	a = bisect_right(ys, A[i])
	b = bisect_right(ys, B[i])
	x_guard[c, a:b] = True

for i in range(M):
	d = bisect_right(ys, D[i])
	e = bisect_right(xs, E[i])
	f = bisect_right(xs, F[i])
	y_guard[e:f, d] = True

nexts = deque()
nexts.append((bisect_right(xs, 0), bisect_right(ys, 0)))
visited = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

area = 0

while nexts:
	xi, yi = nexts.popleft()
	if not visited[xi, yi]:
		visited[xi, yi] = True
		if 0 < xi < len(xs) and 0 < yi < len(ys):
			area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1])
			if not x_guard[xi, yi]:
				nexts.append((xi-1, yi))
			if not x_guard[xi+1, yi]:
				nexts.append((xi+1, yi))
			if not y_guard[xi, yi]:
				nexts.append((xi, yi-1))
			if not y_guard[xi, yi+1]:
				nexts.append((xi, yi+1))
		else:
			area = 'INF'
			break

print(area)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    #x_dic = {val:idx for idx, val in enumerate(x_list)}
    #y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = deque(x_list)
    tmp1.appendleft(x_list[0])
    tmp2 = x_list[:]
    tmp2.append(x_list[-1])
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = deque(y_list)
    tmp1.appendleft(y_list[0])
    tmp2 = y_list[:]
    tmp2.append(y_list[-1])
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None

    while queue:
        x, y = queue.popleft()
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            if not seen[n_x][n_y] and not walls[x][y] & (1 << w_i):
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                ret += x_grid[n_x] * y_grid[n_y]
                if not x_grid[n_x] * y_grid[n_y]:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    #x_dic = {val:idx for idx, val in enumerate(x_list)}
    #y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = deque(x_list)
    tmp1.appendleft(x_list[0])
    tmp2 = x_list[:]
    tmp2.append(x_list[-1])
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = deque(y_list)
    tmp1.appendleft(y_list[0])
    tmp2 = y_list[:]
    tmp2.append(y_list[-1])
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None

    while queue:
        x, y = queue.popleft()
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            if not seen[n_x][n_y] and not walls[x][y] & (1 << w_i):
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                next_sq = x_grid[n_x] * y_grid[n_y]
                ret += next_sq
                if not next_sq:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from itertools import chain


def inputs(func=lambda x: x, sep=None, maxsplit=-1):
	return map(func, sys.stdin.buffer.readline().split(sep=sep, maxsplit=maxsplit))

def input_row(n : int, type=np.int, **kwargs):
	return np.fromiter(inputs(type, **kwargs), dtype=type)

def input_2d(nrows : int, ncols : int, type=np.int, **kwargs):
	data = np.fromiter(
		chain.from_iterable(
			inputs(type) for _ in range(nrows)
		),
		dtype=type
	)
	return data.reshape(nrows, ncols)

from collections import deque
from bisect import bisect_right
import numpy as np


N, M = inputs(int)
A, B, C = input_2d(N, 3).T
D, E, F = input_2d(M, 3).T
xs = set()
ys = set()

for i in range(N):
	xs.add(C[i])
	ys.add(A[i])
	ys.add(B[i])

for i in range(M):
	ys.add(D[i])
	xs.add(E[i])
	xs.add(F[i])

xs = sorted(xs)
ys = sorted(ys)

x_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)
y_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

for i in range(N):
	c = bisect_right(xs, C[i])
	a = bisect_right(ys, A[i])
	b = bisect_right(ys, B[i])
	x_guard[c, a:b] = True

for i in range(M):
	d = bisect_right(ys, D[i])
	e = bisect_right(xs, E[i])
	f = bisect_right(xs, F[i])
	y_guard[e:f, d] = True

nexts = deque()
nexts.append((bisect_right(xs, 0), bisect_right(ys, 0)))
visited = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

area = 0

while nexts:
	xi, yi = nexts.popleft()
	if not visited[xi, yi]:
		visited[xi, yi] = True
		if 0 < xi < len(xs) and 0 < yi < len(ys):
			area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1])
			if not x_guard[xi, yi]:
				nexts.append((xi-1, yi))
			if not x_guard[xi+1, yi]:
				nexts.append((xi+1, yi))
			if not y_guard[xi, yi]:
				nexts.append((xi, yi-1))
			if not y_guard[xi, yi+1]:
				nexts.append((xi, yi+1))
		else:
			area = 'INF'
			break

print(area)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    #x_dic = {val:idx for idx, val in enumerate(x_list)}
    #y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = [x_list[0]]+x_list
    tmp2 = x_list+[x_list[-1]]
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = [y_list[0]]+y_list
    tmp2 = y_list+[y_list[-1]]
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None

    while queue:
        x, y = queue.popleft()
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            if not seen[n_x][n_y] and not walls[x][y] & (1 << w_i):
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                next_sq = x_grid[n_x] * y_grid[n_y]
                ret += next_sq
                if not next_sq:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from itertools import chain


def inputs(func=lambda x: x, sep=None, maxsplit=-1):
	return map(func, sys.stdin.readline().split(sep=sep, maxsplit=maxsplit))

def input_row(n : int, type=np.int, **kwargs):
	return np.fromiter(inputs(type, **kwargs), dtype=type)

def input_2d(nrows : int, ncols : int, type=np.int, **kwargs):
	data = np.fromiter(
		chain.from_iterable(
			inputs(type) for _ in range(nrows)
		),
		dtype=type
	)
	return data.reshape(nrows, ncols)

from collections import deque
from bisect import bisect_right
import numpy as np


N, M = inputs(int)
A, B, C = input_2d(N, 3).T
D, E, F = input_2d(M, 3).T
xs = set()
ys = set()

for i in range(N):
	xs.add(C[i])
	ys.add(A[i])
	ys.add(B[i])

for i in range(M):
	ys.add(D[i])
	xs.add(E[i])
	xs.add(F[i])

xs = sorted(xs)
ys = sorted(ys)

x_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)
y_guard = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

for i in range(N):
	c = bisect_right(xs, C[i])
	a = bisect_right(ys, A[i])
	b = bisect_right(ys, B[i])
	x_guard[c, a:b] = True

for i in range(M):
	d = bisect_right(ys, D[i])
	e = bisect_right(xs, E[i])
	f = bisect_right(xs, F[i])
	y_guard[e:f, d] = True

nexts = deque()
nexts.append((bisect_right(xs, 0), bisect_right(ys, 0)))
visited = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)

area = 0

while nexts:
	xi, yi = nexts.popleft()
	if not visited[xi, yi]:
		visited[xi, yi] = True
		if 0 < xi < len(xs) and 0 < yi < len(ys):
			area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1])
			if not x_guard[xi, yi]:
				nexts.append((xi-1, yi))
			if not x_guard[xi+1, yi]:
				nexts.append((xi+1, yi))
			if not y_guard[xi, yi]:
				nexts.append((xi, yi-1))
			if not y_guard[xi, yi+1]:
				nexts.append((xi, yi+1))
		else:
			area = 'INF'
			break

print(area)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    x_dic = {val:idx for idx, val in enumerate(x_list)}
    y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = [x_list[0]]+x_list
    tmp2 = x_list+[x_list[-1]]
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = [y_list[0]]+y_list
    tmp2 = y_list+[y_list[-1]]
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = x_dic[a]
        b_i = x_dic[b]
        c_i = y_dic[c]
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = x_dic[d]
        e_i = y_dic[e]
        f_i = y_dic[f]
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None

    while queue:
        x, y = queue.popleft()
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            if not seen[n_x][n_y] and not walls[x][y] & (1 << w_i):
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                next_sq = x_grid[n_x] * y_grid[n_y]
                ret += next_sq
                if not next_sq:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()