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:
def main():
    from collections import deque
    import sys
    sys.setrecursionlimit(10**8)
    input = sys.stdin.readline
    n,m = map(int,input().split())
    xl = set([0])
    yl = set([0])
    nl = []
    ml = []
    for i in range(n):
        a,b,c = map(int,input().split())
        xl |= set([a,b])
        yl.add(c)
        nl.append([a,b,c])
    for i in range(m):
        c,a,b = map(int,input().split())
        yl |= set([a,b])
        xl.add(c)
        ml.append([a,b,c])

    xl = list(xl)
    xl.sort()
    yl = list(yl)
    yl.sort()
    dx = {}
    dy = {}
    for i in range(len(xl)):
        dx[xl[i]] = i

    for i in range(len(yl)):
        dy[yl[i]] = i

    h = len(xl)*2
    w = len(yl)*2
    d = [[0]*w for i in range(h)]

    for a,b,c in nl:
        s = dx[a]*2
        g = dx[b]*2
        t = dy[c]*2
        
        for x in range(s,g+1):
            d[x][t] = -1

    for a,b,c in ml:
        s = dy[a]*2
        g = dy[b]*2
        t = dx[c]*2
        
        for y in range(s,g+1):
            d[t][y] = -1


    def bfs(x,y):
        ans = 0
        dtx = [1,-1,0,0]
        dty = [0,0,1,-1]

        sx = dx[x]*2
        sy = dy[y]*2
        q = deque([])
        q.append((sx,sy))
        d[sx][sy] = 1
        while q:
            bx,by = q.popleft()

            for i in range(4):
                nx = bx+dtx[i]
                ny = by+dty[i]

                if 0 <= nx < h and 0 <= ny < w and d[nx][ny] == 0:
                    if nx == 0 or ny == 0 or nx == h-1 or ny == w-1:
                        print("INF")
                        exit()
                    d[nx][ny] = 1
                    if nx%2 != 0 and ny%2 != 0:
                        ax = xl[nx//2+1]-xl[nx//2]
                        ay = yl[ny//2+1]-yl[ny//2]
                        ans += ax*ay
                    q.append((nx,ny))
        print(ans)

    bfs(0,0)
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
ABC = [list(map(int,input().split())) for _ in [0]*N ]
DEF = [list(map(int,input().split())) for _ in [0]*M ]

X = [0]*3003
Y = [0]*3003
INF = 10**9 + 10
X[-1] = -INF
Y[-1] = -INF
X[-2] = INF
Y[-2] = INF
i = 0
j = 0
for a,b,c in ABC:
    X[i] = a
    X[i+1] = b
    Y[j] = c
    i += 2
    j += 1
for d,e,f in DEF:
    X[i] = d
    Y[j] = e
    Y[j+1] = f
    i += 1
    j += 2
X = sorted(set(X))
Y = sorted(set(Y))
Xdict = {x:i for i,x in enumerate(X)}
Ydict = {y:i for i,y in enumerate(Y)}

nx = len(X)
ny = len(Y)
nxy = nx * ny
E = {(x,y):{(X[i-1],y),(X[i+1],y),(x,Y[j-1]),(x,Y[j+1])} for i,x in enumerate(X[1:-1],1) for j,y in enumerate(Y[1:-1],1)}

E = [[15]*nx for _ in [0]*ny]

E[0] = [7]*nx
E[-1] = [13]*nx
for i in range(ny):
    E[i][0] -= 4
    E[i][-1] -= 1

for a,b,c in ABC:
    y1 = Ydict[c]
    y0 = y1-1
    for x in range(Xdict[a],Xdict[b]):
        E[y0][x] &= 15-2
        E[y1][x] &= 15-8

for d,e,f in DEF:
    x1 = Xdict[d]
    x0 = x1-1
    for y in range(Ydict[e],Ydict[f]):
        E[y][x0] &= 15-1
        E[y][x1] &= 15-4

dX = [x2-x for x,x2 in zip(X,X[1:])]
dY = [y2-y for y,y2 in zip(Y,Y[1:])]
burst = False
x0 = Xdict[0]
y0 = Ydict[0]
ans = dX[x0]*dY[y0]
done = [[False]*nx for _ in [0]*ny]
done[y0][x0] = True
q = [(x0,y0)]
dxy = [(1,0),(0,1),(-1,0),(0,-1)]
while q:
    qq = []
    for x,y in q:
        e = E[y][x]
        for i in range(4):
            if (e>>i)&1 == 0 : continue
            dx,dy = dxy[i]
            jx = x+dx
            jy = y+dy
            if done[jy][jx]:continue
            done[jy][jx] = True

            if jx==0 or jx==nx-1 or jy==0 or jy==ny-1:
                burst = True
                ans = "INF"
                qq = []
                break
            ans += dX[jx]*dY[jy]
            qq.append((jx,jy))
        if burst:break
    q = qq

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
ABC = [0] * N
for i in range(N):
    ABC[i] = list(map(int, input().split()))
DEF = [0] * M
for i in range(M):
    DEF[i] = list(map(int, input().split()))

# 座標圧縮
x_co = {-10**9-1, 10**9+1}
y_co = {-10**9-1, 10**9+1}
for i in range(N):
    x_co.add(ABC[i][0])
    x_co.add(ABC[i][1])
    y_co.add(ABC[i][2])
for i in range(M):
    x_co.add(DEF[i][0])
    y_co.add(DEF[i][1])
    y_co.add(DEF[i][2])

x_co = sorted(list(x_co))
y_co = sorted(list(y_co))
xL = len(x_co) - 1
yL = len(y_co) - 1
x_co_d = {x_co[i]: i for i in range(xL+1)}
y_co_d = {y_co[i]: i for i in range(yL+1)}

# 柵の存在
s_ex_tate = [[False] * xL for _ in range(yL+1)]
s_ex_yoko = [[False] * yL for _ in range(xL+1)]
for i in range(N):
    a = x_co_d[ABC[i][0]]
    b = x_co_d[ABC[i][1]]
    c = y_co_d[ABC[i][2]]
    s_ex_tate[c][a:b] = [True] * (b-a)
for i in range(M):
    d = x_co_d[DEF[i][0]]
    e = y_co_d[DEF[i][1]]
    f = y_co_d[DEF[i][2]]
    s_ex_yoko[d][e:f] = [True] * (f-e)

# 初期位置
for i in range(xL):
    if x_co[i+1] > 0:
        xf = [i]
        break
    if x_co[i+1] == 0:
        xf = [i, i+1]
        break
for i in range(yL):
    if y_co[i+1] > 0:
        yf = [i]
        break
    if y_co[i+1] == 0:
        yf = [i, i+1]
        break

def sq(x, y):
    return (x_co[x+1]-x_co[x]) * (y_co[y+1]-y_co[y])

# 探索
Q = []
houmon = [[False] * yL for _ in range(xL)]
ans = 0
is_inf = False
for x in xf:
    for y in yf:
        houmon[x][y] = True
        Q.append((x, y))

while Q:
    x, y = Q.pop()
    if x in [0, xL-1] or y in [0, yL-1]:
        is_inf = True
        break
    ans += sq(x, y)
    if (not houmon[x-1][y]) and (not s_ex_yoko[x][y]):
        houmon[x-1][y] = True
        Q.append((x-1, y))
    if (not houmon[x][y-1]) and (not s_ex_tate[y][x]):
        houmon[x][y-1] = True
        Q.append((x, y-1))
    if (not houmon[x+1][y]) and (not s_ex_yoko[x+1][y]):
        houmon[x+1][y] = True
        Q.append((x+1, y))
    if (not houmon[x][y+1]) and (not s_ex_tate[y+1][x]):
        houmon[x][y+1] = True
        Q.append((x, y+1))
    
if is_inf:
    print('INF')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    sys.setrecursionlimit(10**8)
    input = sys.stdin.readline
    n,m = map(int,input().split())
    xl = set([0])
    yl = set([0])
    nl = []
    ml = []
    for i in range(n):
        a,b,c = map(int,input().split())
        xl.add(a)
        xl.add(b)
        yl.add(c)
        nl.append([a,b,c])
    for i in range(m):
        c,a,b = map(int,input().split())
        yl.add(a)
        yl.add(b)
        xl.add(c)
        ml.append([a,b,c])

    xl = sorted(list(xl))
    yl = sorted(list(yl))
    dx = {}
    dy = {}
    for i in range(len(xl)):
        dx[xl[i]] = i

    for i in range(len(yl)):
        dy[yl[i]] = i

    h = len(xl)*2
    w = len(yl)*2
    d = [[0]*w for i in range(h)]

    for a,b,c in nl:
        s = dx[a]*2
        g = dx[b]*2
        t = dy[c]*2
        
        for x in range(s,g+1):
            d[x][t] = -1

    for a,b,c in ml:
        s = dy[a]*2
        g = dy[b]*2
        t = dx[c]*2
        
        for y in range(s,g+1):
            d[t][y] = -1


    def bfs(x,y):
        ans = 0
        dtx = [1,-1,0,0]
        dty = [0,0,1,-1]

        sx = dx[x]*2
        sy = dy[y]*2
        q = deque([])
        q.append((sx,sy))
        d[sx][sy] = 1
        while q:
            bx,by = q.popleft()

            for i in range(4):
                nx = bx+dtx[i]
                ny = by+dty[i]

                if 0 <= nx < h and 0 <= ny < w and d[nx][ny] == 0:
                    if nx == 0 or ny == 0 or nx == h-1 or ny == w-1:
                        print("INF")
                        exit()
                    d[nx][ny] = 1
                    if nx%2 != 0 and ny%2 != 0:
                        ax = xl[nx//2+1]-xl[nx//2]
                        ay = yl[ny//2+1]-yl[ny//2]
                        ans += ax*ay
                    q.append((nx,ny))
        print(ans)

    bfs(0,0)
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

n,m=l_in()

yoko=[]
tate=[]
xs=set([0])
ys=set([0])

# yoko

for _ in range(n):
    a,b,c=l_in()
    yoko.append((a,b,c))
    xs.add(a)
    xs.add(b)
    ys.add(c)

for _ in range(m):
    d,e,f=l_in()
    tate.append((d,e,f))
    xs.add(d)
    ys.add(e)
    ys.add(f)

xdict={}
ydict={}

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

for i, x in enumerate(sorted(xs)):
    xdict[x] = i
for i, y in enumerate(sorted(ys)):
    ydict[y] = i

h = 2*len(xs)
w = 2*len(ys)
M = [[0]*w for _ in range(h)]

for a,b,c in yoko:
    a,b,c = xdict[a]*2, xdict[b]*2, ydict[c]*2
    for x in range(a,b+1):
        M[x][c] = 1

for d,e,f in tate:
    d,e,f = xdict[d]*2, ydict[e]*2, ydict[f]*2
    for y in range(e,f+1):
        M[d][y] = 1

from collections import deque
q=deque()

Dx=[1,0,-1,0]
Dy=[0,1,0,-1]

q.append((xdict[0]*2, ydict[0]*2))

res = 0

while len(q) > 0:
    x,y = q.popleft()
    for dx, dy in zip(Dx,Dy):
        x2 = x+dx
        y2 = y+dy
        if M[x2][y2] != 0:
            continue
        M[x2][y2] = 2
        if x2 ==0 or x2 == h-1 or y2 == 0 or y2 == w-1:
            print("INF")
            exit()
        q.append((x2,y2))
        if x2%2 == 0 or y2%2 == 0:
            continue
        res += (xs[x2//2+1] - xs[x2//2])*(ys[y2//2+1] - ys[y2//2])
        
print(res)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    sys.setrecursionlimit(10**8)
    n,m = map(int,input().split())
    xl = set([0])
    yl = set([0])
    nl = []
    ml = []
    for i in range(n):
        a,b,c = map(int,input().split())
        xl.add(a)
        xl.add(b)
        yl.add(c)
        nl.append([a,b,c])
    for i in range(m):
        c,a,b = map(int,input().split())
        yl.add(a)
        yl.add(b)
        xl.add(c)
        ml.append([a,b,c])

    xl = sorted(list(xl))
    yl = sorted(list(yl))
    dx = {}
    dy = {}
    for i in range(len(xl)):
        dx[xl[i]] = i

    for i in range(len(yl)):
        dy[yl[i]] = i

    h = len(xl)*2
    w = len(yl)*2
    d = [[0]*w for i in range(h)]

    for a,b,c in nl:
        s = dx[a]*2
        g = dx[b]*2
        t = dy[c]*2
        
        for x in range(s,g+1):
            d[x][t] = -1

    for a,b,c in ml:
        s = dy[a]*2
        g = dy[b]*2
        t = dx[c]*2
        
        for y in range(s,g+1):
            d[t][y] = -1


    def bfs(x,y):
        ans = 0
        dtx = [1,-1,0,0]
        dty = [0,0,1,-1]

        sx = dx[x]*2
        sy = dy[y]*2
        q = deque([])
        q.append((sx,sy))
        d[sx][sy] = 1
        while q:
            bx,by = q.popleft()

            for i in range(4):
                nx = bx+dtx[i]
                ny = by+dty[i]

                if 0 <= nx < h and 0 <= ny < w and d[nx][ny] == 0:
                    if nx == 0 or ny == 0 or nx == h-1 or ny == w-1:
                        print("INF")
                        exit()
                    d[nx][ny] = 1
                    if nx%2 != 0 and ny%2 != 0:
                        ax = xl[nx//2+1]-xl[nx//2]
                        ay = yl[ny//2+1]-yl[ny//2]
                        ans += ax*ay
                    q.append((nx,ny))
        print(ans)

    bfs(0,0)
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**8)
n,m = map(int,input().split())
xl = set([0])
yl = set([0])
nl = []
ml = []
for i in range(n):
    a,b,c = map(int,input().split())
    xl.add(a)
    xl.add(b)
    yl.add(c)
    nl.append([a,b,c])
for i in range(m):
    c,a,b = map(int,input().split())
    yl.add(a)
    yl.add(b)
    xl.add(c)
    ml.append([a,b,c])

xl = sorted(list(xl))
yl = sorted(list(yl))
dx = {}
dy = {}
for i in range(len(xl)):
    dx[xl[i]] = i

for i in range(len(yl)):
    dy[yl[i]] = i

h = len(xl)*2
w = len(yl)*2
d = [[0]*w for i in range(h)]

for a,b,c in nl:
    s = dx[a]*2
    g = dx[b]*2
    t = dy[c]*2
    
    for x in range(s,g+1):
        d[x][t] = -1

for a,b,c in ml:
    s = dy[a]*2
    g = dy[b]*2
    t = dx[c]*2
    
    for y in range(s,g+1):
        d[t][y] = -1


def bfs(x,y):
    ans = 0
    dtx = [1,-1,0,0]
    dty = [0,0,1,-1]

    sx = dx[x]*2
    sy = dy[y]*2
    q = deque([])
    q.append((sx,sy))
    d[sx][sy] = 1
    while q:
        bx,by = q.popleft()

        for i in range(4):
            nx = bx+dtx[i]
            ny = by+dty[i]

            if 0 <= nx < h and 0 <= ny < w and d[nx][ny] == 0:
                if nx == 0 or ny == 0 or nx == h-1 or ny == w-1:
                    print("INF")
                    exit()
                d[nx][ny] = 1
                if nx%2 != 0 and ny%2 != 0:
                    ax = xl[nx//2+1]-xl[nx//2]
                    ay = yl[ny//2+1]-yl[ny//2]
                    ans += ax*ay
                q.append((nx,ny))
    print(ans)

bfs(0,0)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

n,m=l_in()

yoko=[]
tate=[]
xs=set([0])
ys=set([0])

# yoko

for _ in range(n):
    a,b,c=l_in()
    yoko.append((a,b,c))
    xs.add(a)
    xs.add(b)
    ys.add(c)

for _ in range(m):
    d,e,f=l_in()
    tate.append((d,e,f))
    xs.add(d)
    ys.add(e)
    ys.add(f)

xdict={}
ydict={}

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

for i, x in enumerate(sorted(xs)):
    xdict[x] = i
for i, y in enumerate(sorted(ys)):
    ydict[y] = i

h = 2*len(xs)
w = 2*len(ys)
M = [[0]*w for _ in range(h)]

for a,b,c in yoko:
    a,b,c = xdict[a]*2, xdict[b]*2, ydict[c]*2
    for x in range(a,b+1):
        M[x][c] = 1

for d,e,f in tate:
    d,e,f = xdict[d]*2, ydict[e]*2, ydict[f]*2
    for y in range(e,f+1):
        M[d][y] = 1

from collections import deque
q=deque()

Dx=[1,0,-1,0]
Dy=[0,1,0,-1]

q.append((xdict[0]*2, ydict[0]*2))

while len(q) > 0:
    x,y = q.popleft()
    for dx, dy in zip(Dx,Dy):
        x2 = x+dx
        y2 = y+dy
        if x2 < 0 or x2 >= h:
            continue
        if y2 < 0 or y2 >= w:
            continue
        if M[x2][y2] != 0:
            continue
        M[x2][y2] = 2
        q.append((x2,y2))

#[print(m) for m in M]

res = 0
for x in range(h):
    for y in range(w):
        if M[x][y] != 2:
            continue
        if x==0 or x == h-1 or y == 0 or y == w-1:
            print("INF")
            exit()
        if x%2 == 0 or y%2 == 0:
            continue

        res += (xs[x//2+1] - xs[x//2])*(ys[y//2+1] - ys[y//2])

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10**8)
n,m = map(int,input().split())
xl = set()
yl = set()
xl.add(0)
yl.add(0)
nl = []
ml = []
for i in range(n):
    a,b,c = map(int,input().split())
    xl.add(a)
    xl.add(b)
    yl.add(c)
    nl.append([a,b,c])
for i in range(m):
    c,a,b = map(int,input().split())
    yl.add(a)
    yl.add(b)
    xl.add(c)
    ml.append([a,b,c])

xl = sorted(list(xl))
yl = sorted(list(yl))
dx = {}
dy = {}
for i in range(len(xl)):
    dx[xl[i]] = i

for i in range(len(yl)):
    dy[yl[i]] = i

h = len(xl)*2
w = len(yl)*2
d = [[0]*w for i in range(h)]

for a,b,c in nl:
    s = dx[a]*2
    g = dx[b]*2
    t = dy[c]*2
    
    for x in range(s,g+1):
        d[x][t] = -1

for a,b,c in ml:
    s = dy[a]*2
    g = dy[b]*2
    t = dx[c]*2
    
    for y in range(s,g+1):
        d[t][y] = -1


ans = 0
dtx = [1,-1,0,0]
dty = [0,0,1,-1]

sx = dx[0]*2
sy = dy[0]*2
q = deque([])
q.append((sx,sy))
d[sx][sy] = 1
while q:
    nx,ny = q.popleft()

    for i in range(4):
        x = nx+dtx[i]
        y = ny+dty[i]

        if 0 <= x < h and 0 <= y < w and d[x][y] == 0:
            d[x][y] = 1
            q.append((x,y))


for i in range(h):
    for j in range(w):
        if d[i][j] == 0:
            continue
        if (i == 0 or j == 0 or i == h-1 or j == w-1) and d[i][j] == 1:
            print("INF")
            exit()
        if i%2== 0 or j%2== 0:
            continue
        x = xl[i//2+1]-xl[i//2]
        y = yl[j//2+1]-yl[j//2]
        ans += x*y

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
 
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=1<<70
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()
 
class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=0):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def __str__(self):
        return  str(self.edges)
 
    def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
        q=deque()
        q.append(x)
        v=[-1]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==-1:
                    q.append(nb)
                    v[nb]=func(v[c],nb,d)
        return v
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)
 
class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]
 
    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

def dijkstra(edge,st):
    # edge=[[(v_to,dist_to_v),...],[],...]
    # initialize: def: d=dist(st,i), prev=[previous vertex in minimum path], q[]
    n=len(edge)
    d=[(0 if st==i else inf) for i in range(n)]
    prev=[0]*n
    q=[(j,i) for i,j in enumerate(d)]
    heapify(q)
    v=[False]*n
    # calc
    while q:
        dist,cur=heappop(q)
        if v[cur]:
            continue
        v[cur]=True
        for dst,dist in edge[cur]:
            alt=d[cur]+dist
            if alt<d[dst]:
                d[dst]=alt
                prev[dst]=cur
                heappush(q,(alt,dst))
    return d,prev


show_flg=False
show_flg=True
ans=0

n,m=LI()
X=[0,inf,-inf]
Y=[0,inf,-inf]
V=[]
H=[]
for i in range(n):
    a,b,c=LI()
    V.append(((a,b),c))
    Y.append(c)
    X.append(a)
    X.append(b)

n+=2
V.append(((-inf,inf),inf))
V.append(((-inf,inf),-inf))

for i in range(m):
    a,b,c=LI()
    H.append((a,(b,c)))
    X.append(a)
    Y.append(b)
    Y.append(c)

m+=2
H.append((inf,(-inf,inf)))
H.append((-inf,(-inf,inf)))


X.sort()
xdc={}
c=1
for j in sorted(set(X)):
    xdc[c]=j
    c+=1
nx=c-1

Y.sort()
ydc={}
c=1
for j in sorted(set(Y)):
    ydc[c]=j
    c+=1
ny=c-1

xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))

import numba

@numba.jit
def solve(nx,ny,V,H,xdc,xdcr,ydc,ydcr):
    ans=0
    mp=[[0]*(2*nx+2) for i in range(2*ny+2)]
    mpx=[[0]*(2*nx+2) for i in range(2*ny+2)]
    mpy=[[0]*(2*nx+2) for i in range(2*ny+2)]
    
    for (a,b),c in V:
        mpx[ydcr[c]*2][xdcr[a]*2]+=1
        mpx[ydcr[c]*2][xdcr[b]*2+1]+=-1
    for i in range(2*ny+2):
        for j in range(2*nx+1):
            mpx[i][j+1]+=mpx[i][j]
            
    for d,(e,f) in H:
        mpy[ydcr[e]*2][xdcr[d]*2]+=1
        mpy[ydcr[f]*2+1][xdcr[d]*2]+=-1
    for j in range(2*nx+2):
        for i in range(2*ny+1):
            mpy[i+1][j]+=mpy[i][j]
    
    for i in range(2*ny+2):
        for j in range(2*nx+2):
            mp[i][j]=mpx[i][j] or mpy[i][j]
    
    
    
    v=[[0]*(2*nx+2) for i in range(2*ny+2)]
    q=deque()
    q.append((2*xdcr[0]+1,2*ydcr[0]+1))
    v[2*ydcr[0]+1][2*xdcr[0]+1]=1
    while q:
        cx,cy=q.popleft()
        px,py=cx//2,cy//2
        if (cx%2)*(cy%2)==1:
            ans+=(xdc[px]-xdc[px+1])*(ydc[py]-ydc[py+1])
            #show((cx,cy),(xdc[px]-xdc[px-1])*(ydc[py]-ydc[py-1]),(xdc[px],xdc[px-1]),(ydc[py],ydc[py-1]))
        #show((cx,cy))
        for dx,dy in FourNb:
            nbx=cx+dx
            nby=cy+dy
            if (not 0<=nbx<2*nx+2) or (not 0<=nby<2*ny+2) or v[nby][nbx]==1:
                continue
            
            if mp[nby][nbx]==0:
                q.append((nbx,nby))
                v[nby][nbx]=1
    
    if ans>=1<<70:
        ans='INF'
    return ans
print(solve(nx,ny,V,H,xdc,xdcr,ydc,ydcr))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
inf=1<<70
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
input=lambda: sys.stdin.readline().rstrip()


show_flg=False
show_flg=True
ans=0

n,m=LI()
X=[0,inf,-inf]
Y=[0,inf,-inf]
V=[]
H=[]
for i in range(n):
    a,b,c=LI()
    V.append(((a,b),c))
    Y.append(c)
    X.append(a)
    X.append(b)

n+=2
V.append(((-inf,inf),inf))
V.append(((-inf,inf),-inf))

for i in range(m):
    a,b,c=LI()
    H.append((a,(b,c)))
    X.append(a)
    Y.append(b)
    Y.append(c)

m+=2
H.append((inf,(-inf,inf)))
H.append((-inf,(-inf,inf)))


X.sort()
xdc={}
c=1
for j in sorted(set(X)):
    xdc[c]=j
    c+=1
nx=c-1

Y.sort()
ydc={}
c=1
for j in sorted(set(Y)):
    ydc[c]=j
    c+=1
ny=c-1

xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))

mp=[[0]*(2*nx+2) for i in range(2*ny+2)]
mpx=[[0]*(2*nx+2) for i in range(2*ny+2)]
mpy=[[0]*(2*nx+2) for i in range(2*ny+2)]

for (a,b),c in V:
    mpx[ydcr[c]*2][xdcr[a]*2]+=1
    mpx[ydcr[c]*2][xdcr[b]*2+1]+=-1
for i in range(2*ny+2):
    for j in range(2*nx+1):
        mpx[i][j+1]+=mpx[i][j]
        
for d,(e,f) in H:
    mpy[ydcr[e]*2][xdcr[d]*2]+=1
    mpy[ydcr[f]*2+1][xdcr[d]*2]+=-1
for j in range(2*nx+2):
    for i in range(2*ny+1):
        mpy[i+1][j]+=mpy[i][j]

for i in range(2*ny+2):
    for j in range(2*nx+2):
        mp[i][j]=mpx[i][j] or mpy[i][j]



v=[[0]*(2*nx+2) for i in range(2*ny+2)]
q=deque()
q.append((2*xdcr[0]+1,2*ydcr[0]+1))
v[2*ydcr[0]+1][2*xdcr[0]+1]=1
while q:
    cx,cy=q.popleft()
    px,py=cx//2,cy//2
    if (cx%2)*(cy%2)==1:
        ans+=(xdc[px]-xdc[px+1])*(ydc[py]-ydc[py+1])

    for dx,dy in FourNb:
        nbx=cx+dx
        nby=cy+dy
        if (not 0<=nbx<2*nx+2) or (not 0<=nby<2*ny+2) or v[nby][nbx]==1:
            continue
        
        if mp[nby][nbx]==0:
            q.append((nbx,nby))
            v[nby][nbx]=1

if ans>=1<<70:
    ans='INF'
print(ans)