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:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,m = LI()
    p = LIR(n)
    q = LIR(m)
    fx = set([-float("inf"),0,float("inf")])
    fy = set([-float("inf"),0,float("inf")])
    for a,b,c in p:
        fy.add(a)
        fy.add(a+1e-1)
        fy.add(b)
        fy.add(b+1e-1)
        fx.add(c)
        fx.add(c+1e-1)

    for d,e,f in q:
        fy.add(d)
        fy.add(d+1e-1)
        fx.add(e)
        fx.add(e+1e-1)
        fx.add(f)
        fx.add(f+1e-1)
    fy = list(fy)
    fx = list(fx)
    fy.sort()
    fx.sort()
    h = len(fy)+1
    w = len(fx)+1
    s = [[0]*w for i in range(h)]
    for a,b,c in p:
        ai = bisect.bisect_left(fy,a)
        bi = bisect.bisect_left(fy,b)
        ci = bisect.bisect_left(fx,c)
        s[ai][ci] += 1
        s[bi+1][ci] -= 1
        s[ai][ci+1] -= 1
        s[bi+1][ci+1] += 1
    for d,e,f in q:
        di = bisect.bisect_left(fy,d)
        ei = bisect.bisect_left(fx,e)
        fi = bisect.bisect_left(fx,f)
        s[di][ei] += 1
        s[di][fi+1] -= 1
        s[di+1][ei] -= 1
        s[di+1][fi+1] += 1
    for i in range(h):
        for j in range(len(fx)):
            s[i][j+1] += s[i][j]
    for i in range(len(fy)):
        for j in range(w):
            s[i+1][j] += s[i][j]
    d = [(1,0),(-1,0),(0,1),(0,-1)]
    ans = 0
    sx = bisect.bisect_left(fx,0)
    sy = bisect.bisect_left(fy,0)
    nh,nw = len(fy)-1,len(fx)-1
    lx = [float("inf")]*nw
    ly = [float("inf")]*nh
    fx[1] = round(fx[1])
    fy[1] = round(fy[1])
    for i in range(1,nw-1):
        fx[i+1] = round(fx[i+1])
        lx[i] = fx[i+1]-fx[i]
    for i in range(1,nh-1):
        fy[i+1] = round(fy[i+1])
        ly[i] = fy[i+1]-fy[i]

    ans += lx[sx]*ly[sy]
    q = [(sy,sx)]
    f = [[1]*nw for i in range(nh)]
    f[sy][sx] = 0
    while q:
        y,x = q.pop()
        for dy,dx in d:
            ny,nx = y+dy,x+dx
            if 0 <= ny < nh and 0 <= nx < nw:
                if f[ny][nx] and not s[ny][nx]:
                    k = lx[nx]*ly[ny]
                    if k == float("inf"):
                        print("INF")
                        return
                    ans += k
                    f[ny][nx] = 0
                    q.append((ny,nx))
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,m = LI()
    p = LIR(n)
    q = LIR(m)
    fx = set([-float("inf"),0,float("inf")])
    fy = set([-float("inf"),0,float("inf")])
    for a,b,c in p:
        fy.add(a)
        fy.add(a+1e-1)
        fy.add(a-1e-1)
        fy.add(b)
        fy.add(b+1e-1)
        fy.add(b-1e-1)
        fx.add(c)
        fx.add(c+1e-1)
        fx.add(c-1e-1)

    for d,e,f in q:
        fy.add(d)
        fy.add(d+1e-1)
        fy.add(d-1e-1)
        fx.add(e)
        fx.add(e+1e-1)
        fx.add(e-1e-1)
        fx.add(f)
        fx.add(f+1e-1)
        fx.add(f-1e-1)
    fy = list(fy)
    fx = list(fx)
    fy.sort()
    fx.sort()
    h = len(fy)+1
    w = len(fx)+1
    s = [[0]*w for i in range(h)]
    for a,b,c in p:
        ai = bisect.bisect_left(fy,a)
        bi = bisect.bisect_left(fy,b)
        ci = bisect.bisect_left(fx,c)
        s[ai][ci] += 1
        s[bi+1][ci] -= 1
        s[ai][ci+1] -= 1
        s[bi+1][ci+1] += 1
    for d,e,f in q:
        di = bisect.bisect_left(fy,d)
        ei = bisect.bisect_left(fx,e)
        fi = bisect.bisect_left(fx,f)
        s[di][ei] += 1
        s[di][fi+1] -= 1
        s[di+1][ei] -= 1
        s[di+1][fi+1] += 1
    for i in range(h):
        for j in range(len(fx)):
            s[i][j+1] += s[i][j]
    for i in range(len(fy)):
        for j in range(w):
            s[i+1][j] += s[i][j]
    d = [(1,0),(-1,0),(0,1),(0,-1)]
    ans = 0
    sx = bisect.bisect_left(fx,0)
    sy = bisect.bisect_left(fy,0)
    nh,nw = len(fy)-1,len(fx)-1
    lx = [float("inf")]*nw
    ly = [float("inf")]*nh
    fx[1] = round(fx[1])
    fy[1] = round(fy[1])
    for i in range(1,nw-1):
        fx[i+1] = round(fx[i+1])
        lx[i] = fx[i+1]-fx[i]
    for i in range(1,nh-1):
        fy[i+1] = round(fy[i+1])
        ly[i] = fy[i+1]-fy[i]

    ans += lx[sx]*ly[sy]
    q = [(sy,sx)]
    f = [[1]*nw for i in range(nh)]
    f[sy][sx] = 0
    while q:
        y,x = q.pop()
        for dy,dx in d:
            ny,nx = y+dy,x+dx
            if 0 <= ny < nh and 0 <= nx < nw:
                if f[ny][nx] and not s[ny][nx]:
                    k = lx[nx]*ly[ny]
                    if k == float("inf"):
                        print("INF")
                        return
                    ans += k
                    f[ny][nx] = 0
                    q.append((ny,nx))
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,m = LI()
    p = LIR(n)
    q = LIR(m)
    fx = set([-float("inf"),0,float("inf")])
    fy = set([-float("inf"),0,float("inf")])
    for a,b,c in p:
        fy.add(a)
        fy.add(a+1e-1)
        fy.add(a-1e-1)
        fy.add(b)
        fy.add(b+1e-1)
        fy.add(b-1e-1)
        fx.add(c)
        fx.add(c+1e-1)
        fx.add(c-1e-1)

    for d,e,f in q:
        fy.add(d)
        fy.add(d+1e-1)
        fy.add(d-1e-1)
        fx.add(e)
        fx.add(e+1e-1)
        fx.add(e-1e-1)
        fx.add(f)
        fx.add(f+1e-1)
        fx.add(f-1e-1)
    fy = list(fy)
    fx = list(fx)
    fy.sort()
    fx.sort()
    h = len(fy)+1
    w = len(fx)+1
    s = [[0]*w for i in range(h)]
    for a,b,c in p:
        ai = bisect.bisect_left(fy,a)
        bi = bisect.bisect_left(fy,b)
        ci = bisect.bisect_left(fx,c)
        s[ai][ci] += 1
        s[bi+1][ci] -= 1
        s[ai][ci+1] -= 1
        s[bi+1][ci+1] += 1
    for d,e,f in q:
        di = bisect.bisect_left(fy,d)
        ei = bisect.bisect_left(fx,e)
        fi = bisect.bisect_left(fx,f)
        s[di][ei] += 1
        s[di][fi+1] -= 1
        s[di+1][ei] -= 1
        s[di+1][fi+1] += 1
    for i in range(h):
        for j in range(len(fx)):
            s[i][j+1] += s[i][j]
    for i in range(len(fy)):
        for j in range(w):
            s[i+1][j] += s[i][j]
    d = [(1,0),(-1,0),(0,1),(0,-1)]
    ans = 0
    sx = bisect.bisect_left(fx,0)
    sy = bisect.bisect_left(fy,0)
    for i in range(1,len(fx)-1):
        fx[i] = round(fx[i])
    for i in range(1,len(fy)-1):
        fy[i] = round(fy[i])

    ans += (fx[sx+1]-fx[sx])*(fy[sy+1]-fy[sy])
    q = [(sy,sx)]
    nh,nw = len(fy)-1,len(fx)-1
    f = [[1]*nw for i in range(nh)]
    f[sy][sx] = 0
    while q:
        y,x = q.pop()
        for dy,dx in d:
            ny,nx = y+dy,x+dx
            if 0 <= ny < nh and 0 <= nx < nw:
                if f[ny][nx] and not s[ny][nx]:
                    k = (fx[nx+1]-fx[nx])*(fy[ny+1]-fy[ny])
                    if k == float("inf"):
                        print("INF")
                        return
                    ans += k
                    f[ny][nx] = 0
                    q.append((ny,nx))
    print(ans)
    return

