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: Accepted

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

h_lines = {}
v_lines = {}

for _ in range(N):
	a, b, c = map(int, input().split())
	if c in v_lines:
		v_lines[c].append((a, b))
	else:
		v_lines[c] = [(a, b)]

for _ in range(M):
	d, e, f = map(int, input().split())
	if d in h_lines:
		h_lines[d].append((e, f))
	else:
		h_lines[d] = [(e, f)]

h_lines = list(h_lines.items())
v_lines = list(v_lines.items())

h_lines.sort()
v_lines.sort()

rows = len(v_lines) - 1
cols = len(h_lines) - 1

h_walls = [[False] * rows for _ in range(cols + 1)]
v_walls = [[False] * (rows + 1) for _ in range(cols)]

for i, (y, l) in enumerate(h_lines):
	for x1, x2 in l:
		j = 0
		while j < rows:
			if x1 <= v_lines[j][0]:
				break
			j += 1
		while j < rows:
			if x2 < v_lines[j + 1][0]:
				break
			h_walls[i][j] = True
			j += 1

for j, (x, l) in enumerate(v_lines):
	for y1, y2 in l:
		i = 0
		while i < cols:
			if y1 <= h_lines[i][0]:
				break
			i += 1
		while i < cols:
			if y2 < h_lines[i + 1][0]:
				break
			v_walls[i][j] = True
			i += 1

#for i in range(cols + 1):
#	print("+" + "+".join("--" if f else "  " for f in h_walls[i]) + "+")
#	if i < cols:
#		print("  ".join("|" if f else " " for f in v_walls[i]))

def find_initial_pos():
	for i in range(cols):
		if h_lines[i][0] <= 0 and 0 <= h_lines[i + 1][0]:
			for j in range(rows):
				if v_lines[j][0] <= 0 and 0 <= v_lines[j + 1][0]:
					return (i, j)
	return None

def calc_area():
	cur = find_initial_pos()
	if cur == None:
		return "INF"
	stack = [cur]
	area = 0
	visited = [[False] * rows for _ in range(cols)]
	visited[cur[0]][cur[1]] = True
	
	search = (
		( 1,  0, lambda y, x: not h_walls[y + 1][x]),
		(-1,  0, lambda y, x: not h_walls[y][x]),
		( 0,  1, lambda y, x: not v_walls[y][x + 1]),
		( 0, -1, lambda y, x: not v_walls[y][x]),
	)
	
	while stack:
		y, x = stack.pop()
		area += (h_lines[y + 1][0] - h_lines[y][0]) * (v_lines[x + 1][0] - v_lines[x][0])
#		print(area, y, x)
		for dy, dx, check in search:
			if check(y, x):
				ny = y + dy
				nx = x + dx
#				print(">", ny, nx)
				if nx < 0 or nx >= rows or ny < 0 or ny >= cols:
					return "INF"
				if not visited[ny][nx]:
					stack.append((ny, nx))
					visited[ny][nx] = True
	
	return str(area)

