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

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 not visited[ny][nx]:
					if nx < 0 or nx >= rows or ny < 0 or ny >= cols:
						return "INF"
					stack.append((ny, nx))
					visited[ny][nx] = True
	
	return str(area)

print(calc_area())

Submission status: Runtime Error

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

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

    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.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)+1):
            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)+1):
            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: Runtime Error

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

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)

    s = set()
    for x0, x1, y in vl:
        j = coy[y]
        for i in range(cox[x0], cox[x1]):
            s.add(i * h + j)
    vl = s

    s = set()
    for y0, y1, x in hl:
        i = cox[x]
        for j in range(coy[y0], coy[y1]):
            s.add(i * h + j)
    hl = s
    # print(vl,hl)

    tt = [[False] * w for _ in range(h)]
    si, sj = cox[0], coy[0]
    stack = [(si, sj)]
    tt[si][sj] = True

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

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

    while stack:
        i, j = stack.pop()

        ni, nj = i, j - 1
        if i * h + j not in vl:
            if nj == -1: inf()
            move(ni, nj)

        ni, nj = i, j + 1
        if ni * h + nj not in vl:
            if nj == w - 1: inf()
            move(ni, nj)

        ni, nj = i - 1, j
        if i * h + j not in hl:
            if ni == -1: inf()
            move(ni, nj)

        ni, nj = i + 1, j
        if ni * h + nj not in hl:
            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: Runtime Error

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)

    tt=[[9]*w for _ in range(h)]
    s=set()
    for x0,x1,y in vl:
        j=coy[y]
        for i in range(cox[x0],cox[x1]):
            s.add(i*h+j)
    vl=s
    s=set()
    for y0,y1,x in hl:
        i=cox[x]
        for j in range(coy[y0],coy[y1]):
            s.add(i*h+j)
    hl=s
    #print(vl,hl)

    si,sj=cox[0],coy[0]
    stack=[(si,sj)]
    tt[si][sj]=1

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

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

    while stack:
        i,j=stack.pop()

        ni, nj = i, j - 1
        if i * h + j not in vl:
            if nj == -1: inf()
            move(ni, nj)

        ni, nj = i, j + 1
        if ni * h + nj not in vl:
            if nj == w - 1: inf()
            move(ni, nj)

        ni, nj = i-1, j
        if i * h + j not in hl:
            if ni == -1: inf()
            move(ni, nj)

        ni, nj = i+1, j
        if ni * h + nj not in hl:
            if ni == h - 1: inf()
            move(ni, nj)

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

main()

Submission status: Runtime Error

Solution code:
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque
inpl = lambda: list(map(int,input().split()))
N, M = inpl()
hlines_orig = []
Xgrid = set()
vlines_orig = []
Ygrid = set()
for _ in range(N):
    A, B, C = inpl()
    hlines_orig.append((A,B,C))
    Ygrid.add(C)
for _ in range(M):
    D, E, F = inpl()
    vlines_orig.append((D,E,F))
    Xgrid.add(D)

Xgrid = sorted(list(Xgrid))
Ygrid = sorted(list(Ygrid))
W = len(Xgrid)
H = len(Ygrid)
areas = [[(Xgrid[w+1]-Xgrid[w])*(Ygrid[h+1]-Ygrid[h]) for h in range(H-1)] for w in range(W-1)]
walled = defaultdict(bool)
dirs = {(0,1),(1,0),(-1,0),(0,-1)}
for A, B, C in hlines_orig:
    a = bisect_right(Xgrid, A) - 1
    b = bisect_right(Xgrid, B) - 1
    c = bisect_right(Ygrid, C) - 1
    for i in range(a, b):
        if c < H-1:
            walled[((i,c),(0,-1))] = True
        if c > 0:
            walled[((i,c-1),(0,1))] = True

for D, E, F in vlines_orig:
    d = bisect_right(Ygrid, D) - 1 
    e = bisect_right(Xgrid, E) - 1 
    f = bisect_right(Xgrid, F) - 1
    for i in range(e, f):
        if d < W-1:
            walled[((d,i),(-1,0))] = True
        if d > 0:
            walled[((d-1,i),(1,0))] = True

x, y = bisect_right(Xgrid, 0) - 1, bisect_right(Ygrid, 0) - 1
if x == 0 or y == 0 or x >= W-1 or y >= H-1:
    print('INF')
    exit()
