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:
import sys
from collections import defaultdict, deque

input = sys.stdin.readline
n, m = map(int, input().split())

xx = set([0]); yy = set([0]);
aa = []; bb = []; cc = []; dd = []; ee = []; ff = []; 
for _ in range(n):
    a, b, c = map(int, input().split())
    xx.add(a)
    xx.add(b)
    yy.add(c)
    aa.append(a); bb.append(b); cc.append(c); 
for _ in range(m):
    d, e, f = map(int, input().split())
    xx.add(d)
    yy.add(e)
    yy.add(f)
    dd.append(d); ee.append(e); ff.append(f); 
xx = sorted(list(xx))
yy = sorted(list(yy))
xp = defaultdict(int)
yp = defaultdict(int)

for i, v in enumerate(xx):
    xp[v] = i
for i, v in enumerate(yy):
    yp[v] = i

h = len(xx) - 1
w = len(yy) - 1
field = [[[0, 0, 0, 0] for _ in range(w)] for _ in range(h)]

for i in range(n):
    a, b, c = aa[i], bb[i], cc[i]
    for x in range(xp[a], xp[b]):
        if yp[c] < w:
            field[x][yp[c]][1] = 1
        if yp[c] - 1 >= 0:
            field[x][yp[c] - 1][3] = 1

for i in range(m):
    d, e, f = dd[i], ee[i], ff[i]
    for y in range(yp[e], yp[f]):
        if xp[d] < h:
            field[xp[d]][y][0] = 1
        if xp[d] - 1 >= 0:
            field[xp[d] - 1][y][2] = 1

visited = [[False for _ in range(w)] for _ in range(h)]
sx, sy = min(xp[0], h - 1), min(yp[0], w - 1)
visited[sx][sy] = True
q = deque([(sx, sy)])
ans = 0