print(calc_area())

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,M=map(int,input().split())
    X,Y=set([0]),set([0])
    A,B,C=[0]*N,[0]*N,[0]*N
    for i in range(N):
        A[i],B[i],C[i]=map(int,input().split())
        X.add(A[i])
        X.add(B[i])
        Y.add(C[i])
    D,E,F=[0]*M,[0]*M,[0]*M
    for i in range(M):
        D[i],E[i],F[i]=map(int,input().split())
        X.add(D[i])
        Y.add(E[i])
        Y.add(F[i])
    UX=list(X)
    UY=list(Y)
    UX.sort()
    UY.sort()
    dictx,dicty={n:i*2 for i,n in enumerate(UX)},{n:i*2 for i,n in enumerate(UY)}
    LX=[UX[i//2+1]-UX[i//2] if i%2 else 0 for i in range(len(UX)*2-1)]
    LY=[UY[i//2+1]-UY[i//2] if i%2 else 0 for i in range(len(UY)*2-1)]
    c=[[0]*(len(UX)*2-1) for _ in range(len(UY)*2-1)]
    for i in range(N):
        y=dicty[C[i]]
        for x in range(dictx[A[i]],dictx[B[i]]+1):
            c[y][x]=1
    for i in range(M):
        x=dictx[D[i]]
        for y in range(dicty[E[i]],dicty[F[i]]+1):
            c[y][x]=1
    que=deque()
    used=[[0]*len(UX)*2 for _ in range(len(UY)*2)]
    dy=[1,1,-1,-1]
    dx=[1,-1,1,-1]
    for k in range(4):
        nny,nnx=dicty[0]+dy[k],dictx[0]+dx[k]
        if 1<=nny<len(UY)*2-1 and 1<=nnx<len(UX)*2-1:
            que.append((nny,nnx))
            used[nny][nnx]=1
    ans=0
    dy=[1,0,-1,0]
    dx=[0,1,0,-1]
    while que:
        y,x=que.popleft()
        if y%2 and x%2:
            ans+=LY[y]*LX[x]
        for k in range(4):
            ny,nx=y+dy[k],x+dx[k]
            nny,nnx=ny+dy[k],nx+dx[k]
            if c[ny][nx]==0:
                if nny<0 or nny>=len(UY)*2-1 or nnx<0 or nnx>=len(UX)*2-1:
                    print('INF')
                    exit()
                if not used[nny][nnx]:
                    que.append((nny,nnx))
                    used[nny][nnx]=1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**9 + 1
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    x = []; y = []
    A = []
    D = []
    for _ in range(N):
        a,b,c = LI()
        A.append((a,b,c))
        x.append(a); x.append(b)
        y.append(c); y.append(c)
    for _ in range(M):
        d,e,f = LI()
        D.append((d,e,f))
        x.append(d); x.append(d)
        y.append(e); y.append(f)

    x.append(-INF); x.append(INF); x.append(0)
    y.append(-INF); y.append(INF); y.append(0)
    x.sort(); y.sort()
    lx = len(x); ly = len(y)
    fld = [[0] * ly for _ in range(lx)]
    for a,b,c in A:
        j = bisect.bisect_left(y,c)
        for i in range(bisect.bisect_left(x,a),bisect.bisect_left(x,b)):
            fld[i][j] = 1
    for d,e,f in D:
        i = bisect.bisect_left(x,d)
        for j in range(bisect.bisect_left(y,e),bisect.bisect_left(y,f)):
            fld[i][j] = 1

    q = []
    i = bisect.bisect_left(x,0)
    j = bisect.bisect_left(y,0)
    q.append((i,j))
    fld[i][j] = 1
    ans = 0
    while q:
        i,j = q.pop()
        ans += (x[i+1]-x[i]) * (y[j+1]-y[j])
        for di,dj in ((0,1),(1,0),(0,-1),(-1,0)):
            if 0 < i+di < lx-1 and 0 < j+dj < ly-1:
                if fld[i+di][j+dj] == 0:
                    fld[i+di][j+dj] = 1
                    q.append((i+di,j+dj))
            else:
                print('INF')
                exit(0)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    INF = 10**9 + 1
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]

    N,M = LI()
    x = []; y = []
    A = []
    D = []
    for _ in range(N):
        a,b,c = LI()
        A.append((a,b,c))
        x.append(a); x.append(b)
        y.append(c); y.append(c)
    for _ in range(M):
        d,e,f = LI()
        D.append((d,e,f))
        x.append(d); x.append(d)
        y.append(e); y.append(f)

    x.append(-INF); x.append(INF); x.append(0)
    y.append(-INF); y.append(INF); y.append(0)
    x.sort(); y.sort()
    lx = len(x); ly = len(y)
    fld = [[0] * ly for _ in range(lx)]
    for a,b,c in A:
        j = bisect.bisect_left(y,c)
        for i in range(bisect.bisect_left(x,a),bisect.bisect_left(x,b)):
            fld[i][j] = 1
    for d,e,f in D:
        i = bisect.bisect_left(x,d)
        for j in range(bisect.bisect_left(y,e),bisect.bisect_left(y,f)):
            fld[i][j] = 1

    q = collections.deque()
    i = bisect.bisect_left(x,0)
    j = bisect.bisect_left(y,0)
    q.append((i,j))
    fld[i][j] = 1
    ans = 0
    while q:
        i,j = q.popleft()
        ans += (x[i+1]-x[i]) * (y[j+1]-y[j])
        for di,dj in ((0,1),(1,0),(0,-1),(-1,0)):
            if 0 < i+di < lx-1 and 0 < j+dj < ly-1:
                if fld[i+di][j+dj] == 0:
                    fld[i+di][j+dj] = 1
                    q.append((i+di,j+dj))
            else:
                print('INF')
                exit(0)

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n, m = MI()
    xx = set([0])
    yy = set([0])
    vl = []
    hl = []
    for _ in range(n):
        a, b, c = MI()
        xx.add(a)
        xx.add(b)
        yy.add(c)
        vl.append((a, b, c))
    for _ in range(m):
        a, b, c = MI()
        xx.add(a)
        yy.add(b)
        yy.add(c)
        hl.append((b, c, a))

    dex = list(sorted(xx))
    dey = list(sorted(yy))
    cox = {x: i for i, x in enumerate(dex)}
    coy = {x: i for i, x in enumerate(dey)}
    h = len(dex)
    w = len(dey)

    vlt=[[1]*w for _ in range(h)]
    for x0, x1, y in vl:
        j = coy[y]
        for i in range(cox[x0], cox[x1]):
            vlt[i][j]=0

    hlt=[[1]*w for _ in range(h)]
    for y0, y1, x in hl:
        i = cox[x]
        for j in range(coy[y0], coy[y1]):
            hlt[i][j]=0
    #p2D(vlt)
    #print()
    #p2D(hlt)

    tt = [[False] * w for _ in range(h)]

    def inf():
        print("INF")
        exit()

    def move(ni, nj):
        if tt[ni][nj]: return
        tt[ni][nj] = True
        stack.append((ni, nj))

    si, sj = cox[0], coy[0]
    if si==h-1 or sj==w-1:inf()
    stack = [(si, sj)]
    tt[si][sj] = True
    while stack:
        i, j = stack.pop()

        ni, nj = i, j - 1
        if vlt[i][j]:
            if nj == -1: inf()
            move(ni, nj)

        ni, nj = i, j + 1
        if vlt[ni][nj]:
            if nj == w - 1: inf()
            move(ni, nj)

        ni, nj = i - 1, j
        if hlt[i][j]:
            if ni == -1: inf()
            move(ni, nj)

        ni, nj = i + 1, j
        if hlt[ni][nj]:
            if ni == h - 1: inf()
            move(ni, nj)
    #p2D(tt)

    ans = 0
    for i in range(h - 1):
        for j in range(w - 1):
            if tt[i][j]: ans += (dex[i + 1] - dex[i]) * (dey[j + 1] - dey[j])
    print(ans)

main()

Submission status: Accepted

Solution code:
#!/usr/bin/python3


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

xti = {}
yti = {}
xti[0] = -1
yti[0] = -1

lvs = []
for i in range(n):
    (a, b, c) = map(int, input().split())
    yti[a] = -1
    yti[b] = -1   
    xti[c] = -1
    lvs.append((a, b, c))

lhs = []
for i in range(m):
    (d, e, f) = map(int, input().split())
    yti[d] = -1
    xti[e] = -1   
    xti[f] = -1
    lhs.append((d, e, f))

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

xsl = len(xs) * 2
ysl = len(ys) * 2

fi = [ [ 0 for x in range(xsl) ] for y in range(ysl) ]

for (a, b, c) in lvs:
    x = xti[c] * 2
    for y in range(yti[a] * 2, yti[b] * 2 + 1):
        fi[y][x] = 2

for (d, e, f) in lhs:
    y = yti[d] * 2
    for x in range(xti[e] * 2, xti[f] * 2 + 1):
        fi[y][x] = 2

(cx, cy) = (xti[0] * 2 + 1, yti[0] * 2 + 1)
if cx < 0 or cx >= xsl - 1 or cy < 0 or cy >= ysl - 1:
    print('INF')
    exit()
q = []
q.append((cx, cy))
fi[cy][cx] = 1
s = (xs[(cx + 1) // 2] - xs[cx // 2]) * (ys[(cy + 1) // 2] - ys[cy // 2])
dxs = [0, 1, 0, -1]
dys = [1, 0, -1, 0]

while q:
    (x, y) = q.pop(-1)

    for i in range(4):
        cx = x + dxs[i] * 2
        cy = y + dys[i] * 2
    
        if fi[cy][cx] != 0:
            continue

        pcx = x + dxs[i]
        pcy = y + dys[i]
        if fi[pcy][pcx] == 2:
            continue
        
        
        if cx < 0 or cx >= xsl - 1 or cy < 0 or cy >= ysl - 1:
            print('INF')
            exit()

        fi[cy][cx] = 1
        s += (xs[(cx + 1) // 2] - xs[cx // 2]) * (ys[(cy + 1) // 2] - ys[cy // 2])
        q.append((cx, cy))

print(s)

#for xl in fi:
#    print(xl)

Submission status: Accepted

Solution code:
#!/usr/bin/python3


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

xti = {}
yti = {}
xti[0] = -1
yti[0] = -1

lvs = []
for i in range(n):
    (a, b, c) = map(int, input().split())
    yti[a] = -1
    yti[b] = -1   
    xti[c] = -1
    lvs.append((a, b, c))

lhs = []
for i in range(m):
    (d, e, f) = map(int, input().split())
    yti[d] = -1
    xti[e] = -1   
    xti[f] = -1
    lhs.append((d, e, f))

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

xsl = (len(xs) + 1) * 2
ysl = (len(ys) + 1) * 2

fi = [ [ 0 for x in range(xsl) ] for y in range(ysl) ]

for (a, b, c) in lvs:
    x = xti[c] * 2 + 1
    for y in range(yti[a] * 2 + 1, yti[b] * 2 + 1 + 1):
        fi[y][x] = 2

for (d, e, f) in lhs:
    y = yti[d] * 2 + 1
    for x in range(xti[e] * 2 + 1, xti[f] * 2 + 1 + 1):
        fi[y][x] = 2

(cx, cy) = (xti[0] * 2, yti[0] * 2)
q = []
q.append((cx, cy))
fi[cy][cx] = 1
s = (xs[cx // 2] - xs[(cx - 1)// 2]) * (ys[cy // 2] - ys[(cy - 1) // 2])
dxs = [0, 1, 0, -1]
dys = [1, 0, -1, 0]

while q:
    (x, y) = q.pop(-1)

    for i in range(4):
        cx = x + dxs[i] * 2
        cy = y + dys[i] * 2
    
        if fi[cy][cx] != 0:
            continue

        pcx = x + dxs[i]
        pcy = y + dys[i]
        if fi[pcy][pcx] == 2:
            continue
        
        
        if cx == 0 or cx == xsl - 2 or cy == 0 or cy == ysl - 2:
            print('INF')
            exit()

        fi[cy][cx] = 1
        s += (xs[cx // 2] - xs[(cx - 1)// 2]) * (ys[cy // 2] - ys[(cy - 1) // 2])
        q.append((cx, cy))

print(s)

#for xl in fi:
#    print(xl)

Submission status: Accepted

Solution code:
import sys
import numpy as np

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

INF = 10**9 + 1

def precompute(N, M, data):
    data = data.reshape(-1, 3)
    A, B, C = data[:N].T
    D, E, F = data[N:].T
    X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))
    Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))
    A = np.searchsorted(X, A)
    B = np.searchsorted(X, B)
    D = np.searchsorted(X, D)
    C = np.searchsorted(Y, C)
    E = np.searchsorted(Y, E)
    F = np.searchsorted(Y, F)
    return A, B, C, D, E, F, X, Y

def solve(A, B, C, D, E, F, X, Y):
    H, W = len(X), len(Y)
    N = H * W
    DX = X[1:] - X[:-1]
    DY = Y[1:] - Y[:-1]

    def set_ng(A, B, C, D, E, F, H, W):
        ng = np.zeros((H * W, 4), np.bool_)

        for i in range(len(A)):
            for x in range(A[i], B[i]):
                v = x * W + C[i]
                ng[v][1] = 1
                ng[v - 1][0] = 1

        for i in range(len(D)):
            for y in range(E[i], F[i]):
                v = D[i] * W + y
                ng[v][3] = 1
                ng[v - W][2] = 1
        return ng

    ng = set_ng(A, B, C, D, E, F, H, W)
    x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)
    v0 = x0 * W + y0
    
    def area(x):
        x, y = divmod(x, W)
        return DX[x] * DY[y]

    visited = np.zeros(N, np.bool_)
    visited[v0] = 1
    stack = [v0]
    ret = area(v0)

    def push(x):
        nonlocal ret
        stack.append(x)
        visited[x] = 1
        ret += area(x)

    def pop():
        return stack.pop()

    move = (1, -1, W, -W)
    while stack:
        v = pop()
        for i in range(4):
            if ng[v][i]:
                continue
            w = v + move[i]
            if visited[w]:
                continue
            x, y = divmod(w, W)
            if x == 0 or x == H - 1 or y == 0 or y == W - 1:
                return 0
            push(w)
    return ret

def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    signature = '(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:])'
    cc.export('solve', signature)(solve)
    cc.compile()

if sys.argv[-1] == 'ONLINE_JUDGE':
    cc_export()
    exit()

from my_module import solve

N, M = map(int, readline().split())
data = np.int64(read().split())

x = solve(*precompute(N, M, data))
if x == 0:
    print('INF')
else:
    print(x)

Submission status: Accepted

Solution code:
import sys
import numpy as np

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

INF = 10**9 + 1

def precompute(N, M, data):
    data = data.reshape(-1, 3)
    A, B, C = data[:N].T
    D, E, F = data[N:].T
    X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))
    Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))
    A = np.searchsorted(X, A)
    B = np.searchsorted(X, B)
    D = np.searchsorted(X, D)
    C = np.searchsorted(Y, C)
    E = np.searchsorted(Y, E)
    F = np.searchsorted(Y, F)
    return A, B, C, D, E, F, X, Y

def solve(A, B, C, D, E, F, X, Y):
    H, W = len(X), len(Y)
    N = H * W
    DX = X[1:] - X[:-1]
    DY = Y[1:] - Y[:-1]

    def set_ng(A, B, C, D, E, F, H, W):
        ng = np.zeros((H * W, 4), np.bool_)

        for i in range(len(A)):
            for x in range(A[i], B[i]):
                v = x * W + C[i]
                ng[v][1] = 1
                ng[v - 1][0] = 1

        for i in range(len(D)):
            for y in range(E[i], F[i]):
                v = D[i] * W + y
                ng[v][3] = 1
                ng[v - W][2] = 1
        return ng

    ng = set_ng(A, B, C, D, E, F, H, W)
    x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)
    v0 = x0 * W + y0
    visited = np.zeros(N, np.bool_)
    visited[v0] = 1
    stack = np.empty(N, np.int32)
    p = 0
    ret = 0

    def area(x):
        x, y = divmod(x, W)
        return DX[x] * DY[y]

    def push(x):
        nonlocal p, ret
        stack[p] = x
        visited[x] = 1
        ret += area(x)
        p += 1

    def pop():
        nonlocal p
        p -= 1
        return stack[p]

    push(v0)
    move = (1, -1, W, -W)
    while p:
        v = pop()
        for i in range(4):
            if ng[v][i]:
                continue
            w = v + move[i]
            if visited[w]:
                continue
            x, y = divmod(w, W)
            if x == 0 or x == H - 1 or y == 0 or y == W - 1:
                return 0
            push(w)
    return ret

def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    signature = '(i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:],i8[:])'
    cc.export('solve', signature)(solve)
    cc.compile()

if sys.argv[-1] == 'ONLINE_JUDGE':
    cc_export()
    exit()

from my_module import solve

N, M = map(int, readline().split())
data = np.int64(read().split())

x = solve(*precompute(N, M, data))
if x == 0:
    print('INF')
else:
    print(x)

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    from collections import deque
    input = sys.stdin.buffer.readline

    def fin():
        print("INF")
        exit()

    N, M = map(int, input().split())
    X = set()
    X.add(-10**9-1)
    X.add(0)
    X.add(10**9+1)
    Y = set()
    Y.add(-10**9-1)
    Y.add(0)
    Y.add(10**9+1)
    ABC = []
    DEF = []
    for _ in range(N):
        a, b, c = map(int, input().split())
        X.add(a)
        X.add(b)
        Y.add(c)
        ABC.append((a, b, c))
    for _ in range(M):
        d, e, f = map(int, input().split())
        X.add(d)
        Y.add(e)
        Y.add(f)
        DEF.append((d, e, f))
    X = sorted(list(X))
    Y = sorted(list(Y))
    x2i = {x: i for i, x in enumerate(X)}
    y2j = {y: j for j, y in enumerate(Y)}
    LX = len(X)
    LY = len(Y)
    ABCwall = [set() for _ in range(LY)]
    for a, b, c in ABC:
        i0 = x2i[a]
        i1 = x2i[b]
        j = y2j[c]
        for i in range(i0, i1):
            ABCwall[j].add(i)
    DEFwall = [set() for _ in range(LX)]
    for d, e, f in DEF:
        i = x2i[d]
        j0 = y2j[e]
        j1 = y2j[f]
        for j in range(j0, j1):
            DEFwall[i].add(j)

    ii = x2i[0]
    jj = y2j[0]
    que = deque()
    que.append((ii, jj))
    seen = [[0] * (LY-1) for _ in range(LX-1)]
    seen[ii][jj] = 1
    ans = 0
    while que:
        i, j = que.popleft()
        ans += (X[i+1] - X[i]) * (Y[j+1] - Y[j])

        # x inc
        if j not in DEFwall[i+1]:
            if i == LX - 2:
                fin()
            if not seen[i+1][j]:
                que.append((i+1, j))
                seen[i+1][j] = 1

        # x dec
        if j not in DEFwall[i]:
            if i == 1:
                fin()
            if not seen[i-1][j]:
                que.append((i-1, j))
                seen[i-1][j] = 1

        # y inc
        if i not in ABCwall[j+1]:
            if j == LY - 2:
                fin()
            if not seen[i][j+1]:
                que.append((i, j+1))
                seen[i][j+1] = 1

        # y dec
        if i not in ABCwall[j]:
            if j == 1:
                fin()
            if not seen[i][j-1]:
                que.append((i, j-1))
                seen[i][j-1] = 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
import bisect

INF = float("inf")

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

xtic = {0,-INF,INF}
ytic = {0,-INF,INF}

hor = []
for _ in range(N):
  a,b,c = map(int,input().split())
  hor.append((c,a,b))
  xtic.add(a)
  xtic.add(b)
  ytic.add(c)
  
ver = []
for _ in range(M):
  d,e,f = map(int,input().split())
  ver.append((d,e,f))
  xtic.add(d)
  ytic.add(e)
  ytic.add(f)

xtic = list(xtic)
ytic = list(ytic)
xtic.sort()
ytic.sort()
xdic = {xtic[i]:i+1 for i in range(len(xtic))}
ydic = {ytic[i]:i+1 for i in range(len(ytic))}

gyaku_xdic = {xdic[k]:k for k in xdic}
gyaku_ydic = {ydic[k]:k for k in ydic}

hor.sort()
ver.sort()

hor_dic = {}
ver_dic = {}

now = None
for c,a,b in hor:
  c,a,b = ydic[c],xdic[a],xdic[b]
  if c != now:
    hor_dic[c] = (1<<b) - (1<<a)
  else:
    hor_dic[c] |= (1<<b) - (1<<a)
  now = c

now = None
for d,e,f in ver:
  d,e,f = xdic[d],ydic[e],ydic[f]
  if d != now:
    ver_dic[d] = (1<<f) - (1<<e)
  else:
    ver_dic[d] |= (1<<f) - (1<<e)
  now = d

def is_connected(x,y,dx,dy):
  if dx == 0:
    if dy > 0:
      if (hor_wall[y+1]>>x)&1:
        return False
      return True
    else:
      if (hor_wall[y]>>x)&1:
        return False
      return True
  else:
    if dx > 0:
      if (ver_wall[x+1]>>y)&1:
        return False
      return True
    else:
      if (ver_wall[x]>>y)&1:
        return False
      return True
      
def calc_area(x,y):
  X = gyaku_xdic[x+1] - gyaku_xdic[x]
  Y = gyaku_ydic[y+1] - gyaku_ydic[y]
  return X*Y

offset = [(1,0),(0,1),(-1,0),(0,-1)]
x0 = bisect.bisect(xtic,0)
y0 = bisect.bisect(ytic,0)
W,H = len(xtic)+1 ,len(ytic)+1

hor_wall = [0 for i in range(H)]
ver_wall = [0 for i in range(W)]

for k in hor_dic:
  hor_wall[k] = hor_dic[k]
for k in ver_dic:
  ver_wall[k] = ver_dic[k]

d = [[0 for i in range(W)] for j in range(H)]
d[y0][x0] = 1
q = deque([(x0,y0)])

area = 0

while q:
  x,y = q.pop()
  area += calc_area(x,y)
  for dx,dy in offset:
    nx,ny = x+dx,y+dy
    if 0<=nx<W and 0<=ny<H:
      if is_connected(x,y,dx,dy):
        if nx == 0 or ny == 0 or nx == W-1 or ny == H-1:
          print("INF")
          exit()
        if d[ny][nx] == 0:
          d[ny][nx] = 1
          q.append((nx,ny))

print(area)

Submission status: Accepted

Solution code:
from collections import deque
import bisect

INF = float("inf")

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

xtic = {0,-INF,INF}
ytic = {0,-INF,INF}

hor = []
for _ in range(N):
  a,b,c = map(int,input().split())
  hor.append((c,a,b))
  xtic.add(a)
  xtic.add(b)
  ytic.add(c)
  
ver = []
for _ in range(M):
  d,e,f = map(int,input().split())
  ver.append((d,e,f))
  xtic.add(d)
  ytic.add(e)
  ytic.add(f)

xtic = list(xtic)
ytic = list(ytic)
xtic.sort()
ytic.sort()
xdic = {xtic[i]:i+1 for i in range(len(xtic))}
ydic = {ytic[i]:i+1 for i in range(len(ytic))}

gyaku_xdic = {xdic[k]:k for k in xdic}
gyaku_ydic = {ydic[k]:k for k in ydic}

hor.sort()
ver.sort()

hor_dic = {}
ver_dic = {}

now = None
for c,a,b in hor:
  c,a,b = ydic[c],xdic[a],xdic[b]
  if c != now:
    hor_dic[c] = (1<<b) - (1<<a)
  else:
    hor_dic[c] |= (1<<b) - (1<<a)
  now = c

now = None
for d,e,f in ver:
  d,e,f = xdic[d],ydic[e],ydic[f]
  if d != now:
    ver_dic[d] = (1<<f) - (1<<e)
  else:
    ver_dic[d] |= (1<<f) - (1<<e)
  now = d

def is_connected(x,y,dx,dy):
  if dx == 0:
    if dy > 0:
      if (hor_wall[y+1]>>x)&1:
        return False
      return True
    else:
      if (hor_wall[y]>>x)&1:
        return False
      return True
  else:
    if dx > 0:
      if (ver_wall[x+1]>>y)&1:
        return False
      return True
    else:
      if (ver_wall[x]>>y)&1:
        return False
      return True
      
def calc_area(x,y):
  X = gyaku_xdic[x+1] - gyaku_xdic[x]
  Y = gyaku_ydic[y+1] - gyaku_ydic[y]
  return X*Y

offset = [(1,0),(0,1),(-1,0),(0,-1)]
x0 = bisect.bisect(xtic,0)
y0 = bisect.bisect(ytic,0)
W,H = len(xtic)+1 ,len(ytic)+1

hor_wall = [0 for i in range(H)]
ver_wall = [0 for i in range(W)]

for k in hor_dic:
  hor_wall[k] = hor_dic[k]
for k in ver_dic:
  ver_wall[k] = ver_dic[k]
"""
for k in range(H):
  listb = list(map(int,list(bin(hor_wall[k])[2:])))
  hor_wall[k] = [0 for j in range(H-len(listb))] + listb

for k in range(W):
  listb = list(map(int,list(bin(ver_wall[k])[2:])))
  ver_wall[k] = [0 for j in range(W-len(listb))] + listb  
"""

d = [[0 for i in range(W)] for j in range(H)]
d[y0][x0] = 1
q = deque([(x0,y0)])

area = 0

while q:
  x,y = q.pop()
  area += calc_area(x,y)
  for dx,dy in offset:
    nx,ny = x+dx,y+dy
    if 0<=nx<W and 0<=ny<H:
      if is_connected(x,y,dx,dy):
        if nx == 0 or ny == 0 or nx == W-1 or ny == H-1:
          print("INF")
          exit()
        if d[ny][nx] == 0:
          d[ny][nx] = 1
          q.append((nx,ny))

print(area)

Submission status: Accepted

Solution code:
import sys
import numpy as np

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

INF = 10**9 + 1

def precompute(N, M, data):
    data = data.reshape(-1, 3)
    A, B, C = data[:N].T
    D, E, F = data[N:].T
    X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))
    Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))
    A = np.searchsorted(X, A)
    B = np.searchsorted(X, B)
    D = np.searchsorted(X, D)
    C = np.searchsorted(Y, C)
    E = np.searchsorted(Y, E)
    F = np.searchsorted(Y, F)
    return A, B, C, D, E, F, X, Y

