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: Wrong Answer

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-15)
        fy.add(a-1e-15)
        fy.add(b)
        fy.add(b+1e-15)
        fy.add(b-1e-15)
        fx.add(c)
        fx.add(c+1e-15)
        fx.add(c-1e-15)

    for d,e,f in q:
        fy.add(d)
        fy.add(d+1e-15)
        fy.add(d-1e-15)
        fx.add(e)
        fx.add(e+1e-15)
        fx.add(e-1e-15)
        fx.add(f)
        fx.add(f+1e-15)
        fx.add(f-1e-15)
    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)
    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:
        if ans == float("inf"):
            print("INF")
            return
        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]:
                    ans += (fx[nx+1]-fx[nx])*(fy[ny+1]-fy[ny])
                    f[ny][nx] = 0
                    q.append((ny,nx))
    print(round(ans))
    return

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

Submission status: Wrong Answer

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-15)
        fy.add(b)
        fy.add(b+1e-15)
        fx.add(c)
        fx.add(c+1e-15)

    for d,e,f in q:
        fy.add(d)
        fy.add(d+1e-15)
        fx.add(e)
        fx.add(e+1e-15)
        fx.add(f)
        fx.add(f+1e-15)
    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)
    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:
        if ans == float("inf"):
            print("INF")
            return
        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]:
                    ans += (fx[nx+1]-fx[nx])*(fy[ny+1]-fy[ny])
                    f[ny][nx] = 0
                    q.append((ny,nx))
    print(round(ans))
    return

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

Submission status: Wrong Answer

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([0,float("inf")])
    fy = set([0,float("inf")])
    for a,b,c in p:
        fy.add(a-1e-15)
        fy.add(a)
        fy.add(a+1e-15)
        fy.add(b-1e-15)
        fy.add(b)
        fy.add(b+1e-15)
        fx.add(c-1e-15)
        fx.add(c)
        fx.add(c+1e-15)

    for d,e,f in q:
        fy.add(d-1e-15)
        fy.add(d)
        fy.add(d+1e-15)
        fx.add(e-1e-15)
        fx.add(e)
        fx.add(e+1e-15)
        fx.add(f-1e-15)
        fx.add(f)
        fx.add(f+1e-15)
    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)
    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()
        if ans == float("inf"):
            print("INF")
            return
        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]:
                    ans += (fx[nx+1]-fx[nx])*(fy[ny+1]-fy[ny])
                    f[ny][nx] = 0
                    q.append((ny,nx))
    print(round(ans))
    return

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

Submission status: Wrong Answer

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([0,float("inf")])
    fy = set([0,float("inf")])
    for a,b,c in p:
        fy.add(a-1e-15)
        fy.add(a)
        fy.add(a+1e-15)
        fy.add(b-1e-15)
        fy.add(b)
        fy.add(b+1e-15)
        fx.add(c-1e-15)
        fx.add(c)
        fx.add(c+1e-15)

    for d,e,f in q:
        fy.add(d-1e-15)
        fy.add(d)
        fy.add(d+1e-15)
        fx.add(e-1e-15)
        fx.add(e)
        fx.add(e+1e-15)
        fx.add(f-1e-15)
        fx.add(f)
        fx.add(f+1e-15)
    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)
    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()
        if ans == float("inf"):
            print("INF")
            return
        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]:
                    ans += (fx[nx+1]-fx[nx])*(fy[ny+1]-fy[ny])
                    f[ny][nx] = 0
                    q.append((ny,nx))
    print(round(ans))
    return

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

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from numba import njit

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

INF = 10**9 + 1

N, M = map(int, readline().split())
data = np.array(read().split(), np.int64)
A = data[::3]
B = data[1::3]
C = data[2::3]

D = A[N:]
E = B[N:]
F = C[N:]
A = A[:N]
B = B[:N]
C = C[:N]

X = np.unique(np.concatenate([A, B, D, [0, -INF, INF]]))
Y = np.unique(np.concatenate([C, E, F, [0, -INF, INF]]))
DX = X[1:] - X[:-1]
DY = Y[1:] - Y[:-1]

A = np.searchsorted(X, A)
B = np.searchsorted(X, B)
C = np.searchsorted(X, C)
D = np.searchsorted(X, D)
E = np.searchsorted(X, E)
F = np.searchsorted(X, F)