else:
    x -= 1
    y -= 1
visited = [[ False for _ in range(H-1) ] for _ in range(W-1)]
visited[x][y] = True
pool = deque([(x,y)])
ans = 0
while pool:
    x, y = pool.popleft()
    ans += areas[x][y]
    for d in dirs:
        if not walled[((x,y),d)]:
            cx, cy = x+d[0], y+d[1]
            if cx < 0 or cx >= W-1 or cy < 0 or cy >= H-1:
                print('INF')
                exit()
            elif not visited[cx][cy]:
                visited[cx][cy] = True
                pool.append((cx,cy))
print(ans)

Submission status: Runtime Error

Solution code:
from itertools import chain
from bisect import bisect_left as bisect
from math import isfinite

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

hor = [tuple(map(int,input().split())) for _ in range(N)]
ver = [tuple(map(int,input().split())) for _ in range(M)]

X = sorted(set(chain((a for a,b,c in hor), (b for a,b,c in hor), (a for a,b,c in ver))))
X = tuple(chain((-float('inf'),),*zip(X,X),(float('inf'),)))

Y = sorted(set(chain((c for a,b,c in hor), (b for a,b,c in ver), (c for a,b,c in ver))))
Y = tuple(chain((-float('inf'),),*zip(Y,Y),(float('inf'),)))

grid = [[True]*(len(Y)-1) for _ in range(len(X)-1)]

for x in range(len(X)-1):
    grid[x][0] = None
    grid[x][-1] = None
for y in range(len(Y)-1):
    grid[0][y] = None
    grid[-1][y] = None

for a,b,y in hor:
    ai,bi,yi = bisect(X,a),bisect(X,b),bisect(Y,y)
    for i in range(ai,bi+1):
        grid[i][yi] = False

for x,a,b in ver:
    xi,ai,bi = bisect(X,x),bisect(Y,a),bisect(Y,b)
    for i in range(ai,bi+1):
        grid[xi][i] = False
def dothething():
    x0,y0 = bisect(X,0), bisect(Y,0)
    stack = [(x0,y0)]
    if not grid[x0][y0]:
        print(grid[x0][y0])
        return float('nan')
    grid[x0][y0] = False
    def it():
        while stack:
            i,j = stack.pop()
            yield (X[i+1]-X[i])*(Y[j+1]-Y[j])
            for di,dj in ((0,1),(0,-1),(1,0),(-1,0)):
                ii,jj = i+di,j+dj
                if grid[ii][jj]:
                    grid[ii][jj] = False
                    stack.append((ii, jj))
                elif grid[ii][jj] is None:
                    yield float('nan')
                    return
    return sum(it())

res = dothething()
print(res if isfinite(res) else 'INF')