#Solve
if __name__ == "__main__":
    solve()

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()]
yoko = [[int(i) for i in readline().split()] for _ in range(n)]
tate = [[int(i) for i in readline().split()] for _ in range(m)]

INF = 10**9+5
xcoord = [-INF,0,INF]
ycoord = [-INF,0,INF]

for a,b,c in yoko: # (a,c) to (b,c)
    xcoord.append(a)
    xcoord.append(b)
    ycoord.append(c)
for d,e,f in tate: # (d,e) to (d,f)
    ycoord.append(e)
    ycoord.append(f)
    xcoord.append(d)

xcoord = list(sorted(set(xcoord)))
ycoord = list(sorted(set(ycoord)))

zaatu_x = {a:i for i,a in enumerate(xcoord)}
zaatu_y = {a:i for i,a in enumerate(ycoord)}

P = len(xcoord)
Q = len(ycoord)

ok = [[[1,1,1,1] for y in range(Q-1)] for x in range(P-1)] #移動できる方角
for y in range(Q-1):
    ok[0][y][2] = 0
    ok[P-2][y][0] = 0
for x in range(P-1):
    ok[x][0][3] = 0
    ok[x][Q-2][1] = 0

for a,b,c in yoko: # (a,c) to (b,c)
    xa = zaatu_x[a]
    xb = zaatu_x[b]
    yc = zaatu_y[c]
    for i in range(xa,xb):
        ok[i][yc][3] = 0
        ok[i][yc-1][1] = 0