while q:
    x, y = q.popleft()
    ans += (xx[x + 1] - xx[x]) * (yy[y + 1] - yy[y])
    if field[x][y][0] == 0:
        if x == 0:
            print('INF'); exit();
        if not visited[x - 1][y]:
            visited[x - 1][y] = True
            q.append((x - 1, y))
    if field[x][y][1] == 0:
        if y == 0:
            print('INF'); exit();
        if not visited[x][y - 1]:
            visited[x][y - 1] = True
            q.append((x, y - 1))
    if field[x][y][2] == 0:
        if x == h - 1:
            print('INF'); exit();
        if not visited[x + 1][y]:
            visited[x + 1][y] = True
            q.append((x + 1, y))
    if field[x][y][3] == 0:
        if y == w - 1:
            print('INF'); exit();
        if not visited[x][y + 1]:
            visited[x][y + 1] = True
            q.append((x, y + 1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict, deque

input = sys.stdin.readline
n, m = map(int, input().split())

xx = [0]; yy = [0];
aa = []; bb = []; cc = []; dd = []; ee = []; ff = []; 
for _ in range(n):
    a, b, c = map(int, input().split())
    xx.append(a)
    xx.append(b)
    yy.append(c)
    aa.append(a); bb.append(b); cc.append(c); 
for _ in range(m):
    d, e, f = map(int, input().split())
    xx.append(d)
    yy.append(e)
    yy.append(f)
    dd.append(d); ee.append(e); ff.append(f); 
xx.sort()
yy.sort()
xp = defaultdict(int)
yp = defaultdict(int)
xa = []
ya = []

prev = 99999999999
idx = 0
for v in xx:
    if v == prev:
        continue
    xp[v] = idx
    if idx != 0:
        xa.append(v - prev)
    prev = v
    idx += 1
prev = 99999999999
idx = 0
for v in yy:
    if v == prev:
        continue
    yp[v] = idx
    if idx != 0:
        ya.append(v - prev)
    prev = v
    idx += 1

h = len(xa)
w = len(ya)
field = [[[0, 0, 0, 0] for _ in range(w)] for _ in range(h)]

for i in range(n):
    a, b, c = aa[i], bb[i], cc[i]
    for x in range(xp[a], xp[b]):
        if yp[c] < w:
            field[x][yp[c]][1] = 1
        if yp[c] - 1 >= 0:
            field[x][yp[c] - 1][3] = 1
                
for i in range(m):
    d, e, f = dd[i], ee[i], ff[i]
    for y in range(yp[e], yp[f]):
        if xp[d] < h:
            field[xp[d]][y][0] = 1
        if xp[d] - 1 >= 0:
            field[xp[d] - 1][y][2] = 1

visited = [[False for _ in range(w)] for _ in range(h)]
sx, sy = min(xp[0], h - 1), min(yp[0], w - 1)
visited[sx][sy] = True
q = deque([(sx, sy)])
ans = 0

while q:
    x, y = q.popleft()
    ans += xa[x] * ya[y]
    if field[x][y][0] == 0:
        if x == 0:
            print('INF'); exit();
        if not visited[x - 1][y]:
            visited[x - 1][y] = True
            q.append((x - 1, y))
    if field[x][y][1] == 0:
        if y == 0:
            print('INF'); exit();
        if not visited[x][y - 1]:
            visited[x][y - 1] = True
            q.append((x, y - 1))
    if field[x][y][2] == 0:
        if x == h - 1:
            print('INF'); exit();
        if not visited[x + 1][y]:
            visited[x + 1][y] = True
            q.append((x + 1, y))
    if field[x][y][3] == 0:
        if y == w - 1:
            print('INF'); exit();
        if not visited[x][y + 1]:
            visited[x][y + 1] = True
            q.append((x, y + 1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

from heapq import heappush, heappop
import sys
import numpy as np

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
# INF = sys.maxsize
INF = 10 ** 10
# INF = float("inf")


def dp(*x):  # debugprint
    print(*x)


try:
    profile
except:
    def profile(f): return f


def main(N, M, data):
    # vlines = defaultdict(lambda: [(0, 0)])
    vlines = {}
    # hlines = defaultdict(lambda: [(0, 0)])
    hlines = {}
    # vticks = {0}
    vticks = {0}
    # hticks = {0}
    hticks = {0}

    ABC = data[:3 * N]
    DEF = data[3 * N:]
    A, B, C = [ABC[i::3] for i in range(3)]
    D, E, F = [DEF[i::3] for i in range(3)]

    xticks = np.unique(np.concatenate((E, F, C, np.array([-INF, 0, INF]))))
    yticks = np.unique(np.concatenate((A, B, D, np.array([-INF, 0, INF]))))
    width = xticks[1:] - xticks[:-1]
    height = yticks[1:] - yticks[:-1]

    # compress
    A = np.searchsorted(yticks, A)
    B = np.searchsorted(yticks, B)
    C = np.searchsorted(xticks, C)
    D = np.searchsorted(yticks, D)
    E = np.searchsorted(xticks, E)
    F = np.searchsorted(xticks, F)

    GRAPH_WIDTH = len(xticks)
    GRAPH_HEIGHT = len(yticks)
    NUM_VERTEXES = GRAPH_HEIGHT * GRAPH_WIDTH

    ng_egdes = np.zeros((NUM_VERTEXES, 4), dtype=np.bool_)
    #ng_egdes = csr_matrix((NUM_VERTEXES, 4), dtype=np.bool_)
    direction = (-1, +1, -GRAPH_WIDTH, +GRAPH_WIDTH)

    # vertical lines A,C-B,C
    for i in range(N):
        x = C[i]
        for y in range(A[i], B[i]):
            pos = y * GRAPH_WIDTH + x
            ng_egdes[pos, 0] = 1  # left
            ng_egdes[pos - 1, 1] = 1  # right

    # horizontal lines D,E-D,F
    for i in range(M):
        y = D[i]
        for x in range(E[i], F[i]):
            pos = y * GRAPH_WIDTH + x
            ng_egdes[pos, 2] = 1
            ng_egdes[pos - GRAPH_WIDTH, 3] = 1

    A = B = C = D = E = F = 0

    total_area = 0
    #visited = np.zeros(N)
    visited = set()
    x = np.searchsorted(xticks, 0)
    y = np.searchsorted(yticks, 0)
    start = y * GRAPH_WIDTH + x
    to_visit = [start]

    while to_visit:
        pos = to_visit.pop()
        y, x = divmod(pos, GRAPH_WIDTH)
        if pos in visited:
            continue
        if y == 0 or y == GRAPH_HEIGHT - 1 or x == 0 or x == GRAPH_WIDTH - 1:
            print("INF")
            break

        total_area += width[x] * height[y]
        visited.add(pos)
        # plan to visit neighbors
        for i in range(4):
            if not ng_egdes[pos, i]:
                to_visit.append(pos + direction[i])
    else:
        print(total_area)


if sys.argv[-1] == 'ONLINE_JUDGE' or sys.argv[-1] == '-c':
    print("compiling")
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export(
        'main',
        "void(i8, i8, i8[:])"
    )(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
    exit()
else:
    if 0 and sys.argv[-1] != '-p':
        # -p: pure python mode
        # if not -p, import compiled module
        from my_module import main  # pylint: disable=all

    # read parameter
    import numba
    N, M = map(int, input().split())
    data = np.int64(sys.stdin.read().split())
    main(N, M, data)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

from collections import defaultdict
from heapq import heappush, heappop
import sys
import bisect

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
# INF = sys.maxsize
INF = 10 ** 10
# INF = float("inf")


def dp(*x):  # debugprint
    print(*x)


# f = open(sys.argv[1])
# input = f.buffer.readline

N, M = map(int, input().split())
vlines = defaultdict(list)
hlines = defaultdict(list)
vticks = {0}
hticks = {0}

for i in range(N):
    A, B, C = map(int, input().split())
    vlines[C].append((A, B))
    hticks.add(C)
    vticks.update((A, B))

for i in range(M):
    D, E, F = map(int, input().split())
    hlines[D].append((E, F))
    vticks.add(D)
    hticks.update((E, F))

vticks = [-INF] + list(sorted(vticks)) + [INF]
hticks = [-INF] + list(sorted(hticks)) + [INF]


def up(y):
    return vticks[bisect.bisect_left(vticks, y) - 1]


def down(y):
    return vticks[bisect.bisect_left(vticks, y) + 1]


def left(x):
    return hticks[bisect.bisect_left(hticks, x) - 1]


def right(x):
    return hticks[bisect.bisect_left(hticks, x) + 1]


def area(i, j):
    width = hticks[i + 1] - hticks[i]
    height = vticks[j + 1] - vticks[j]
    return width * height


total_area = 0
visited = set()


def visit(i, j):
    global total_area
    if (i, j) in visited:
        return
    # dp("visit: (i,j)", (i, j))
    x = hticks[i]
    y = vticks[j]
    a = area(i, j)
    total_area += a
    visited.add((i, j))
    # visit neighbors
    l = i - 1
    if (l, j) not in visited:
        for a, b in vlines[x]:
            if a <= y < b:
                # blocked
                break
        else:
            # can move left
            to_visit.append((l, j))

    u = j - 1
    if (i, u) not in visited:
        for a, b in hlines[y]:
            if a <= x < b:
                # blocked
                break
        else:
            # can move up
            to_visit.append((i, u))

    r = i + 1
    if (r, j) not in visited:
        for a, b in vlines[hticks[r]]:
            if a <= y < b:
                # blocked
                break
        else:
            # can move left
            to_visit.append((r, j))

    d = j + 1
    if (i, d) not in visited:
        for a, b in hlines[vticks[d]]:
            if a <= x < b:
                # blocked
                break
        else:
            # can move up
            to_visit.append((i, d))


maxH = len(hticks) - 2
maxV = len(vticks) - 2
# dp(": maxH, maxV", maxH, maxV)
i = bisect.bisect_left(hticks, 0)
j = bisect.bisect_left(vticks, 0)
to_visit = [(i, j)]

while to_visit:
    i, j = to_visit.pop()
    # dp(": (i,j)", (i, j))
    if i == 0 or i == maxH or j == 0 or j == maxV:
        print("INF")
        break
    visit(i, j)
    # dp(": to_visit", to_visit)
else:
    print(total_area)


def _test():
    import doctest
    doctest.testmod()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

from collections import defaultdict
from heapq import heappush, heappop
import sys
import bisect

sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
# INF = sys.maxsize
INF = 10 ** 10
# INF = float("inf")


def dp(*x):  # debugprint
    print(*x)


# f = open(sys.argv[1])
# input = f.buffer.readline

N, M = map(int, input().split())
vlines = defaultdict(list)
hlines = defaultdict(list)
vticks = {0}
hticks = {0}

for i in range(N):
    A, B, C = map(int, input().split())
    vlines[C].append((A, B))
    hticks.add(C)
    vticks.update((A, B))

for i in range(M):
    D, E, F = map(int, input().split())
    hlines[D].append((E, F))
    vticks.add(D)
    hticks.update((E, F))

vticks = [-INF] + list(sorted(vticks)) + [INF, INF]
hticks = [-INF] + list(sorted(hticks)) + [INF, INF]


def up(y):
    return vticks[bisect.bisect_left(vticks, y) - 1]


def down(y):
    return vticks[bisect.bisect_left(vticks, y) + 1]


def left(x):
    return hticks[bisect.bisect_left(hticks, x) - 1]


def right(x):
    return hticks[bisect.bisect_left(hticks, x) + 1]


def area(x, y):
    i = bisect.bisect_left(hticks, x)
    width = hticks[i + 1] - hticks[i]
    j = bisect.bisect_left(vticks, y)
    height = vticks[j + 1] - vticks[j]
    return width * height


total_area = 0
visited = set()


def visit(x, y):
    global total_area
    if (x, y) in visited:
        return
    # dp("visited: x,y", x, y)
    a = area(x, y)
    total_area += a
    visited.add((x, y))
    # visit neighbors
    l = left(x)
    if (l, y) not in visited:
        for a, b in vlines[x]:
            if a <= y < b:
                # blocked
                break
        else:
            # can move left
            to_visit.append((l, y))

    u = up(y)
    if (x, u) not in visited:
        for a, b in hlines[y]:
            if a <= x < b:
                # blocked
                break
        else:
            # can move up
            to_visit.append((x, u))

    r = right(x)
    if (r, y) not in visited:
        for a, b in vlines[r]:
            if a <= y < b:
                # blocked
                break
        else:
            # can move left
            to_visit.append((r, y))

    d = down(y)
    if (x, d) not in visited:
        for a, b in hlines[d]:
            if a <= x < b:
                # blocked
                break
        else:
            # can move up
            to_visit.append((x, d))


# for y in [up(0), 0]:
#     for x in [left(0), 0]:
#         visit(x, y)
# print(total_area)
to_visit = [(0, 0)]
while to_visit:
    x, y = to_visit.pop()
    if x == INF or x == -INF or y == INF or y == -INF:
        print("INF")
        break
    visit(x, y)
else:
    print(total_area)


def _test():
    import doctest
    doctest.testmod()

Submission status: Time Limit Exceeded

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


def compress_coordinate(x: list, key=None, reverse=False):
    zipped = {}
    unzipped = {}
    for i, xi in enumerate(sorted(set(x), key=key, reverse=reverse)):
        zipped[xi] = i
        unzipped[i] = xi
    return zipped, unzipped


n, m = map(int, input().split())
line_v = [tuple(map(int, input().split())) for _ in range(n)]
line_h = [tuple(map(int, input().split())) for _ in range(m)]

INF = 10**9 + 10
dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]

x_list = [-INF, 0, INF]
y_list = [-INF, 0, INF]
for x1, x2, y in line_v:
    # abc
    x_list.append(x1)
    x_list.append(x2)
    y_list.append(y)
for x, y1, y2 in line_h:
    # def
    x_list.append(x)
    y_list.append(y1)
    y_list.append(y2)

x_zipped, x_unzipped = compress_coordinate(x_list)
y_zipped, y_unzipped = compress_coordinate(y_list)

nx = len(x_zipped)
ny = len(y_zipped)

v_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
h_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
for x1, x2, y in line_v:
    x1 = x_zipped[x1]
    x2 = x_zipped[x2]
    y = y_zipped[y]
    v_ng[x1][y] += 1
    v_ng[x2][y] -= 1
for x, y1, y2 in line_h:
    x = x_zipped[x]
    y1 = y_zipped[y1]
    y2 = y_zipped[y2]
    h_ng[x][y1] += 1
    h_ng[x][y2] -= 1

for x in range(nx):
    for y in range(ny):
        v_ng[x + 1][y] += v_ng[x][y]
        h_ng[x][y + 1] += h_ng[x][y]

# print(nx, ny)
grid = [[False] * (ny + 1) for _ in range(nx + 1)]
q = [(x_zipped[0], y_zipped[0])]
while q:
    x0, y0 = q.pop()
    if grid[x0][y0]:
        continue
    grid[x0][y0] = True
    for k in range(4):
        x1 = x0 + dx[k]
        y1 = y0 + dy[k]
        if x1 < 0 or x1 >= nx or y1 < 0 or y1 >= ny:
            continue
        if grid[x1][y1]:
            continue

        if k == 0 and h_ng[x1][y1] == 0:
            # move x-dir
            q.append((x1, y1))
        elif k == 2 and h_ng[x0][y0] == 0:
            # move x-dir
            q.append((x1, y1))
        elif k == 1 and v_ng[x1][y1] == 0:
            # move y-dir
            q.append((x1, y1))
        elif k == 3 and v_ng[x0][y0] == 0:
            # move y-dir
            q.append((x1, y1))

# print(*grid, sep='\n')
if grid[0][0]:
    ans = 'INF'
else:
    ans = 0
    for x in range(nx):
        for y in range(ny):
            if grid[x][y]:
                ans += (x_unzipped[x + 1] -
                        x_unzipped[x]) * (y_unzipped[y + 1] - y_unzipped[y])

print(ans)

Submission status: Time Limit Exceeded

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


def compress_coordinate(x: list, key=None, reverse=False):
    zipped = {}
    unzipped = {}
    for i, xi in enumerate(sorted(set(x), key=key, reverse=reverse)):
        zipped[xi] = i
        unzipped[i] = xi
    return zipped, unzipped


n, m = map(int, input().split())
line_v = [tuple(map(int, input().split())) for _ in range(n)]
line_h = [tuple(map(int, input().split())) for _ in range(m)]

INF = 10**9 + 10
dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]

x_list = [-INF, 0, INF]
y_list = [-INF, 0, INF]
for x1, x2, y in line_v:
    # abc
    x_list.append(x1)
    x_list.append(x2)
    y_list.append(y)
for x, y1, y2 in line_h:
    # def
    x_list.append(x)
    y_list.append(y1)
    y_list.append(y2)

x_zipped, x_unzipped = compress_coordinate(x_list)
y_zipped, y_unzipped = compress_coordinate(y_list)

nx = len(x_zipped)
ny = len(y_zipped)

v_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
h_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
for x1, x2, y in line_v:
    x1 = x_zipped[x1]
    x2 = x_zipped[x2]
    y = y_zipped[y]
    v_ng[x1][y] += 1
    v_ng[x2][y] -= 1
for x, y1, y2 in line_h:
    x = x_zipped[x]
    y1 = y_zipped[y1]
    y2 = y_zipped[y2]
    h_ng[x][y1] += 1
    h_ng[x][y2] -= 1

for x in range(nx):
    for y in range(ny):
        v_ng[x + 1][y] += v_ng[x][y]
        h_ng[x][y + 1] += h_ng[x][y]

# print(nx, ny)
grid = [[False] * (ny + 1) for _ in range(nx + 1)]
q = [(x_zipped[0], y_zipped[0])]
while q:
    x0, y0 = q.pop()
    grid[x0][y0] = True
    for k in range(4):
        x1 = x0 + dx[k]
        y1 = y0 + dy[k]
        if x1 < 0 or x1 >= nx or y1 < 0 or y1 >= ny:
            continue
        if grid[x1][y1]:
            continue

        if k == 0 and h_ng[x1][y1] == 0:
            # move x-dir
            q.append((x1, y1))
        elif k == 2 and h_ng[x0][y0] == 0:
            # move x-dir
            q.append((x1, y1))
        elif k == 1 and v_ng[x1][y1] == 0:
            # move y-dir
            q.append((x1, y1))
        elif k == 3 and v_ng[x0][y0] == 0:
            # move y-dir
            q.append((x1, y1))

# print(*grid, sep='\n')
if grid[0][0]:
    ans = 'INF'
else:
    ans = 0
    for x in range(nx):
        for y in range(ny):
            if grid[x][y]:
                ans += (x_unzipped[x + 1] -
                        x_unzipped[x]) * (y_unzipped[y + 1] - y_unzipped[y])

print(ans)

Submission status: Time Limit Exceeded

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


def compress_coordinate(x: list, key=None, reverse=False):
    zipped = {}
    unzipped = {}
    for i, xi in enumerate(sorted(set(x), key=key, reverse=reverse)):
        zipped[xi] = i
        unzipped[i] = xi
    return zipped, unzipped


n, m = map(int, input().split())
line_v = [tuple(map(int, input().split())) for _ in range(n)]
line_h = [tuple(map(int, input().split())) for _ in range(m)]

INF = 10**9 + 10
dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]

x_list = [-INF, 0, INF]
y_list = [-INF, 0, INF]
for x1, x2, y in line_v:
    # abc
    x_list.append(x1)
    x_list.append(x2)
    y_list.append(y)
for x, y1, y2 in line_h:
    # def
    x_list.append(x)
    y_list.append(y1)
    y_list.append(y2)

x_zipped, x_unzipped = compress_coordinate(x_list)
y_zipped, y_unzipped = compress_coordinate(y_list)

nx = len(x_zipped)
ny = len(y_zipped)

v_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
h_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
for x1, x2, y in line_v:
    x1 = x_zipped[x1]
    x2 = x_zipped[x2]
    y = y_zipped[y]
    v_ng[x1][y] += 1
    v_ng[x2][y] -= 1
for x, y1, y2 in line_h:
    x = x_zipped[x]
    y1 = y_zipped[y1]
    y2 = y_zipped[y2]
    h_ng[x][y1] += 1
    h_ng[x][y2] -= 1

for x in range(nx):
    for y in range(ny):
        v_ng[x + 1][y] += v_ng[x][y]
        h_ng[x][y + 1] += h_ng[x][y]

# print(nx, ny)
grid = [[False] * (ny + 1) for _ in range(nx + 1)]
q = [(x_zipped[0], y_zipped[0])]
while q:
    x0, y0 = q.pop()
    grid[x0][y0] = True
    for k in range(4):
        x1 = x0 + dx[k]
        y1 = y0 + dy[k]
        if x1 < 0 or x1 >= nx or y1 < 0 or y1 >= ny:
            continue
        if grid[x1][y1]:
            continue

        if k == 0 and h_ng[x1][y1] == 0:
            # move x-dir
            q.append((x1, y1))
        if k == 2 and h_ng[x0][y0] == 0:
            # move x-dir
            q.append((x1, y1))
        if k == 1 and v_ng[x1][y1] == 0:
            # move y-dir
            q.append((x1, y1))
        if k == 3 and v_ng[x0][y0] == 0:
            # move y-dir
            q.append((x1, y1))

# print(*grid, sep='\n')
c_start = x_zipped[0] * ny + y_zipped[0]
if grid[0][0]:
    ans = 'INF'
else:
    ans = 0
    for x in range(nx):
        for y in range(ny):
            if grid[x][y]:
                ans += (x_unzipped[x + 1] -
                        x_unzipped[x]) * (y_unzipped[y + 1] - y_unzipped[y])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
input = sys.stdin.readline


def compress_coordinate(x: list, key=None, reverse=False):
    zipped = {}
    unzipped = {}
    for i, xi in enumerate(sorted(set(x), key=key, reverse=reverse)):
        zipped[xi] = i
        unzipped[i] = xi
    return zipped, unzipped


n, m = map(int, input().split())
line_v = [tuple(map(int, input().split())) for _ in range(n)]
line_h = [tuple(map(int, input().split())) for _ in range(m)]

INF = 10**9 + 10
dx = [+1, 0, -1, 0]
dy = [0, +1, 0, -1]

x_list = [-INF, 0, INF]
y_list = [-INF, 0, INF]
for x1, x2, y in line_v:
    # abc
    x_list.append(x1)
    x_list.append(x2)
    y_list.append(y)
for x, y1, y2 in line_h:
    # def
    x_list.append(x)
    y_list.append(y1)
    y_list.append(y2)

x_zipped, x_unzipped = compress_coordinate(x_list)
y_zipped, y_unzipped = compress_coordinate(y_list)

nx = len(x_zipped)
ny = len(y_zipped)

v_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
h_ng = [[0] * (ny + 1) for _ in range(nx + 1)]
for x1, x2, y in line_v:
    x1 = x_zipped[x1]
    x2 = x_zipped[x2]
    y = y_zipped[y]
    v_ng[x1][y] += 1
    v_ng[x2][y] -= 1
for x, y1, y2 in line_h:
    x = x_zipped[x]
    y1 = y_zipped[y1]
    y2 = y_zipped[y2]
    h_ng[x][y1] += 1
    h_ng[x][y2] -= 1

for x in range(nx):
    for y in range(ny):
        v_ng[x + 1][y] += v_ng[x][y]
        h_ng[x][y + 1] += h_ng[x][y]

# print(nx, ny)
grid = [[False] * (ny + 1) for _ in range(nx + 1)]
q = deque([(x_zipped[0], y_zipped[0])])
while q:
    x0, y0 = q.popleft()
    grid[x0][y0] = True
    for k in range(4):
        x1 = x0 + dx[k]
        y1 = y0 + dy[k]
        if x1 < 0 or x1 >= nx or y1 < 0 or y1 >= ny:
            continue
        if grid[x1][y1]:
            continue

        if k == 0 and h_ng[x1][y1] == 0:
            # move x-dir
            q.append((x1, y1))
        if k == 2 and h_ng[x0][y0] == 0:
            # move x-dir
            q.append((x1, y1))

        if k == 1 and v_ng[x1][y1] == 0:
            # move y-dir
            q.append((x1, y1))
        if k == 3 and v_ng[x0][y0] == 0:
            # move y-dir
            q.append((x1, y1))

# print(*grid, sep='\n')
c_start = x_zipped[0] * ny + y_zipped[0]
if grid[0][0]:
    ans = 'INF'
else:
    ans = 0
    for x in range(nx):
        for y in range(ny):
            if grid[x][y]:
                ans += (x_unzipped[x + 1] -
                        x_unzipped[x]) * (y_unzipped[y + 1] - y_unzipped[y])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=[0]+f;Y=X[:];R=(f,F),(f,-F),;H=(F,f),(-F,f),
for i in r(n):*a,c=I();R+=(a,c),;Y+=c,;X+=a
for i in r(m):a,*b=I();H+=(a,b),;X+=a,;Y+=b
def g(X):s=sorted(set(X));l=len(s);return{s[i]:i for i in r(l)},s,l
h,s,K=g(X);w,t,L=g(Y);V,U,v=[[[0]*-~K for i in r(L+1)]for _ in r(3)];q=[(h[0],w[0])];z=0
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]-=1
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]-=1
for i in r(L):
 for j in r(K):U[i][j+1]+=U[i][j];V[i+1][j]+=V[i][j]