H, W = len(X), len(Y)
N = H * W

@njit
def set_ng(A, B, C, D, E, F):
    p = 0
    head = np.full(N, -1, np.int32)
    ng = np.empty(4 * N, np.int32)
    nxt = np.empty(4 * N, np.int32)

    def add(v, w):
        nonlocal p
        nxt[p] = head[v]
        head[v] = p
        ng[p] = w
        p += 1

    for i in range(len(A)):
        a, b, c = A[i], B[i], C[i]
        for x in range(a, b):
            v = x * W + c
            add(v, v - 1)
            add(v - 1, v)
    for i in range(len(D)):
        d, e, f = D[i], E[i], F[i]
        for y in range(e, f):
            v = d * W + y
            add(v, v - W)
            add(v - W, v)
    return head, ng[:p], nxt[:p]

head, ng, nxt = set_ng(A, B, C, D, E, F)

Submission status: Wrong Answer

Solution code:
print('INF')

Submission status: Wrong Answer

Solution code:
print("INF")

Submission status: Time Limit Exceeded

Solution code:
# ABC168F .(Single Dot)
from collections import deque

g=lambda:map(int,input().split())

N,M=g()

sortx=[]
sorty=[]

y_line=[0]*N
x_line=[0]*M

for i in range(N):
    a,b,c=g()
    sortx.append(a)
    sortx.append(b)
    sorty.append(c)
    y_line[i]=(a,b,c)
    
for i in range(M):
    d,e,f=g()
    sortx.append(d)
    sorty.append(e)
    sorty.append(f)
    x_line[i]=(d,e,f)
    
from bisect import bisect_left as bl
    
sortx=sorted(list(set(sortx)))
sorty=sorted(list(set(sorty)))

for i in range(N):
    a,b,c=y_line[i]
    a=bl(sortx,a)
    b=bl(sortx,b)
    c=bl(sorty,c)
    y_line[i]=(a,b,c)
    
for i in range(M):
    d,e,f=x_line[i]
    d=bl(sortx,d)
    e=bl(sorty,e)
    f=bl(sorty,f)
    x_line[i]=(d,e,f)
    
W=len(sortx)*2-1
H=len(sorty)*2-1
    
G=[1]*W*H

def make_graph(i,j,s=0):
    G[i+j*W]=s
    
def isOK(x,y):
    if 0<=x+y*W<W*H:
        return G[x+y*W]==1
    else:
        return False
    
def isSoto(x,y):
    return (not 0<=x+y*W<W*H)