for d,e,f in tate: # (d,e) to (d,f)
    ye = zaatu_y[e]
    yf = zaatu_y[f]
    xd = zaatu_x[d]
    for i in range(ye,yf):
        ok[xd][i][2] = 0
        ok[xd-1][i][0] = 0

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

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

used = [[0 for y in range(Q-1)] for x in range(P-1)]

q = [(x0,y0)]
used[x0][y0] = 1

while q:
    x,y = q.pop()
    for i,oki in enumerate(ok[x][y]):
        if oki:
            nx = x+dx[i]
            ny = y+dy[i]
            if used[nx][ny] == 0:
                used[nx][ny] = 1
                q.append((nx,ny))


#print(used)

if used[0][0] == 1:
    print("INF")
else:
    ans = 0
    for i in range(P-1):
        for j in range(Q-1):
            if used[i][j] == 1:
                ans += (xcoord[i+1]-xcoord[i])*(ycoord[j+1]-ycoord[j])
    print(ans)

#print(xcoord)
#print(ycoord)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline

def compress(L):
    L2 = list(set(L))
    L2.sort()
    C = {v : k for k, v in enumerate(L2)}
    return L2, C

N, M = map(int, readline().split())
INF = 10**9+7

Wp = [tuple(map(int, readline().split())) for _ in range(N)]
Hp = [tuple(map(int, readline().split())) for _ in range(M)]

epx = [0, INF, -INF]
epy = [0, INF, -INF]

for X, st, en in Hp:
    epx.append(X)
    epy.append(st)
    epy.append(en)

for st, en, Y in Wp:
    epy.append(Y)
    epx.append(st)
    epx.append(en)
    

Elx, Cex = compress(epx)
Ely, Cey = compress(epy)
Lx = len(Elx)
Ly = len(Ely)

event = [[] for _ in range(Lx)]
for X, st, en in Hp:
    event[Cex[X]].append((0, Cey[st], Cey[en]))
for st, en, Y in Wp:
    event[Cex[st]].append((1, Cey[Y], 0))
    event[Cex[en]].append((-1, Cey[Y], 0))

geta = Ly
geta2 = 10**8
banned = set()