while q:
 x,y=q.pop();v[y][x]=1;z+=(s[x]-s[x+1])*(t[y]-t[y+1])
 for e,f in(-1,0),(1,0),(0,1),(0,-1),:
  c=x+e;d=y+f
  if(1-v[d][c])*(0==U[(f>0)+y][x]*f+V[y][(e>0)+x]*e):q+=(c,d),;v[d][c]=1
print([z,'INF'][z>F])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque
INF = 10**20 

n, m = map(int, input().split())
xseen = set()
xseen.add(INF); xseen.add(-INF)
yseen = set()
yseen.add(INF); yseen.add(-INF)
a_b_c = []
for _ in range(n):
    a, b, c = map(int, input().split())
    xseen.add(a)
    xseen.add(b)
    yseen.add(c)
    a_b_c.append((a, b, c))
d_e_f = []
for _ in range(m):
    d, e, f = map(int, input().split())
    xseen.add(d)
    yseen.add(e)
    yseen.add(f)
    d_e_f.append((d, e, f))

xlen = len(xseen) * 2 - 1
ylen = len(yseen) * 2 - 1

xseen = sorted(list(xseen))
xcomp = {val:i for i, val in enumerate(xseen)}
yseen = sorted(list(yseen))
ycomp = {val:i for i, val in enumerate(yseen)}

