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 bisect import bisect_left

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())
m = map(int, read().split())
A, B, C = zip(*zip(m, m, m))

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

X = sorted(set(A + B + D + (0, -INF, INF)))
Y = sorted(set(C + E + F + (0, -INF, INF)))
DX = [y - x for x, y in zip(X, X[1:])]
DY = [y - x for x, y in zip(Y, Y[1:])]

A = [bisect_left(X, x) for x in A]
B = [bisect_left(X, x) for x in B]
D = [bisect_left(X, x) for x in D]
C = [bisect_left(Y, x) for x in C]
E = [bisect_left(Y, x) for x in E]
F = [bisect_left(Y, x) for x in F]

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

ng = [[] for _ in range(N)]
for a, b, c in zip(A, B, C):
    for x in range(a, b):
        v = x * W + c
        ng[v].append(v - 1)
        if c != 0:
            ng[v - 1].append(v)
for d, e, f in zip(D, E, F):
    for y in range(e, f):
        v = d * W + y
        ng[v].append(v - W)
        if d != 0:
            ng[v - W].append(v)

x0, y0 = bisect_left(X, 0), bisect_left(Y, 0)
v0 = x0 * W + y0

visited = [0] * N
visited[v0] = 1
stack = [v0]
answer = DX[x0] * DY[y0]
while stack:
    v = stack.pop()
    ngv = ng[v]
    for dv in (-W, W, 1, -1):
        w = v + dv
        if w in ngv:
            continue
        x, y = divmod(w, W)
        if x in (0, H - 1) or y in (0, W - 1):
            print('INF')
            exit()
        elif visited[w]:
            continue
        else:
            answer += DX[x] * DY[y]
            stack.append(w)
            visited[w] = 1

print(answer)

Submission status: Memory Limit Exceeded

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

from collections import deque

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

X = [-10**9, 0, 10**9]
Y = [-10**9, 0, 10**9]

tate = []
yoko = []

for _ in range(N):
    a, b, c = map(int, input().split())
    X.append(a)
    X.append(b)
    Y.append(c)
    tate.append((a, b, c))

for _ in range(M):
    d, e, f = map(int, input().split())
    X.append(d)
    Y.append(e)
    Y.append(f)
    yoko.append((d, e, f))

X = sorted(set(X))
Y = sorted(set(Y))

Cx = {val: idx * 2 for idx, val in enumerate(X)}
Cy = {val: idx * 2 for idx, val in enumerate(Y)}

H = len(X) * 2 - 1
W = len(Y) * 2 - 1

G = [0] * (H * W)

for a, b, c in tate:
    j = Cy[c]
    for i in range(Cx[a], Cx[b] + 1):
        G[i * W + j] = -1

for d, e, f in yoko:
    i = Cx[d]
    for j in range(Cy[e], Cy[f] + 1):
        G[i * W + j] = -1