Submission status: Runtime Error

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)}
    xn=len(dex)
    yn=len(dey)

    tt=[[9]*yn*2 for _ in range(xn*2)]
    for x0,x1,y in vl:
        for i in range(cox[x0]*2,cox[x1]*2):
            tt[i][coy[y]*2]=0
    for y0,y1,x in hl:
        for j in range(coy[y0]*2,coy[y1]*2):
            tt[cox[x]*2][j]=0
    #p2D(tt)

    si,sj=cox[0]*2,coy[0]*2
    stack=[(si,sj)]
    tt[si][sj]=1
    dij=[(1,0),(0,1),(-1,0),(0,-1)]
    while stack:
        i,j=stack.pop()
        for di,dj in dij:
            ni,nj=i+di,j+dj
            if ni<0 or nj<0 or ni>=2*xn or nj>=2*yn:continue
            if tt[ni][nj]!=9:continue
            if ni==0 or nj==0 or ni==2*xn-1 or nj==2*yn-1:
                print("INF")
                #p2D(tt)
                exit()
            tt[ni][nj]=1
            stack.append((ni,nj))
    #p2D(tt)

    ans=0
    for i in range(1,xn*2,2):
        for j in range(1,yn*2,2):
            if tt[i][j]==1:
                ans+=(dex[i//2+1]-dex[i//2])*(dey[j//2+1]-dex[j//2])
    print(ans)

main()

Submission status: Runtime Error

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)}
    xn=len(dex)
    yn=len(dey)

    tt=[[9]*yn*2 for _ in range(xn*2)]
    for x0,x1,y in vl:
        for i in range(cox[x0]*2,cox[x1]*2):
            tt[i][coy[y]*2]=0
    for y0,y1,x in hl:
        for j in range(coy[y0]*2,coy[y1]*2):
            tt[cox[x]*2][j]=0
    p2D(tt)

    si,sj=cox[0]*2,coy[0]*2
    stack=[(si,sj)]
    tt[si][sj]=1
    dij=[(1,0),(0,1),(-1,0),(0,-1)]
    while stack:
        i,j=stack.pop()
        for di,dj in dij:
            ni,nj=i+di,j+dj
            if ni<0 or nj<0 or ni>=2*xn or nj>=2*yn:continue
            if tt[ni][nj]!=9:continue
            if ni==0 or nj==0 or ni==2*xn-1 or nj==2*yn-1:
                print("INF")
                #p2D(tt)
                exit()
            tt[ni][nj]=1
            stack.append((ni,nj))
    p2D(tt)

    ans=0
    for i in range(1,xn*2,2):
        for j in range(1,yn*2,2):
            if tt[i][j]==1:
                ans+=(dex[i//2+1]-dex[i//2])*(dey[j//2+1]-dex[j//2])
    print(ans)

main()

Submission status: Runtime Error

Solution code:
from itertools import chain
from bisect import bisect_left, bisect_right
from math import isfinite

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

hor = [tuple(map(int,input().split())) for _ in range(N)]
ver = [tuple(map(int,input().split())) for _ in range(M)]

X = sorted(set(chain((a for a,b,c in hor), (b for a,b,c in hor), (a for a,b,c in ver))))
X = tuple(chain((-float('inf'),),*zip(X,X),(float('inf'),)))

Y = sorted(set(chain((c for a,b,c in hor), (b for a,b,c in ver), (c for a,b,c in ver))))
Y = tuple(chain((-float('inf'),),*zip(Y,Y),(float('inf'),)))

grid = [[False]*(len(Y)-1) for _ in range(len(X)-1)]

for a,b,y in hor:
    ai,bi,yi = bisect_left(X,a),bisect_right(X,b),bisect_left(Y,y)
    for i in range(ai,bi-1):
        grid[i][yi] = True

for x,a,b in ver:
    xi,ai,bi = bisect_left(X,x),bisect_left(Y,a),bisect_right(Y,b)
    for i in range(ai,bi-1):
        grid[xi][i] = True

def dothething():
    x0,y0 = bisect_left(X,0), bisect_left(Y,0)
    stack = [(x0,y0)]
    grid[x0][y0] = True
    area = 0
    while stack:
        i,j = stack.pop()
        area += (X[i+1]-X[i])*(Y[j+1]-Y[j])
        if not isfinite(area):
            return None
        for di,dj in ((0,1),(0,-1),(1,0),(-1,0)):
            ii,jj = i+di,j+dj
            if not grid[ii][jj]:
                grid[ii][jj] = True
                stack.append((i+di, j+dj))
    return area

res = dothething()
print('INF' if res is None else res)

Submission status: Runtime Error

Solution code:
from itertools import chain
from bisect import bisect_left as bisect
from math import isfinite
import numpy as np

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

hor = [tuple(map(int,input().split())) for _ in range(N)]
ver = [tuple(map(int,input().split())) for _ in range(M)]

X = sorted(set(chain((a for a,b,c in hor), (b for a,b,c in hor), (a for a,b,c in ver))))
X = tuple(chain((-float('inf'),),*zip(X,X),(float('inf'),)))

Y = sorted(set(chain((c for a,b,c in hor), (b for a,b,c in ver), (c for a,b,c in ver))))
Y = tuple(chain((-float('inf'),),*zip(Y,Y),(float('inf'),)))

grid = [[False]*(len(Y)-1) for _ in range(len(X)-1)]

for a,b,y in hor:
    ai,bi,yi = bisect(X,a),bisect(X,b),bisect(Y,y)
    for i in range(ai,bi+1):
        grid[i][yi] = True

for x,a,b in ver:
    xi,ai,bi = bisect(X,x),bisect(Y,a),bisect(Y,b)
    for i in range(ai,bi+1):
        grid[xi][i] = True



def dothething():
    x0,y0 = bisect(X,0), bisect(Y,0)
    stack = [(x0,y0)]
    grid[x0][y0] = True
    area = 0
    while stack:
        i,j = stack.pop()
        area += (X[i+1]-X[i])*(Y[j+1]-Y[j])
        if not isfinite(area):
            return None
        for di,dj in ((0,1),(0,-1),(1,0),(-1,0)):
            ii,jj = i+di,j+dj
            if not grid[ii][jj]:
                grid[ii][jj] = True
                stack.append((i+di, j+dj))
    return area

res = dothething()
print('INF' if res is None else res)

Submission status: Runtime Error

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)}
    xn=len(dex)
    yn=len(dey)

    tt=[[9]*yn*2 for _ in range(xn*2)]
    for x0,x1,y in vl:
        for i in range(cox[x0]*2,cox[x1]*2+1):
            tt[i][coy[y]*2]=0
    for y0,y1,x in hl:
        for j in range(coy[y0]*2,coy[y1]*2+1):
            tt[cox[x]*2][j]=0
    #p2D(tt)

    si,sj=cox[0]*2,coy[0]*2
    stack=[(si,sj)]
    tt[si][sj]=1
    dij=[(1,0),(0,1),(-1,0),(0,-1)]
    while stack:
        i,j=stack.pop()
        for di,dj in dij:
            ni,nj=i+di,j+dj
            if ni<0 or nj<0 or ni>=2*xn or nj>=2*yn:continue
            if tt[ni][nj]!=9:continue
            if ni==0 or nj==0 or ni==2*xn-1 or nj==2*yn-1:
                print("INF")
                #p2D(tt)
                exit()
            tt[ni][nj]=1
            stack.append((ni,nj))
    #p2D(tt)

    ans=0
    for i in range(1,xn*2,2):
        for j in range(1,yn*2,2):
            if tt[i][j]==1:
                ans+=(dex[i//2+1]-dex[i//2])*(dey[j//2+1]-dex[j//2])
    print(ans)

main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict
import sys

sys.setrecursionlimit(10 ** 6)
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)}
    xn=len(dex)
    yn=len(dey)

    tt=[[-1]*yn*2 for _ in range(xn*2)]
    for x0,x1,y in vl:
        for i in range(cox[x0]*2,cox[x1]*2+1):
            tt[i][coy[y]*2]=0
    for x0,x1,y in hl:
        for i in range(coy[x0]*2,coy[x1]*2+1):
            tt[cox[y]*2][i]=0

    stack=[(cox[0]*2,coy[0]*2)]
    tt[cox[0]*2][coy[0]*2]=1
    dij=[(1,0),(0,1),(-1,0),(0,-1)]
    while stack:
        i,j=stack.pop()
        for di,dj in dij:
            ni,nj=i+di,j+dj
            if ni<0 or nj<0 or ni>=2*xn or nj>=2*yn:continue
            if tt[ni][nj]!=-1:continue
            if ni==0 or nj==0 or ni==2*xn-1 or nj==2*yn-1:
                print("INF")
                exit()
            tt[ni][nj]=1
            stack.append((ni,nj))

    ans=0
    for i in range(1,xn*2,2):
        for j in range(1,yn*2,2):
            if tt[i][j]==1:
                ans+=(dex[i//2+1]-dex[i//2])*(dey[j//2+1]-dex[j//2])
    print(ans)

main()

Submission status: Runtime Error

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][H-1-x]:
        return False
      return True
    else:
      if hor_wall[y][H-1-x]:
        return False
      return True
  else:
    if dx > 0:
      if ver_wall[x+1][W-1-y]:
        return False
      return True
    else:
      if ver_wall[x][W-1-y]:
        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]

def Base_10_to_2(X):
  if (int(X/2)):
    return Base_10_to_2(int(X/2))+str(X%2)
  return str(X%2)  

for k in range(H):
  listb = list(map(int,list(Base_10_to_2(hor_wall[k]))))
  hor_wall[k] = [0 for j in range(H-len(listb))] + listb

for k in range(W):
  listb = list(map(int,list(Base_10_to_2(ver_wall[k]))))
  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: Runtime Error

Solution code:
from collections import deque
import bisect

INF = float("inf")

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

xtic = {0}
ytic = {0}

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][H-1-x]:
        return False
      return True
    else:
      if hor_wall[y][H-1-x]:
        return False
      return True
  else:
    if dx > 0:
      if ver_wall[x+1][W-1-y]:
        return False
      return True
    else:
      if ver_wall[x][W-1-y]:
        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(len(hor_wall)):
  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(len(ver_wall)):
  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)