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:
# coding: utf-8
# Your code here!
import sys
readline = sys.stdin.readline
read = sys.stdin.read

n,m = [int(i) for i in readline().split()]
tate = [[int(i) for i in readline().split()] for _ in range(n)]
yoko = [[int(i) for i in readline().split()] for _ in range(m)]

INF = 10**9+5
hcoord = {-INF,0,INF}
wcoord = {-INF,0,INF}

for a,b,c in tate: # (a,c) to (b,c)
    hcoord.add(a)
    hcoord.add(b)
    wcoord.add(c)
for d,e,f in yoko: # (d,e) to (d,f)
    hcoord.add(d)
    wcoord.add(e)
    wcoord.add(f)

hcoord = list(sorted(hcoord))
wcoord = list(sorted(wcoord))

zaatu_x = {a:i for i,a in enumerate(sorted(hcoord))}
zaatu_y = {a:i for i,a in enumerate(sorted(wcoord))}

P = len(hcoord)*2
Q = len(wcoord)*2
used = [[0 for y in range(Q-1)] for x in range(P-1)]

for a,b,c in tate: # (a,c) to (b,c)
    xa = 2*zaatu_x[a]
    xb = 2*zaatu_x[b]
    yc = 2*zaatu_y[c]
    for i in range(xa,xb):
        used[i][yc] = -1
for d,e,f in yoko: # (d,e) to (d,f)
    xd = 2*zaatu_x[d]
    ye = 2*zaatu_y[e]
    yf = 2*zaatu_y[f]
    for i in range(ye,yf):
        used[xd][i] = -1

dx = [1,0,-1,0]
dy = [0,1,0,-1]

x0 = zaatu_x[0]*2
y0 = zaatu_y[0]*2

from collections import deque
q = deque([(x0,y0)])
used[x0][y0] = 1
while q:
    x,y = q.popleft()
    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]
        if nx < 0 or ny < 0 or nx >= P-1 or ny >= Q-1: continue #枠外
        if used[nx][ny] == 0:
            used[nx][ny] = 1
            q.append((nx,ny))

if used[0][0] == 1:
    print("INF")