table = [0]*Ly
for xi in range(Lx):
    for a, b, c in event[xi]:
        if a == 0:
            for yi in range(b, c):
                banned.add(geta+geta2*((xi-1)*geta+yi))
                banned.add(-geta+geta2*(xi*geta+yi))
        elif a == 1:
            table[b] = 1
        else:
            table[b] = 0
    for i in range(Ly):
        if table[i]:
            banned.add(-1+geta2*(xi*geta+i))
            banned.add(1+geta2*(xi*geta+i-1))
                
ed = set()
for i in range(Lx):
    ed.add(i*geta)
    ed.add(i*geta+Ly-1)
for j in range(Ly):
    ed.add(j)
    ed.add((Lx-1)*geta+j)
used = set()
st = Cex[0]*geta+Cey[0]
stack = [st]
DIREC = (1, -1, -geta, geta)
while stack:
    vn = stack.pop()
    if vn in ed:
        continue
    for d in DIREC:
        if vn*geta2+d in banned:
            continue
        vf = vn+d
        if vf not in used:
            used.add(vf)
            stack.append(vf)

if ed&used:
    print('INF')
else:
    area = 0
    for k in used:
        x, y = divmod(k, geta)
        area += (Elx[x+1]-Elx[x])*(Ely[y+1]-Ely[y])
    print(area)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline

def compress(L):
    L2 = list(set(L))
    L2.sort()
    C = {v : k for k, v in enumerate(L2)}
    return L2, C

N, M = map(int, readline().split())
INF = 10**9+7

Wp = [tuple(map(int, readline().split())) for _ in range(N)]
Hp = [tuple(map(int, readline().split())) for _ in range(M)]

epx = [0, INF, -INF]
epy = [0, INF, -INF]

for X, st, en in Hp:
    epx.append(X)
    epy.append(st)
    epy.append(en)

for st, en, Y in Wp:
    epy.append(Y)
    epx.append(st)
    epx.append(en)
    

Elx, Cex = compress(epx)
Ely, Cey = compress(epy)
Lx = len(Elx)
Ly = len(Ely)

event = [[] for _ in range(Lx)]
for X, st, en in Hp:
    event[Cex[X]].append((0, Cey[st], Cey[en]))
for st, en, Y in Wp:
    event[Cex[st]].append((1, Cey[Y], 0))
    event[Cex[en]].append((-1, Cey[Y], 0))

geta = Ly

direc = [set((1, -1, geta, -geta)) for _ in range(Lx*Ly)]

table = [0]*Ly
for xi in range(Lx):
    for a, b, c in event[xi]:
        if a == 0:
            for yi in range(b, c):
                direc[(xi-1)*geta+yi].remove(geta)
                direc[xi*geta+yi].remove(-geta)
        elif a == 1:
            table[b] = 1
        else:
            table[b] = 0
    for i in range(Ly):
        if table[i]:
            direc[xi*geta+i].remove(-1)
            direc[xi*geta+i-1].remove(1)
                
ed = set()
for i in range(Lx):
    ed.add(i*geta)
    ed.add(i*geta+Ly-1)
for j in range(Ly):
    ed.add(j)
    ed.add((Lx-1)*geta+j)
used = set()
st = Cex[0]*geta+Cey[0]
stack = [st]

while stack:
    vn = stack.pop()
    if vn in ed:
        continue
    for d in direc[vn]:
        vf = vn+d
        if vf not in used:
            used.add(vf)
            stack.append(vf)

if ed&used:
    print('INF')
else:
    area = 0
    for k in used:
        x, y = divmod(k, geta)
        area += (Elx[x+1]-Elx[x])*(Ely[y+1]-Ely[y])
    print(area)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline

def compress(L):
    L2 = list(set(L))
    L2.sort()
    C = {v : k for k, v in enumerate(L2)}
    return L2, C

N, M = map(int, readline().split())
INF = 10**9+7

Wp = [tuple(map(int, readline().split())) for _ in range(N)]
Hp = [tuple(map(int, readline().split())) for _ in range(M)]

epx = [0, INF, -INF]
epy = [0, INF, -INF]

for X, st, en in Hp:
    epx.append(X)
    epy.append(st)
    epy.append(en)

for st, en, Y in Wp:
    epy.append(Y)
    epx.append(st)
    epx.append(en)
    

Elx, Cex = compress(epx)
Ely, Cey = compress(epy)
Lx = len(Elx)
Ly = len(Ely)