def solve(A, B, C, D, E, F, X, Y):
    H, W = len(X), len(Y)
    N = H * W
    DX = X[1:] - X[:-1]
    DY = Y[1:] - Y[:-1]

    def set_ng(A, B, C, D, E, F, H, W):
        ng = np.zeros((H * W, 4), np.bool_)

        for i in range(len(A)):
            for x in range(A[i], B[i]):
                v = x * W + C[i]
                ng[v][1] = 1
                ng[v - 1][0] = 1

        for i in range(len(D)):
            for y in range(E[i], F[i]):
                v = D[i] * W + y
                ng[v][3] = 1
                ng[v - W][2] = 1
        return ng

    ng = set_ng(A, B, C, D, E, F, H, W)
    x0, y0 = np.searchsorted(X, 0), np.searchsorted(Y, 0)
    v0 = x0 * W + y0
    visited = np.zeros(N, np.bool_)
    visited[v0] = 1
    stack = np.empty(N, np.int32)
    p = 0
    ret = 0

    def area(x):
        x, y = divmod(x, W)
        return DX[x] * DY[y]

    def push(x):
        nonlocal p, ret
        stack[p] = x
        visited[x] = 1
        ret += area(x)
        p += 1

    def pop():
        nonlocal p
        p -= 1
        return stack[p]

    push(v0)
    move = (1, -1, W, -W)
    while p:
        v = pop()
        for i in range(4):
            if ng[v][i]:
                continue
            w = v + move[i]
            if visited[w]:
                continue
            x, y = divmod(w, W)
            if x == 0 or x == H - 1 or y == 0 or y == W - 1:
                return 0
            push(w)
    return ret

def cc_export():
    from numba.pycc import CC
    cc = CC('my_module')
    signature = '(i8[::1],i8[::1],i8[::1],i8[::1],i8[::1],i8[::1],i8[::1],i8[::1])'
    cc.export('solve', signature)(solve)
    cc.compile()

if sys.argv[-1] == 'ONLINE_JUDGE':
    cc_export()
    exit()

from my_module import solve

N, M = map(int, readline().split())
data = np.int64(read().split())

x = solve(*precompute(N, M, data))
if x == 0:
    print('INF')
else:
    print(x)