else:
    ans = 0
    for i in range(1,P-1,2):
        for j in range(1,Q-1,2):
            if used[i][j] == 1:
                ans += (hcoord[i//2+1]-hcoord[i//2])*(wcoord[j//2+1]-wcoord[j//2])
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

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

N, M = map(int, readline().split())
INF = 10**9 + 1
s_X = set([-INF, 0, INF])
s_Y = set([-INF, 0, INF])

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

W = [[False] * maxY for _ in range(maxX)]

for A, B, C in ABC:
    A = mapX[l_X[bisect.bisect_left(l_X, A)]]
    B = mapX[l_X[bisect.bisect_right(l_X, B)-1]]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[j][C] = True

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[l_Y[bisect.bisect_left(l_Y, E)]]
    F = mapY[l_Y[bisect.bisect_right(l_Y, F)-1]]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[D][j] = True

#print(W)
q = deque()
q.append((mapX[0]*2, mapY[0]*2))
W[mapX[0]*2][mapY[0]*2] = True
ans = 0
b_ans = True
while q:
    x, y = q.pop()
    if x == maxX or x == 0 or y == maxY or y == 0:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if W[nx][ny] == False:
            if nx%2==1 and ny%2==1:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[nx][ny] = True

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

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

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

N, M = map(int, readline().split())
INF = 10**9 + 1
s_X = set([-INF, 0, INF])
s_Y = set([-INF, 0, INF])

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

W = [[0] * maxY for _ in range(maxX)]

for A, B, C in ABC:
    A = mapX[l_X[bisect.bisect_left(l_X, A)]]
    B = mapX[l_X[bisect.bisect_right(l_X, B)-1]]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[j][C] = 1

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[l_Y[bisect.bisect_left(l_Y, E)]]
    F = mapY[l_Y[bisect.bisect_right(l_Y, F)-1]]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[D][j] = 1

#print(W)
q = deque()
q.append((mapX[0]*2, mapY[0]*2))
W[mapX[0]*2][mapY[0]*2] = 1
ans = 0
b_ans = True
while q:
    x, y = q.pop()
    if x == maxX or x == 0 or y == maxY or y == 0:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if W[nx][ny] == 0:
            if nx%2==1 and ny%2==1:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[nx][ny] = 1

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

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

import bisect
import sys
readline = sys.stdin.readline

N, M = map(int, readline().split())
INF = 10**9 + 1
s_X = set([-INF, 0, INF])
s_Y = set([-INF, 0, INF])

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

W = [[0] * maxY for _ in range(maxX)]

for A, B, C in ABC:
    A = mapX[l_X[bisect.bisect_left(l_X, A)]]
    B = mapX[l_X[bisect.bisect_right(l_X, B)-1]]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[j][C] = 1

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[l_Y[bisect.bisect_left(l_Y, E)]]
    F = mapY[l_Y[bisect.bisect_right(l_Y, F)-1]]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[D][j] = 1

#print(W)
q = []
q.append((mapX[0]*2, mapY[0]*2))
W[mapX[0]*2][mapY[0]*2] = 1
ans = 0
b_ans = True
while q:
    x, y = q.pop()
    if x == maxX or x == 0 or y == maxY or y == 0:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if W[nx][ny] == 0:
            if nx%2==1 and ny%2==1:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[nx][ny] = 1

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

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

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

N, M = map(int, readline().split())
INF = 10**9 + 1
s_X = set()
s_Y = set()
s_X.add(0)
s_X.add(INF)
s_X.add(-INF)
s_Y.add(0)
s_Y.add(INF)
s_Y.add(-INF)

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_X.add(A)
    s_X.add(B)
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)
    s_Y.add(E)
    s_Y.add(F)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

W = [[0] * maxY for _ in range(maxX)]

for A, B, C in ABC:
    A = mapX[A]
    B = mapX[B]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[j][C] = 1

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[E]
    F = mapY[F]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[D][j] = 1

#print(W)
q = deque()
q.append((mapX[0]*2, mapY[0]*2))
W[mapX[0]*2][mapY[0]*2] = 1
ans = 0
b_ans = True
while q:
    x, y = q.pop()
    if x == maxX or x == 0 or y == maxY or y == 0:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if W[nx][ny]==0:
            if nx%2==1 and ny%2==1:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[nx][ny] = 1

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
from bisect import bisect_left

def main():
    n,m=map(int,input().split())
    X,Y=set(),set()
    H=[]
    V=[]
    for _ in range(n):
        a,b,c=map(int,input().split())
        X.add(a); X.add(b)
        Y.add(c)
        V.append((a,b,c))
    for _ in range(m):
        d,e,f=map(int,input().split())
        X.add(d)
        Y.add(e); Y.add(f)
        H.append((d,e,f))
    X=list(X); Y=list(Y)
    X.sort(); Y.sort()
    MapX={}; MapY={}
    for i,x in enumerate(X):
        MapX[x]=i
    for i,y in enumerate(Y):
        MapY[y]=i
    h=len(MapX)*2; w=len(MapY)*2
    Grid=[[False]*w for _ in range(h)]
    for a,b,c in V:
        a=MapX[a]*2
        b=MapX[b]*2
        c=MapY[c]*2
        for x in range(a,b+1):
            Grid[x][c]=True
    for d,e,f in H:
        d=MapX[d]*2
        e=MapY[e]*2
        f=MapY[f]*2
        for y in range(e,f+1):
            Grid[d][y]=True
    s_x=bisect_left(X,0)*2-1
    s_y=bisect_left(Y,0)*2-1
    if s_x<0 or s_y<0 or s_x>=h-1 or s_y>=w-1:
        return 'INF'
    Grid[s_x][s_y]=True
    D=[(1,0),(-1,0),(0,1),(0,-1)]
    ans=0
    q=deque([(s_x,s_y)])
    Grid[s_x][s_y]=True
    while q:
        x,y=q.popleft()
        ans+=(X[x//2+1]-X[x//2])*(Y[y//2+1]-Y[y//2])
        for dx,dy in D:
            half_x,half_y=x+dx,y+dy
            if Grid[half_x][half_y]:
                continue
            to_x,to_y=half_x+dx,half_y+dy
            if to_x<0 or to_y<0 or to_x==h-1 or to_y==w-1:
                return 'INF'
            if Grid[to_x][to_y]:
                continue
            Grid[to_x][to_y]=True
            q.append((to_x,to_y))
    return ans
    
if __name__ == "__main__":
    print(main())

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

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

N, M = map(int, readline().split())
INF = 10**9 + 1
s_X = set()
s_Y = set()
s_X.add(0)
s_X.add(INF)
s_X.add(-INF)
s_Y.add(0)
s_Y.add(INF)
s_Y.add(-INF)

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_X.add(A)
    s_X.add(B)
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)
    s_Y.add(E)
    s_Y.add(F)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

W = [[True] * maxY for _ in range(maxX)]

for A, B, C in ABC:
    A = mapX[A]
    B = mapX[B]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[j][C] = False

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[E]
    F = mapY[F]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[D][j] = False

#print(W)
q = deque()
q.append((mapX[0]*2, mapY[0]*2))
W[mapX[0]*2][mapY[0]*2] = False
ans = 0
b_ans = True
while q:
    x, y = q.pop()
    if x == maxX or x == 0 or y == maxY or y == 0:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if W[nx][ny]:
            if nx%2==1 and ny%2==1:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[nx][ny] = False

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

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_left, 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 = np.unique(C)
ys = np.unique(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 a, b, c in zip(A, B, C):
	c = bisect_right(xs, c)
	a = bisect_left(ys, a) + 1
	b = bisect_right(ys, b)
	x_guard[c, a:b] = True

for d, e, f in zip(D, E, F):
	d = bisect_right(ys, d)
	e = bisect_left(xs, e) + 1
	f = bisect_right(xs, f)
	y_guard[e:f, d] = True

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

area = 0

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

print(area)

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.unique(C)
ys = np.unique(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)

C = np.searchsorted(xs, C, side='right')
A = np.searchsorted(ys, A, side='left') + 1
B = np.searchsorted(ys, B, side='right')

D = np.searchsorted(ys, D, side='right')
E = np.searchsorted(xs, E, side='left') + 1
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

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

area = 0

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

print(area)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import sys
from queue import Queue
from pprint import pprint
sys.setrecursionlimit(300000)


def solve(N: int, M: int, A: "List[int]", B: "List[int]", C: "List[int]", D: "List[int]", E: "List[int]", F: "List[int]"):
    xs, ys = {}, {}
    xs[0] = 0
    ys[0] = 0
    for i in range(N):
        xs[A[i]] = 0
        xs[B[i]] = 0
        ys[C[i]] = 0
    for i in range(M):
        xs[D[i]] = 0
        ys[E[i]] = 0
        ys[F[i]] = 0

    sx = sorted(xs.keys())
    sy = sorted(ys.keys())
    for i, x in enumerate(sx):
        xs[x] = i
    for i, y in enumerate(sy):
        ys[y] = i

    h, w = len(sy) * 2, len(sx) * 2
    g = [[0] * w for _ in range(h)]
    for i in range(N):
        y = ys[C[i]] * 2
        for x in range(xs[A[i]] * 2, xs[B[i]] * 2 + 1):
            g[y][x] = 1
    for i in range(M):
        x = xs[D[i]] * 2
        for y in range(ys[E[i]] * 2, ys[F[i]] * 2 + 1):
            g[y][x] = 1

    x, y = xs[0] * 2, ys[0] * 2
    g[y][x] = 2
    q = Queue()
    q.put((x, y))
    dx = [0, -1, 0, 1]
    dy = [1, 0, -1, 0]
    ret = 0
    #pprint(g)
    while not q.empty():
        x, y = q.get()
        if x % 2 and y % 2:
            xx = sx[x // 2 + 1] - sx[x // 2]
            yy = sy[y // 2 + 1] - sy[y // 2]
            ret += xx * yy
        for k in range(len(dx)):
            tx, ty = x + dx[k], y + dy[k]
            if 0 <= tx < w and 0 <= ty < h and g[ty][tx] == 0:
                if tx == 0 or tx == w - 1 or ty == 0 or ty == h - 1:
                    print('INF')
                    return
                g[ty][tx] = 2
                q.put((tx, ty))
    #pprint(g)

    #ret = 0
    #for y in range(h):
    #    for x in range(w):
    #        if g[y][x] != 2:
    #            continue
    #        if x == 0 or x == w - 1 or y == 0 or y == h - 1:
    #            print('INF')
    #            return
    #        if x % 2 == 0 or y % 2 == 0:
    #            continue
    #        xx = sx[x // 2 + 1] - sx[x // 2]
    #        yy = sy[y // 2 + 1] - sy[y // 2]
    #        ret += xx * yy
    print(ret)
    return
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    A = [int()] * (N)  # type: "List[int]"
    B = [int()] * (N)  # type: "List[int]"
    C = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    D = [int()] * (M)  # type: "List[int]"
    E = [int()] * (M)  # type: "List[int]"
    F = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        D[i] = int(next(tokens))
        E[i] = int(next(tokens))
        F[i] = int(next(tokens))
    solve(N, M, A, B, C, D, E, F)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

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

N, M = map(int, readline().split())
INF = 10**9 + 1
s_X = set()
s_Y = set()
s_X.add(0)
s_X.add(INF)
s_X.add(-INF)
s_Y.add(0)
s_Y.add(INF)
s_Y.add(-INF)

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_X.add(A)
    s_X.add(B)
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)
    s_Y.add(E)
    s_Y.add(F)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

W = [[0]*maxY for _ in range(maxX)]

for A, B, C in ABC:
    A = mapX[A]
    B = mapX[B]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[j][C]= 1

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[E]
    F = mapY[F]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[D][j] = 1

#print(W)
q = deque()
q.append((mapX[0]*2, mapY[0]*2))
W[mapX[0]*2][mapY[0]*2] = 1
ans = 0
b_ans = True
while q:
    x, y = q.pop()
    if x >= maxX or x <= 0 or y >= maxY or y <= 0:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if W[nx][ny] != 1:
            if nx%2==1 and ny%2==1:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[nx][ny] = 1

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

Submission status: Time Limit Exceeded

Solution code:
# F - . (Single Dot)

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

N, M = map(int, readline().split())
INF = 10**9 + 1
s_X = set()
s_Y = set()
s_X.add(0)
s_X.add(INF)
s_X.add(-INF)
s_Y.add(0)
s_Y.add(INF)
s_Y.add(-INF)

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_X.add(A)
    s_X.add(B)
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)
    s_Y.add(E)
    s_Y.add(F)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

W = [[0]*maxY for _ in range(maxX)]

for A, B, C in ABC:
    A = mapX[A]
    B = mapX[B]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[j][C]= 1

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[E]
    F = mapY[F]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[D][j] = 1

#print(W)
q = deque()
q.append((mapX[0]*2, mapY[0]*2))
W[mapX[0]*2][mapY[0]*2] = 1
ans = 0
b_ans = True
while len(q) > 0:
    x, y = q.pop()
    if x >= maxX or x <= 0 or y >= maxY or y <= 0:
        b_ans = False
        break
    for (vx, vy) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx = x + vx
        ny = y + vy
        if W[nx][ny] != 1:
            if nx%2==1 and ny%2==1:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[nx][ny] = 1

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

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())
W = defaultdict(int)
INF = 10**9 + 1
s_X = set()
s_Y = set()
s_X.add(0)
s_X.add(INF)
s_X.add(-INF)
s_Y.add(0)
s_Y.add(INF)
s_Y.add(-INF)

def compress(s):
    ls = list(s)
    ls.sort()
    return {e: i for i, e in enumerate(ls)}

ABC = []
for i in range(N):
    A, B, C = map(int, readline().split())
    ABC.append((A, B, C))
    s_X.add(A)
    s_X.add(B)
    s_Y.add(C)

DEF = []
for i in range(M):
    D, E, F= map(int, readline().split())
    DEF.append((D, E, F))
    s_X.add(D)
    s_Y.add(E)
    s_Y.add(F)

mapX = compress(s_X)
mapY = compress(s_Y)
l_X = list(mapX.keys())
l_Y = list(mapY.keys())
maxX = len(mapX)*2
maxY = len(mapY)*2

for A, B, C in ABC:
    A = mapX[A]
    B = mapX[B]
    C = mapY[C]
    A *= 2
    B *= 2
    C *= 2
    for j in range(A, B+1):
        W[(j, C)] = -1

for D, E, F in DEF:
    D = mapX[D]
    E = mapY[E]
    F = mapY[F]
    D *= 2
    E *= 2
    F *= 2
    for j in range(E, F+1):
        W[(D, j)] = -1

#print(W)
q = deque()
q.append((mapX[0]*2, mapY[0]*2))
W[(mapX[0]*2, mapY[0]*2)] = -1
ans = 0
b_ans = True
while len(q) > 0:
    x, y = q.pop()
    if x >= maxX or x <= 0 or y >= maxY or y <= 0:
        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:
                ex = l_X[(nx+1)//2] - l_X[(nx-1)//2]
                ey = l_Y[(ny+1)//2] - l_Y[(ny-1)//2]
                ans += ex * ey
                #print(nx, ny, ans)
            q.append((nx, ny))
            W[(nx, ny)] = -1

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

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.unique(np.concatenate((C, E, F)))
ys = np.unique(np.concatenate((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)

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()
x0, y0 = (
	np.searchsorted(xs, 0, side='right'),
	np.searchsorted(ys, 0, side='right')
)
nexts.append((x0, y0))
visited = np.zeros((len(xs)+1, len(ys)+1), dtype=bool)
visited[x0, y0] = True
area = 0

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

print(area)

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.unique(np.concatenate((C, E, F)))
ys = np.unique(np.concatenate((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)

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)