event = [[] for _ in range(Lx)]
for X, st, en in Hp:
    event[Cex[X]].append((0, Cey[st], Cey[en]))
for st, en, Y in Wp:
    event[Cex[st]].append((1, Cey[Y], 0))
    event[Cex[en]].append((-1, Cey[Y], 0))

geta = Ly

direc = [[1, -1, geta, -geta] for _ in range(Lx*Ly)]

table = [0]*Ly
for xi in range(Lx):
    for a, b, c in event[xi]:
        if a == 0:
            for yi in range(b, c):
                direc[(xi-1)*geta+yi].remove(geta)
                direc[xi*geta+yi].remove(-geta)
        elif a == 1:
            table[b] = 1
        else:
            table[b] = 0
    for i in range(Ly):
        if table[i]:
            direc[xi*geta+i].remove(-1)
            direc[xi*geta+i-1].remove(1)
                
ed = set()
for i in range(Lx):
    ed.add(i*geta)
    ed.add(i*geta+Ly-1)
for j in range(Ly):
    ed.add(j)
    ed.add((Lx-1)*geta+j)
used = set()
st = Cex[0]*geta+Cey[0]
stack = [st]

while stack:
    vn = stack.pop()
    if vn in ed:
        continue
    for d in direc[vn]:
        vf = vn+d
        if vf not in used:
            used.add(vf)
            stack.append(vf)

if ed&used:
    print('INF')
else:
    area = 0
    for k in used:
        x, y = divmod(k, geta)
        area += (Elx[x+1]-Elx[x])*(Ely[y+1]-Ely[y])
    print(area)

Submission status: Time Limit Exceeded

Solution code:
import os
import sys
from io import BytesIO, IOBase

# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

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

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

vert = []
for _ in range(n):
    a, b, c = map(int, input().split())
    xs.add(a)
    xs.add(b)
    ys.add(c)
    vert.append((a,b,c))

hor = []
for _ in range(m):
    d, e, f = map(int, input().split())
    xs.add(d)
    ys.add(e)
    ys.add(f)
    hor.append((d,e,f))

xs = list(xs)
ys = list(ys)
xs.sort()
ys.sort()

revX = dict()
revY = dict()
for i in range(len(xs)):
    revX[xs[i]] = i
for i in range(len(ys)):
    revY[ys[i]] = i

width = len(xs) + 1
height = len(ys) + 1

visited = [[False] * height for _ in range(width)]

adj = [[15]*height for _ in range(width)]
for a, b, c in vert:
    ra, rb, rc = revX[a], revX[b], revY[c]
    for i in range(ra + 1, rb + 1):
        adj[i][rc] &= 13
        adj[i][rc + 1] &= 14

for d, e, f in hor:
    rd, re, rf = revX[d], revY[e], revY[f]
    for j in range(re + 1, rf + 1):
        adj[rd][j] &= 7
        adj[rd + 1][j] &= 11

dX = [0,0,-1,1]
dY = [-1,1,0,0]

stack = []
start = (revX[0], revY[0])
stack.append(start)
visited[start[0]][start[1]] = True

inf = False
while stack:
    nexX, nexY = stack.pop()
    poss = adj[nexX][nexY]
    for d in range(4):
        if poss & (1 << d):
            newX = nexX + dX[d]
            newY = nexY + dY[d]
            if not visited[newX][newY]:
                visited[newX][newY] = True
                stack.append((newX, newY))
                if newX == 0 or newX == width - 1 or newY == 0 or newY == height - 1:
                    inf = True
                if inf:
                    stack = []

if inf:
    print('INF')
else:
    area = 0
    for i in range(width-1):
        xRange = (xs[i] - xs[i - 1])
        for j in range(height-1):
            if visited[i][j]:
                area += xRange * (ys[j] - ys[j-1])
    print(area)

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline

def compress(L):
    L2 = list(set(L))
    L2.sort()
    C = {v : k for k, v in enumerate(L2)}
    return L2, C

N, M = map(int, readline().split())
INF = 10**9+7

Wp = [tuple(map(int, readline().split())) for _ in range(N)]
Hp = [tuple(map(int, readline().split())) for _ in range(M)]

epx = [0, INF, -INF]
epy = [0, INF, -INF]

for X, st, en in Hp:
    epx.append(X)
    epy.append(st)
    epy.append(en)