field = [[False] * ylen for _ in range(xlen)]
x_range = [0] * xlen
y_range = [0] * ylen
x_range[0] = x_range[-1] = INF
y_range[0] = y_range[-1] = INF
for i, (x1, x2) in enumerate(zip(xseen, xseen[1:])):
    x_range[i * 2 + 1] = x2 - x1
    if x1 <= 0 <= x2:
        sx = i * 2 + 1
for i, (y1, y2) in enumerate(zip(yseen, yseen[1:])):
    y_range[i * 2 + 1] = y2 - y1
    if y1 <= 0 <= y2:
        sy = i * 2 + 1
# print(sx, sy)

for a, b, c in a_b_c:
    y = ycomp[c] * 2
    for x in range(xcomp[a] * 2, xcomp[b] * 2 + 1):
        field[x][y] = True 

for d, e, f in d_e_f:
    x = xcomp[d] * 2
    for y in range(ycomp[e] * 2, ycomp[f] * 2 + 1):
        field[x][y] = True 

# for line in field:
#     print("".join([item for item in line]))

diff = ((0, 1), (1, 0), (-1, 0), (0, -1))
ans = 0

dq = deque([(sx, sy)])
field[sx][sy] = True 
ans += x_range[sx] * y_range[sy]
while dq:
    x, y = dq.popleft()
    for dx, dy in diff:
        nx, ny = dx + x, dy + y
        if field[nx][ny]:
            continue
        nx += dx; ny += dy
        if field[nx][ny]:
            continue
        field[nx][ny] = True 
        dq.append((nx, ny))
        ans += x_range[nx] * y_range[ny] 
        if ans >= INF:
            print("INF")
            exit()

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
from collections import deque
INF = 10**20 