for i in range(1, H, 2):
    for j in range(1, W, 2):
        G[i * W + j] = (X[(i + 1) // 2] - X[(i - 1) // 2]) * (Y[(j + 1) // 2] - Y[(j - 1) // 2])

queue = [Cx[0] * W + Cy[0]]

visited = [0] * (H * W)
visited[Cx[0] * W + Cy[0]] = 1

res = 0

while queue:
    z = queue.pop()

    nz = z + W
    if G[nz] != -1 and not visited[nz]:
        nx = nz // W
        if nx == H - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        queue.append(nz)

    nz = z - W
    if G[nz] != -1 and not visited[nz]:
        nx = nz // W
        if nx == 0:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        queue.append(nz)

    nz = z + 1
    if G[nz] != -1 and not visited[nz]:
        ny = nz % W
        if ny == W - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        queue.append(nz)

    nz = z - 1
    if G[nz] != -1 and not visited[nz]:
        ny = nz % W
        if ny == 0:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        queue.append(nz)
else:
    print(res)

Submission status: Memory Limit Exceeded

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

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

X = [-10**9, 0, 10**9]
Y = [-10**9, 0, 10**9]

tate = []
yoko = []

for _ in range(N):
    a, b, c = map(int, input().split())
    X.append(a)
    X.append(b)
    Y.append(c)
    tate.append((a, b, c))

for _ in range(M):
    d, e, f = map(int, input().split())
    X.append(d)
    Y.append(e)
    Y.append(f)
    yoko.append((d, e, f))

X = sorted(set(X))
Y = sorted(set(Y))

Cx = {val: idx * 2 for idx, val in enumerate(X)}
Cy = {val: idx * 2 for idx, val in enumerate(Y)}

H = len(X) * 2 - 1
W = len(Y) * 2 - 1

G = [0] * (H * W)

for a, b, c in tate:
    j = Cy[c]
    for i in range(Cx[a], Cx[b] + 1):
        G[i * W + j] = -1

for d, e, f in yoko:
    i = Cx[d]
    for j in range(Cy[e], Cy[f] + 1):
        G[i * W + j] = -1

for i in range(1, H, 2):
    for j in range(1, W, 2):
        G[i * W + j] = (X[(i + 1) // 2] - X[(i - 1) // 2]) * (Y[(j + 1) // 2] - Y[(j - 1) // 2])

stack = [Cx[0] * W + Cy[0]]
visited = [0] * (H * W)
visited[Cx[0] * W + Cy[0]] = 1
res = 0

while stack:
    z = stack.pop()
    nz = z + 1
    if G[nz] != -1 and not visited[nz]:
        nx = nz // W
        if nx == H - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
    nz = z - 1
    if G[nz] != -1 and not visited[nz]:
        nx = nz // W
        if nx == 0:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
    nz = z + W
    if G[nz] != -1 and not visited[nz]:
        ny = nz % W
        if ny == W - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
    nz = z - W
    if G[nz] != -1 and not visited[nz]:
        ny = nz % W
        if ny == 0:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
else:
    print(res)

Submission status: Memory Limit Exceeded

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

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

X = [-10**9, 0, 10**9]
Y = [-10**9, 0, 10**9]

tate = []
yoko = []

for _ in range(N):
    a, b, c = map(int, input().split())
    X.append(a)
    X.append(b)
    Y.append(c)
    tate.append((a, b, c))

for _ in range(M):
    d, e, f = map(int, input().split())
    X.append(d)
    Y.append(e)
    Y.append(f)
    yoko.append((d, e, f))

X = sorted(set(X))
Y = sorted(set(Y))

Cx = {val: idx * 2 for idx, val in enumerate(X)}
Cy = {val: idx * 2 for idx, val in enumerate(Y)}

H = len(X) * 2 - 1
W = len(Y) * 2 - 1

G = [0] * (H * W)

for a, b, c in tate:
    j = Cy[c]
    for i in range(Cx[a], Cx[b] + 1):
        G[i * W + j] = -1

for d, e, f in yoko:
    i = Cx[d]
    for j in range(Cy[e], Cy[f] + 1):
        G[i * W + j] = -1

for i in range(1, H, 2):
    for j in range(1, W, 2):
        G[i * W + j] = (X[(i + 1) // 2] - X[(i - 1) // 2]) * (Y[(j + 1) // 2] - Y[(j - 1) // 2])

stack = [Cx[0] * W + Cy[0]]
visited = [0] * (H * W)
visited[Cx[0] * W + Cy[0]] = 1
res = 0

while stack:
    z = stack.pop()
    nz = z + 1
    if G[nz] != -1 and not visited[nz]:
        nx, ny = divmod(nz, W)
        if nx == 0 or nx == H - 1 or ny == 0 or ny == W - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
    nz = z - 1
    if G[nz] != -1 and not visited[nz]:
        nx, ny = divmod(nz, W)
        if nx == 0 or nx == H - 1 or ny == 0 or ny == W - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
    nz = z + W
    if G[nz] != -1 and not visited[nz]:
        nx, ny = divmod(nz, W)
        if nx == 0 or nx == H - 1 or ny == 0 or ny == W - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
    nz = z - W
    if G[nz] != -1 and not visited[nz]:
        nx, ny = divmod(nz, W)
        if nx == 0 or nx == H - 1 or ny == 0 or ny == W - 1:
            print('INF')
            break
        visited[nz] = 1
        res += G[nz]
        stack.append(nz)
else:
    print(res)

Submission status: Memory 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 ** 9 + 1
# INF = float("inf")


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


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


def main(N, M, data):
    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).astype(np.int16)
    B = np.searchsorted(yticks, B).astype(np.int16)
    C = np.searchsorted(xticks, C).astype(np.int16)
    D = np.searchsorted(yticks, D).astype(np.int16)
    E = np.searchsorted(xticks, E).astype(np.int16)
    F = np.searchsorted(xticks, F).astype(np.int16)

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

#    ng_egdes = np.zeros((NUM_VERTEXES, 4), dtype=np.uint8)
    ng_edges = np.zeros(NUM_VERTEXES, dtype=np.uint8)

    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
            ng_edges[pos] |= 0b0001  # left
            ng_edges[pos - 1] |= 0b0010  # right
    A = B = C = 0

    # 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_edges[pos] |= 0b0100
            ng_edges[pos - GRAPH_WIDTH] |= 0b1000
    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]

    MASK = np.array([0b0001, 0b0010, 0b0100, 0b1000], dtype=np.uint8)
    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_edges[pos] & MASK[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(i4, i4, i4[:])"
    )(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
    exit()
else:
    if 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.int32(sys.stdin.read().split())
    main(N, M, data)

Submission status: Memory 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):
    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).astype(np.int16)
    B = np.searchsorted(yticks, B).astype(np.int16)
    C = np.searchsorted(xticks, C).astype(np.int16)
    D = np.searchsorted(yticks, D).astype(np.int16)
    E = np.searchsorted(xticks, E).astype(np.int16)
    F = np.searchsorted(xticks, F).astype(np.int16)

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

#    ng_egdes = np.zeros((NUM_VERTEXES, 4), dtype=np.uint8)
    ng_edges = np.zeros(NUM_VERTEXES, dtype=np.uint8)

    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
            ng_edges[pos] |= 0b0001  # left
            ng_edges[pos - 1] |= 0b0010  # right
    A = B = C = 0

    # 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_edges[pos] |= 0b0100
            ng_edges[pos - GRAPH_WIDTH] |= 0b1000
    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]

    MASK = np.array([0b0001, 0b0010, 0b0100, 0b1000], dtype=np.uint8)
    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_edges[pos] & MASK[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(i4, i4, i4[:])"
    )(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
    exit()
else:
    if 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.int32(sys.stdin.read().split())
    main(N, M, data)

Submission status: Memory 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):
    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).astype(np.int16)
    B = np.searchsorted(yticks, B).astype(np.int16)
    C = np.searchsorted(xticks, C).astype(np.int16)
    D = np.searchsorted(yticks, D).astype(np.int16)
    E = np.searchsorted(xticks, E).astype(np.int16)
    F = np.searchsorted(xticks, F).astype(np.int16)

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

#    ng_egdes = np.zeros((NUM_VERTEXES, 4), dtype=np.uint8)
    ng_edges = np.zeros(NUM_VERTEXES, dtype=np.uint8)

    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
            ng_edges[pos] |= 0b0001  # left
            ng_edges[pos - 1] |= 0b0010  # 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_edges[pos] |= 0b0100
            ng_edges[pos - GRAPH_WIDTH] |= 0b1000
    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]

    MASK = np.array([0b0001, 0b0010, 0b0100, 0b1000], dtype=np.uint8)
    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_edges[pos] & MASK[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(i4, i4, i4[:])"
    )(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
    exit()
else:
    if 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.int32(sys.stdin.read().split())
    main(N, M, data)

Submission status: Memory 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):
    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).astype(np.int16)
    B = np.searchsorted(yticks, B).astype(np.int16)
    C = np.searchsorted(xticks, C).astype(np.int16)
    D = np.searchsorted(yticks, D).astype(np.int16)
    E = np.searchsorted(xticks, E).astype(np.int16)
    F = np.searchsorted(xticks, F).astype(np.int16)

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

    ng_egdes = np.zeros((NUM_VERTEXES, 4), dtype=np.uint8)
    #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(i4, i4, i4[:])"
    )(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
    exit()
else:
    if 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.int32(sys.stdin.read().split())
    main(N, M, data)

Submission status: Memory 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):
    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).astype(np.int16)
    B = np.searchsorted(yticks, B).astype(np.int16)
    C = np.searchsorted(xticks, C).astype(np.int16)
    D = np.searchsorted(yticks, D).astype(np.int16)
    E = np.searchsorted(xticks, E).astype(np.int16)
    F = np.searchsorted(xticks, F).astype(np.int16)

    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(i4, i4, i4[:])"
    )(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
    exit()
else:
    if 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.int32(sys.stdin.read().split())
    main(N, M, data)

Submission status: Memory 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(i4, i4, i4[:])"
    )(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
    exit()
else:
    if 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.int32(sys.stdin.read().split())
    main(N, M, data)