for st, en, Y in Wp:
    epy.append(Y)
    epx.append(st)
    epx.append(en)
    

Elx, Cex = compress(epx)
Ely, Cey = compress(epy)
Lx = len(Elx)
Ly = len(Ely)

event = [[] for _ in range(Lx)]
for X, st, en in Hp:
    event[Cex[X]].append((0, Cey[st], Cey[en]))
for st, en, Y in Wp:
    event[Cex[st]].append((1, Cey[Y], 0))
    event[Cex[en]].append((-1, Cey[Y], 0))

geta = Ly

banned = [[] for _ in range(Lx*Ly)]

table = [0]*Ly
for xi in range(Lx):
    for a, b, c in event[xi]:
        if a == 0:
            for yi in range(b, c):
                banned[(xi-1)*geta+yi].append(geta)
                banned[xi*geta+yi].append(-geta)
        elif a == 1:
            table[b] = 1
        else:
            table[b] = 0
    for i in range(Ly):
        if table[i]:
            if xi*geta+i == 47:
                pass
            banned[xi*geta+i].append(-1)
            banned[xi*geta+i-1].append(1)
                
ed = set()
for i in range(Lx):
    ed.add(i*geta)
    ed.add(i*geta+Ly-1)
for j in range(Ly):
    ed.add(j)
    ed.add((Lx-1)*geta+j)
used = set()
st = Cex[0]*geta+Cey[0]
stack = [st]
DIREC = (1, -1, geta, -geta)

while stack:
    vn = stack.pop()
    if vn in ed:
        continue
    for d in DIREC:
        if d in banned[vn]:
            continue
        vf = vn+d
        if vf not in used:
            used.add(vf)
            stack.append(vf)

if ed&used:
    print('INF')
else:
    area = 0
    for k in used:
        x, y = divmod(k, geta)
        area += (Elx[x+1]-Elx[x])*(Ely[y+1]-Ely[y])
    print(area)

Submission status: Time Limit Exceeded

Solution code:
import os
import sys
from io import BytesIO, IOBase

# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

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

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

vert = []
for _ in range(n):
    a, b, c = map(int, input().split())
    xs.add(a)
    xs.add(b)
    ys.add(c)
    vert.append((a,b,c))

hor = []
for _ in range(m):
    d, e, f = map(int, input().split())
    xs.add(d)
    ys.add(e)
    ys.add(f)
    hor.append((d,e,f))

xs = list(xs)
ys = list(ys)
xs.sort()
ys.sort()

revX = dict()
revY = dict()
for i in range(len(xs)):
    revX[xs[i]] = i
for i in range(len(ys)):
    revY[ys[i]] = i

width = len(xs) + 1
height = len(ys) + 1

visited = [[False] * height for _ in range(width)]
area = [[0] * height for _ in range(width)]
for i in range(1, width - 1):
    for j in range(1, height - 1):
        area[i][j] = (xs[i] - xs[i-1]) * (ys[j] - ys[j-1])
        
adj = [[15]*height for _ in range(width)]
for a, b, c in vert:
    ra, rb, rc = revX[a], revX[b], revY[c]
    for i in range(ra + 1, rb + 1):
        adj[i][rc] &= 13
        adj[i][rc + 1] &= 14

for d, e, f in hor:
    rd, re, rf = revX[d], revY[e], revY[f]
    for j in range(re + 1, rf + 1):
        adj[rd][j] &= 7
        adj[rd + 1][j] &= 11

dX = [0,0,-1,1]
dY = [-1,1,0,0]

stack = []
start = (revX[0], revY[0])
stack.append(start)
visited[start[0]][start[1]] = True
out = area[start[0]][start[1]]

inf = False
while stack:
    nexX, nexY = stack.pop()
    poss = adj[nexX][nexY]
    for d in range(4):
        if poss & (1 << d):
            newX = nexX + dX[d]
            newY = nexY + dY[d]
            if not visited[newX][newY]:
                visited[newX][newY] = True
                stack.append((newX, newY))
                newA = area[newX][newY]
                out += newA
                inf |= newA == 0
                if inf:
                    stack = []

if inf:
    print('INF')
else:
    print(out)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

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

vert = []
for _ in range(n):
    a, b, c = map(int, input().split())
    xs.add(a)
    xs.add(b)
    ys.add(c)
    vert.append((a,b,c))