n, m = map(int, input().split())
xseen = set()
xseen.add(INF); xseen.add(-INF)
yseen = set()
yseen.add(INF); yseen.add(-INF)
a_b_c = []
for _ in range(n):
    a, b, c = map(int, input().split())
    xseen.add(a)
    xseen.add(b)
    yseen.add(c)
    a_b_c.append((a, b, c))
d_e_f = []
for _ in range(m):
    d, e, f = map(int, input().split())
    xseen.add(d)
    yseen.add(e)
    yseen.add(f)
    d_e_f.append((d, e, f))

xlen = len(xseen) * 2 - 1
ylen = len(yseen) * 2 - 1

xseen = list(xseen)
xseen.sort()
xcomp = dict()
yseen = list(yseen)
yseen.sort()
ycomp = dict()
for i, item in enumerate(xseen):
    xcomp[item] = i
for i, item in enumerate(yseen):
    ycomp[item] = i

field = [[False] * ylen for _ in range(xlen)]
x_range = [0] * xlen
y_range = [0] * ylen
x_range[0] = x_range[-1] = INF
y_range[0] = y_range[-1] = INF
for i, (x1, x2) in enumerate(zip(xseen, xseen[1:])):
    x_range[i * 2 + 1] = x2 - x1
    if x1 <= 0 <= x2:
        sx = i * 2 + 1