def get_score(i,j):
    if i<=0 or j<=0  or i>=W or j>=H:
        return float('inf')
    elif i%2 and j%2:
        dx=sortx[(i+1)//2]-sortx[(i-1)//2]
        dy=sorty[(j+1)//2]-sorty[(j-1)//2]
        return dx*dy
    else:
        return 0

dic=[(-1,0),(1,0),(0,1),(0,-1)]
def search(i,j):
    res=[]
    for dx,dy in dic:
        if isOK(i+dx,j+dy) and (isOK(i+2*dx,j+2*dy) or isSoto(i+2*dx,j+2*dy)):
            res.append((i+2*dx,j+2*dy))
    return res

for a,b,c in y_line:
    for i in range(2*a,2*b+1):
        make_graph(i,2*c)
        
for d,e,f in x_line:
    for j in range(2*e,2*f+1):
        make_graph(2*d,j)
        
x0,y0=2*bl(sortx,0)-1,2*bl(sorty,0)-1

stack=deque()

for dx,dy in [(-1,-1),(-1,1),(1,1),(1,-1)]:
    if isOK(x0+dx,y0) or isOK(x0,y0+dy):
        stack.append((x0+dx,y0+dy))

stack.append((x0,y0))
res=0
make_graph(x0,y0,1)

while stack:
    x,y=stack.pop()
    if isSoto(x,y):
        res+=get_score(x,y)
        break
    if not isOK(x,y):
        continue
    res+=get_score(x,y)
    stack+=search(x,y)
    make_graph(x,y)

print(res if res<float('inf') else 'INF')

Submission status: Time Limit Exceeded

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
from collections import deque
def resolve():
    m, n = map(int, input().split())
    horizontal, vertical = [], []
    X, Y = {-INF, 0, INF}, {-INF, 0, INF}

    for _ in range(m):
        x0, x1, y = map(int, input().split())
        horizontal.append((x0, x1, y))
        X.add(x0)
        X.add(x1)
        Y.add(y)
    for _ in range(n):
        x, y0, y1 = map(int, input().split())
        vertical.append((x, y0, y1))
        X.add(x)
        Y.add(y0)
        Y.add(y1)
    X = sorted(X)
    Y = sorted(Y)

    # compress
    m, n = len(X), len(Y)
    cX = {v : i for i, v in enumerate(X)}
    cY = {v : i for i, v in enumerate(Y)}

    # make grid
    grid_hor = [[True] * n for _ in range(m)]
    grid_ver = [[True] * n for _ in range(m)]
    for x0, x1, y in horizontal:
        y = cY[y]
        for x in range(cX[x0], cX[x1]):
            grid_hor[x][y] = False
    for x, y0, y1 in vertical:
        x = cX[x]
        for y in range(cY[y0], cY[y1]):
            grid_ver[x][y] = False

    # bfs
    ans = 0
    queue = [(cX[0], cY[0])]
    used = [[False] * n for _ in range(m)]
    used[cX[0]][cY[0]] = True
    for x, y in queue:
        if x == 0 or y == 0 or x == m - 1 or y == n - 1:
            print("INF")
            return
        ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
        # up
        if y + 1 < n and grid_hor[x][y + 1] and not used[x][y + 1]:
            used[x][y + 1] = True
            queue.append((x, y + 1))
        # down
        if y - 1 >= 0 and grid_hor[x][y] and not used[x][y - 1]:
            used[x][y - 1] = True
            queue.append((x, y - 1))
        # right
        if x + 1 < m and grid_ver[x + 1][y] and not used[x + 1][y]:
            used[x + 1][y] = True
            queue.append((x + 1, y))
        # left
        if x - 1 >= 0 and grid_ver[x][y] and not used[x - 1][y]:
            used[x - 1][y] = True
            queue.append((x - 1, y))

    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
def resolve():
    m, n = map(int, input().split())
    horizontal, vertical = [], []
    X, Y = {-INF, 0, INF}, {-INF, 0, INF}

    for _ in range(m):
        x0, x1, y = map(int, input().split())
        horizontal.append((x0, x1, y))
        X.add(x0)
        X.add(x1)
        Y.add(y)
    for _ in range(n):
        x, y0, y1 = map(int, input().split())
        vertical.append((x, y0, y1))
        X.add(x)
        Y.add(y0)
        Y.add(y1)
    X = sorted(X)
    Y = sorted(Y)

    # compress
    m, n = len(X), len(Y)
    cX = {v : i for i, v in enumerate(X)}
    cY = {v : i for i, v in enumerate(Y)}

    # make grid
    grid_hor = [[True] * n for _ in range(m)]
    grid_ver = [[True] * n for _ in range(m)]
    for x0, x1, y in horizontal:
        y = cY[y]
        for x in range(cX[x0], cX[x1]):
            grid_hor[x][y] = False
    for x, y0, y1 in vertical:
        x = cX[x]
        for y in range(cY[y0], cY[y1]):
            grid_ver[x][y] = False

    # dfs
    ans = 0
    stack = [(cX[0], cY[0])]
    used = [[False] * n for _ in range(m)]
    used[cX[0]][cY[0]] = True
    while stack:
        x, y = stack.pop()
        if x == 0 or y == 0 or x == m - 1 or y == n - 1:
            print("INF")
            return
        ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
        # up
        if y + 1 < n and grid_hor[x][y + 1] and not used[x][y + 1]:
            used[x][y + 1] = True
            stack.append((x, y + 1))
        # down
        if y - 1 >= 0 and grid_hor[x][y] and not used[x][y - 1]:
            used[x][y - 1] = True
            stack.append((x, y - 1))
        # right
        if x + 1 < m and grid_ver[x + 1][y] and not used[x + 1][y]:
            used[x + 1][y] = True
            stack.append((x + 1, y))
        # left
        if x - 1 >= 0 and grid_ver[x][y] and not used[x - 1][y]:
            used[x - 1][y] = True
            stack.append((x - 1, y))

    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
def resolve():
    m, n = map(int, input().split())
    horizontal, vertical = [], []
    X, Y = {-INF, 0, INF}, {-INF, 0, INF}

    for _ in range(m):
        x0, x1, y = map(int, input().split())
        horizontal.append((x0, x1, y))
        X.add(x0)
        X.add(x1)
        Y.add(y)
    for _ in range(n):
        x, y0, y1 = map(int, input().split())
        vertical.append((x, y0, y1))
        X.add(x)
        Y.add(y0)
        Y.add(y1)
    X = sorted(X)
    Y = sorted(Y)

    # compress
    m, n = len(X), len(Y)
    cX = {v : i for i, v in enumerate(X)}
    cY = {v : i for i, v in enumerate(Y)}

    # make grid
    grid_hor = [[True] * n for _ in range(m)]
    grid_ver = [[True] * n for _ in range(m)]
    for x0, x1, y in horizontal:
        y = cY[y]
        for x in range(cX[x0], cX[x1]):
            grid_hor[x][y] = False
    for x, y0, y1 in vertical:
        x = cX[x]
        for y in range(cY[y0], cY[y1]):
            grid_ver[x][y] = False

    # dfs
    ans = 0
    stack = [(cX[0], cY[0])]
    used = [[False] * n for _ in range(m)]
    while stack:
        x, y = stack.pop()
        if used[x][y]:
            continue
        used[x][y] = True
        if x == 0 or y == 0 or x == m - 1 or y == n - 1:
            print("INF")
            return
        ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
        # up
        if y + 1 < n and grid_hor[x][y + 1]:
            stack.append((x, y + 1))
        # down
        if y - 1 >= 0 and grid_hor[x][y]:
            stack.append((x, y - 1))
        # right
        if x + 1 < m and grid_ver[x + 1][y]:
            stack.append((x + 1, y))
        # left
        if x - 1 >= 0 and grid_ver[x][y]:
            stack.append((x - 1, y))

    print(ans)
resolve()

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split())
A, B, C = [], [], []
for _ in range(N):
  a, b, c = map(int, input().split())
  A.append(a)
  B.append(b)
  C.append(c)
D, E, F = [], [], []
for _ in range(M):
  d, e, f = map(int, input().split())
  D.append(d)
  E.append(e)
  F.append(f)

orig_X = sorted(set([0] + A + B + D))
orig_Y = sorted(set([0] + C + E + F))
                
X = {x: i for i, x in enumerate(orig_X)}
Y = {y: i for i, y in enumerate(orig_Y)}
max_X = len(X) - 1
max_Y = len(Y) - 1
#print(X, Y)

movable = [(-1, 0), (1, 0), (0, -1), (0, 1)]
blocked = {}
# (x, y) -> stands at (x+0.5, y+0.5)
for a, b, c in zip(A, B, C):
  y = Y[c]
  for x in range(X[a], X[b]):
    if y < max_Y:
      if (x, y) not in blocked:
        blocked[(x, y)] = set()
      blocked[(x, y)].add((0, -1))
    if y > 0:
      if (x, y-1) not in blocked:
        blocked[(x, y-1)] = set()
      blocked[(x, y-1)].add((0, +1))

for d, e, f in zip(D, E, F):
  x = X[d]
  for y in range(Y[e], Y[f]):
    if (x, y) not in blocked:
      blocked[(x, y)] = set()
    blocked[(x, y)].add((-1, 0))
    if x > 0:
      if (x-1, y) not in blocked:
        blocked[(x-1, y)] = set()
      blocked[(x-1, y)].add((+1, 0))

#print(sorted(blocked))

visited = [0] * max_X * max_Y
def get_visited(x, y):
  return visited[x * max_Y + y]
def set_visited(x, y):
  #print(x,y)
  visited[x * max_Y + y] = True

to_visit = [(X[0], Y[0])]
while to_visit:
  #print(to_visit)
  x, y = to_visit.pop()
  if x < 0 or x >= max_X or y < 0 or y >= max_Y:
    print('INF')
    exit()
  if get_visited(x, y):
    continue
  set_visited(x, y)
  for d in movable:
    if (x, y) in blocked and d in blocked[(x, y)]:
      continue
    to_visit.append((x + d[0], y + d[1]))

ans = 0
for x in range(0, max_X):
  for y in range(0, max_Y):
    if get_visited(x, y):
      ans += (orig_X[x+1] - orig_X[x]) * (
        orig_Y[y+1] - orig_Y[y])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
  n,m=map(int,input().split())
  def hashh(x1,y1,x2,y2):
      if x1>x2:
          x1,y1,x2,y2=x2,y2,x1,y1
      if x1==x2 and y1>y2:
          x1,y1,x2,y2=x2,y2,x1,y1
      return x1*27000000000+y1*9000000+x2*3000+y2
  abc_l=[list(map(int,input().split()))for _ in range(n)]
  def_l=[list(map(int,input().split()))for _ in range(m)]
  x=[0]
  y=[0]
  for a,b,c in abc_l:
      x.append(a)
      x.append(b)
      y.append(c)
  for d,e,f in def_l:
      x.append(d)
      y.append(e)
      y.append(f)
  x=sorted(list(set(x)))
  y=sorted(list(set(y)))
  h=len(x)+1
  w=len(y)+1
  dicx={}
  dicy={}
  for i in range(len(x)):dicx[x[i]]=i
  for i in range(len(y)):dicy[y[i]]=i
  grid=[[0]*w for _ in range(h)]
  dont=set()
  for a,b,c in abc_l:
      for i in range(dicx[a],dicx[b]):
          dont.add(hashh(i+1,dicy[c],i+1,dicy[c]+1))
  for d,e,f in def_l:
      for j in range(dicy[e],dicy[f]):
          dont.add(hashh(dicx[d],j+1,dicx[d]+1,j+1))
  if dicx[0]==0 or dicx[0]==h-1 or dicy[0]==0 or dicy[0]==w-1:
      exit(print("INF"))
  stack=[(dicx[0],dicy[0])]
  grid[dicx[0]][dicy[0]]=1
  ans=0
  for sx,sy in stack:
      ans+=(x[sx]-x[sx-1])*(y[sy]-y[sy-1])
      for dx,dy in ((-1,0),(1,0),(0,-1),(0,1)):
          tx=sx+dx
          ty=sy+dy
          if grid[tx][ty]:continue
          if hashh(sx,sy,tx,ty) in dont:continue
          if tx==0 or tx==h-1 or ty==0 or ty==w-1:
              exit(print("INF"))
          grid[tx][ty]=1
          stack.append((tx,ty))
  print(ans)
main()

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
def hashh(x1,y1,x2,y2):
    if x1>x2:
        x1,y1,x2,y2=x2,y2,x1,y1
    if x1==x2 and y1>y2:
        x1,y1,x2,y2=x2,y2,x1,y1
    return x1*27000000000+y1*9000000+x2*3000+y2
abc_l=[list(map(int,input().split()))for _ in range(n)]
def_l=[list(map(int,input().split()))for _ in range(m)]
x=[0]
y=[0]
for a,b,c in abc_l:
    x.append(a)
    x.append(b)
    y.append(c)
for d,e,f in def_l:
    x.append(d)
    y.append(e)
    y.append(f)
x=sorted(list(set(x)))
y=sorted(list(set(y)))
h=len(x)+1
w=len(y)+1
dicx={}
dicy={}
for i in range(len(x)):dicx[x[i]]=i
for i in range(len(y)):dicy[y[i]]=i
grid=[[0]*w for _ in range(h)]
dont=set()
for a,b,c in abc_l:
    for i in range(dicx[a],dicx[b]):
        dont.add(hashh(i+1,dicy[c],i+1,dicy[c]+1))
for d,e,f in def_l:
    for j in range(dicy[e],dicy[f]):
        dont.add(hashh(dicx[d],j+1,dicx[d]+1,j+1))
if dicx[0]==0 or dicx[0]==h-1 or dicy[0]==0 or dicy[0]==w-1:
    exit(print("INF"))
stack=[(dicx[0],dicy[0])]
grid[dicx[0]][dicy[0]]=1
ans=0
for sx,sy in stack:
    ans+=(x[sx]-x[sx-1])*(y[sy]-y[sy-1])
    for dx,dy in ((-1,0),(1,0),(0,-1),(0,1)):
        tx=sx+dx
        ty=sy+dy
        if grid[tx][ty]:continue
        if hashh(sx,sy,tx,ty) in dont:continue
        if tx==0 or tx==h-1 or ty==0 or ty==w-1:
            exit(print("INF"))
        grid[tx][ty]=1
        stack.append((tx,ty))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
def hashh(x1,y1,x2,y2):
    if x1>x2:
        x1,y1,x2,y2=x2,y2,x1,y1
    if x1==x2 and y1>y2:
        x1,y1,x2,y2=x2,y2,x1,y1
    return (x1 << 48) + (y1 << 32) + (x2 << 16)  +y2
abc_l=[list(map(int,input().split()))for _ in range(n)]
def_l=[list(map(int,input().split()))for _ in range(m)]
x=[0]
y=[0]
for a,b,c in abc_l:
    x.append(a)
    x.append(b)
    y.append(c)
for d,e,f in def_l:
    x.append(d)
    y.append(e)
    y.append(f)
x=sorted(list(set(x)))
y=sorted(list(set(y)))
h=len(x)+1
w=len(y)+1
dicx={}
dicy={}
for i in range(len(x)):dicx[x[i]]=i
for i in range(len(y)):dicy[y[i]]=i
grid=[[0]*w for _ in range(h)]
dont=set()
for a,b,c in abc_l:
    for i in range(dicx[a],dicx[b]):
        dont.add(hashh(i+1,dicy[c],i+1,dicy[c]+1))
for d,e,f in def_l:
    for j in range(dicy[e],dicy[f]):
        dont.add(hashh(dicx[d],j+1,dicx[d]+1,j+1))
if dicx[0]==0 or dicx[0]==h-1 or dicy[0]==0 or dicy[0]==w-1:
    exit(print("INF"))
stack=[(dicx[0],dicy[0])]
grid[dicx[0]][dicy[0]]=1
ans=0
for sx,sy in stack:
    ans+=(x[sx]-x[sx-1])*(y[sy]-y[sy-1])
    for dx,dy in ((-1,0),(1,0),(0,-1),(0,1)):
        tx=sx+dx
        ty=sy+dy
        if grid[tx][ty]:continue
        if hashh(sx,sy,tx,ty) in dont:continue
        if tx==0 or tx==h-1 or ty==0 or ty==w-1:
            exit(print("INF"))
        grid[tx][ty]=1
        stack.append((tx,ty))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
def hashh(x1,y1,x2,y2):
    if x1>x2:
        x1,y1,x2,y2=x2,y2,x1,y1
    if x1==x2 and y1>y2:
        x1,y1,x2,y2=x2,y2,x1,y1
    return (x1, y1, x2, y2)
abc_l=[list(map(int,input().split()))for _ in range(n)]
def_l=[list(map(int,input().split()))for _ in range(m)]
x=[0]
y=[0]
for a,b,c in abc_l:
    x.append(a)
    x.append(b)
    y.append(c)
for d,e,f in def_l:
    x.append(d)
    y.append(e)
    y.append(f)
x=sorted(list(set(x)))
y=sorted(list(set(y)))
h=len(x)+1
w=len(y)+1
dicx={}
dicy={}
for i in range(len(x)):dicx[x[i]]=i
for i in range(len(y)):dicy[y[i]]=i
grid=[[0]*w for _ in range(h)]
dont=set()
for a,b,c in abc_l:
    for i in range(dicx[a],dicx[b]):
        dont.add(hashh(i+1,dicy[c],i+1,dicy[c]+1))
for d,e,f in def_l:
    for j in range(dicy[e],dicy[f]):
        dont.add(hashh(dicx[d],j+1,dicx[d]+1,j+1))
if dicx[0]==0 or dicx[0]==h-1 or dicy[0]==0 or dicy[0]==w-1:
    exit(print("INF"))
stack=[(dicx[0],dicy[0])]
grid[dicx[0]][dicy[0]]=1
ans=0
for sx,sy in stack:
    ans+=(x[sx]-x[sx-1])*(y[sy]-y[sy-1])
    for dx,dy in ((-1,0),(1,0),(0,-1),(0,1)):
        tx=sx+dx
        ty=sy+dy
        if grid[tx][ty]:continue
        if hashh(sx,sy,tx,ty) in dont:continue
        if tx==0 or tx==h-1 or ty==0 or ty==w-1:
            exit(print("INF"))
        grid[tx][ty]=1
        stack.append((tx,ty))
print(ans)