hor = []
for _ in range(m):
    d, e, f = map(int, input().split())
    xs.add(d)
    ys.add(e)
    ys.add(f)
    hor.append((d,e,f))

xs = list(xs)
ys = list(ys)
xs.sort()
ys.sort()

revX = dict()
revY = dict()
for i in range(len(xs)):
    revX[xs[i]] = i
for i in range(len(ys)):
    revY[ys[i]] = i

width = len(xs) + 1
height = len(ys) + 1

visited = [[False] * height for _ in range(width)]
area = [[0] * height for _ in range(width)]
for i in range(1, width - 1):
    for j in range(1, height - 1):
        area[i][j] = (xs[i] - xs[i-1]) * (ys[j] - ys[j-1])
        
adj = [[15]*height for _ in range(width)]
for a, b, c in vert:
    ra, rb, rc = revX[a], revX[b], revY[c]
    for i in range(ra + 1, rb + 1):
        adj[i][rc] &= 13
        adj[i][rc + 1] &= 14

for d, e, f in hor:
    rd, re, rf = revX[d], revY[e], revY[f]
    for j in range(re + 1, rf + 1):
        adj[rd][j] &= 7
        adj[rd + 1][j] &= 11

dX = [0,0,-1,1]
dY = [-1,1,0,0]

stack = []
start = (revX[0], revY[0])
stack.append(start)
visited[start[0]][start[1]] = True
out = area[start[0]][start[1]]

inf = False
while stack:
    nexX, nexY = stack.pop()
    poss = adj[nexX][nexY]
    for d in range(4):
        if poss & (1 << d):
            newX = nexX + dX[d]
            newY = nexY + dY[d]
            if not visited[newX][newY]:
                visited[newX][newY] = True
                stack.append((newX, newY))
                newA = area[newX][newY]
                out += newA
                inf |= newA == 0
                if inf:
                    stack = []

if inf:
    print('INF')
else:
    print(out)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

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

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

vert = []
for _ in range(n):
    a, b, c = map(int, input().split())
    xs.add(a)
    xs.add(b)
    ys.add(c)
    vert.append((a,b,c))

hor = []
for _ in range(m):
    d, e, f = map(int, input().split())
    xs.add(d)
    ys.add(e)
    ys.add(f)
    hor.append((d,e,f))

xs = list(xs)
ys = list(ys)
xs.sort()
ys.sort()

revX = dict()
revY = dict()
for i in range(len(xs)):
    revX[xs[i]] = i
for i in range(len(ys)):
    revY[ys[i]] = i

width = len(xs) + 1
height = len(ys) + 1

visited = [[False] * height for _ in range(width)]
area = [[0] * height for _ in range(width)]
for i in range(1, width - 1):
    for j in range(1, height - 1):
        area[i][j] = (xs[i] - xs[i-1]) * (ys[j] - ys[j-1])
        
adj = [[15]*height for _ in range(width)]
for i in range(width):
    adj[i][0] &= 14
    adj[i][height - 1] &= 13
for j in range(height):
    adj[0][j] &= 11
    adj[width - 1][j] &= 7

for a, b, c in vert:
    ra, rb, rc = revX[a], revX[b], revY[c]
    for i in range(ra + 1, rb + 1):
        adj[i][rc] &= 13
        adj[i][rc + 1] &= 14

for d, e, f in hor:
    rd, re, rf = revX[d], revY[e], revY[f]
    for j in range(re + 1, rf + 1):
        adj[rd][j] &= 7
        adj[rd + 1][j] &= 11

dX = [0,0,-1,1]
dY = [-1,1,0,0]

stack = []
start = (revX[0], revY[0])
stack.append(start)
visited[start[0]][start[1]] = True
out = area[start[0]][start[1]]
inf = False
while stack:
    nexX, nexY = stack.pop()
    poss = adj[nexX][nexY]
    for d in range(4):
        if poss & (1 << d):
            newX = nexX + dX[d]
            newY = nexY + dY[d]
            if not visited[newX][newY]:
                visited[newX][newY] = True
                stack.append((newX, newY))
                newA = area[newX][newY]
                out += newA
                inf |= newA == 0

if inf:
    print('INF')
else:
    print(out)