for i, (y1, y2) in enumerate(zip(yseen, yseen[1:])):
    y_range[i * 2 + 1] = y2 - y1
    if y1 <= 0 <= y2:
        sy = i * 2 + 1
# print(sx, sy)

for a, b, c in a_b_c:
    y = ycomp[c] * 2
    for x in range(xcomp[a] * 2, xcomp[b] * 2 + 1):
        field[x][y] = True 

for d, e, f in d_e_f:
    x = xcomp[d] * 2
    for y in range(ycomp[e] * 2, ycomp[f] * 2 + 1):
        field[x][y] = True 

# for line in field:
#     print("".join([item for item in line]))

diff = ((0, 1), (1, 0), (-1, 0), (0, -1))
ans = 0

st = deque([(sx, sy)])
field[sx][sy] = True 
ans += x_range[sx] * y_range[sy]
while st:
    x, y = st.popleft()
    for dx, dy in diff:
        nx, ny = dx + x, dy + y
        if field[nx][ny]:
            continue
        nx += dx; ny += dy
        if field[nx][ny]:
            continue
        field[nx][ny] = True 
        st.append((nx, ny))
        h = x_range[nx]
        w = y_range[ny]
        ans += h * w 
        if ans >= INF:
            print("INF")
            exit()

print(ans)