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: Accepted

Solution code:
import sys
N, M = map(int, input().split())
X = []
for _ in range(N):
    a, b, c = map(int, input().split())
    X.append((a,b,c))
Y = []
for _ in range(M):
    a, b, c = map(int, input().split())
    Y.append((b, c, a))
X.sort(key=lambda x:x[2])
Y.sort(key=lambda x:x[2])

dxs = []
bc = X[0][2]
for _, _, c in X[1:]:
    dxs.append(c-bc)
    bc = c
dys = []
bc = Y[0][2]
for _, _, c in Y[1:]:
    dys.append(c-bc)
    bc = c
#print(dxs, dys)
Ws = set()
for i, (a, b, _) in enumerate(X):
    yi = 0
    for (_, _, z1), (_, _, z2) in zip(Y, Y[1:]):
        if z1==z2 or (a<=z1 and z2<=b):
            Ws.add(((i-1, yi), (i, yi)))
            Ws.add(((i, yi), (i-1, yi)))
        yi += 1

for i, (a, b, _) in enumerate(Y):
    yi = 0
    for (_, _, z1), (_, _, z2) in zip(X, X[1:]):
        if z1 == z2 or (a<=z1 and z2<=b):
            Ws.add(((yi, i-1), (yi, i)))
            Ws.add(((yi, i), (yi, i-1)))
        yi += 1
#print(Ws)

fci = -1
for _, _, c in X:
    if 0<c:
        break
    fci += 1
if fci < 0 or N-1<=fci:
    print("INF")
    sys.exit()
fcj = -1
for _, _, c in Y:
    if 0<c:
        break
    fcj += 1
if fcj < 0 or M-1<=fcj:
    print("INF")
    sys.exit()
#print(fci, fcj)
stack = [(fci, fcj)]
S = 0
vs = set([(fci, fcj)])
while stack:
    i,j = stack.pop()
#    print(i, j)
    S += dxs[i]*dys[j]
    for k, l in [(i+1, j), (i-1, j), (i, j-1), (i, j+1)]:
        if ((i, j), (k, l)) in Ws:
            continue
#        print(S, k, l)
        if k<0 or N-2<k:
            print("INF")
            sys.exit()
        if l<0 or M-2<l:
            print("INF")
            sys.exit()
        if (k, l) in vs:
            continue
        vs.add((k, l))
        stack.append((k, l))
print(S)

Submission status: Accepted

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 = deque([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: Accepted

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 = deque([Cx[0] * W + Cy[0]])

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

res = 0

while queue:
    z = queue.popleft()
    
    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: Accepted

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 = deque([Cx[0] * W + Cy[0]])
visited = [0] * (H * W)
visited[Cx[0] * W + Cy[0]] = 1
res = 0

while queue:
    z = queue.popleft()
    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: Accepted

Solution code:
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    dir = [(-1,0),(1,0),(0,-1),(0,1)]
    n,m = map(int,ipt().split())
    xb = []
    yb = []
    xs = []
    ys = []
    for i in range(n):
        a,b,c = map(int,ipt().split())
        xb.append((a,b,c))
        xs.append(a)
        xs.append(b)
        ys.append(c)
    for j in range(m):
        d,e,f = map(int,ipt().split())
        yb.append((d,e,f))
        xs.append(d)
        ys.append(e)
        ys.append(f)
    xs = sorted(list(set(xs)))
    ys = sorted(list(set(ys)))
    lx = len(xs)
    ly = len(ys)

    dix = dict()
    diy = dict()

    for i,xi in enumerate(xs):
        dix[xi] = i
    for i,yi in enumerate(ys):
        diy[yi] = i

    brd = [[1]*(ly*2-1) for _ in range(lx*2-1)]
    for a,b,c in xb:
        xa = dix[a]
        xb = dix[b]
        xc = diy[c]
        for i in range(xa,xb):
            brd[2*i+1][xc*2] = 0
    for d,e,f in yb:
        xd = dix[d]
        xe = diy[e]
        xf = diy[f]
        for i in range(xe,xf):
            brd[xd*2][2*i+1] = 0
    for i,xi in enumerate(xs[1::]):
        for j,yj in enumerate(ys[1::]):
            brd[2*i+1][2*j+1] = (yj-ys[j])*(xi-xs[i])

    sx = bisect.bisect_left(xs,0)
    sy = bisect.bisect_left(ys,0)
    if sx == 0 or sy == 0 or sx == lx or sy == ly:
        print("INF")
        exit()
    q = []
    q.append((sx*2-1,sy*2-1))
    ans = brd[sx*2-1][sy*2-1]
    brd[sx*2-1][sy*2-1] = 0
    while q:
        qx,qy = q.pop()
        for dx,dy in dir:
            nx = qx+dx
            ny = qy+dy
            if brd[nx][ny]:
                if nx == 0 or nx == lx*2-2 or ny == 0 or ny == ly*2-2:
                    print("INF")
                    exit()
                nx += dx
                ny += dy
                if brd[nx][ny]:
                    ans += brd[nx][ny]
                    brd[nx][ny] = 0
                    q.append((nx,ny))
        #print(qx,qy,q)
    print(ans)


    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


n, m = LI()
hor = []
ver = []
x_co = {-INF, INF}
y_co = {-INF, INF}
for _ in range(n):
    a, b, c = LI()
    x_co.add(a)
    x_co.add(b)
    y_co.add(c)
    ver += [(a, b, c)]

for _ in range(m):
    d, e, f = LI()
    x_co.add(d)
    y_co.add(e)
    y_co.add(f)
    hor += [(d, e, f)]


x_co = sorted(x_co)
y_co = sorted(y_co)
XD = {val:i for i,val in enumerate(x_co)}
YD = {val:i for i,val in enumerate(y_co)}
x_len = len(x_co) * 2 - 1
y_len = len(y_co) * 2 - 1
grid = [[0] * y_len for _ in range(x_len)]
x_range = [0] * x_len
y_range = [0] * y_len
x_range[0] = x_range[-1] = y_range[0] = y_range[-1] = INF
for i in range(len(x_co) - 1):
    x_range[i * 2 + 1] = x_co[i + 1] - x_co[i]
    if x_co[i] <= 0 <= x_co[i + 1]:
        sx = i * 2 + 1

for j in range(len(y_co) - 1):
    y_range[j * 2 + 1] = y_co[j + 1] - y_co[j]
    if y_co[j] <= 0 <= y_co[j + 1]:
        sy = j * 2 + 1

for a, b, c in ver:
    yi = YD[c] * 2
    for xi in range(XD[a] * 2,  XD[b] * 2 + 1):
        grid[xi][yi] = 1


for d, e, f in hor:
    xi = XD[d] * 2
    for yi in range(YD[e] * 2,  YD[f] * 2 + 1):
        grid[xi][yi] = 1


ans = x_range[sx] * y_range[sy]
grid[sx][sy] = 1


ans = 0
dq = deque([(sx, sy)])
grid[sx][sy] = 1
diff = ((0, 1), (1, 0), (-1, 0), (0, -1))
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 grid[nx][ny]:
            continue
        nx += dx;
        ny += dy
        if grid[nx][ny]:
            continue
        grid[nx][ny] = 1
        dq.append((nx, ny))
        ans += x_range[nx] * y_range[ny]
        if ans >= INF:
            print("INF")
            exit()

print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, acos, asin, atan, sqrt, tan, cos, pi
from operator import mul
from functools import reduce
from pprint import pprint


sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


n, m = LI()
hor = []
ver = []
x_co = {-INF, INF}
y_co = {-INF, INF}
for _ in range(n):
    a, b, c = LI()
    x_co.add(a)
    x_co.add(b)
    y_co.add(c)
    ver += [(a, b, c)]

for _ in range(m):
    d, e, f = LI()
    x_co.add(d)
    y_co.add(e)
    y_co.add(f)
    hor += [(d, e, f)]


x_co = sorted(x_co)
y_co = sorted(y_co)
XD = {val:i for i,val in enumerate(x_co)}
YD = {val:i for i,val in enumerate(y_co)}
x_len = len(x_co) * 2 - 1
y_len = len(y_co) * 2 - 1
grid = [[0] * y_len for _ in range(x_len)]
x_range = [0] * x_len
y_range = [0] * y_len
x_range[0] = x_range[-1] = y_range[0] = y_range[-1] = INF

for i, (x1, x2) in enumerate(zip(x_co, x_co[1:])):
    x_range[i * 2 + 1] = x2 - x1
    if x1 <= 0 <= x2:
        sx = i * 2 + 1

for i, (y1, y2) in enumerate(zip(y_co, y_co[1:])):
    y_range[i * 2 + 1] = y2 - y1
    if y1 <= 0 <= y2:
        sy = i * 2 + 1

for a, b, c in ver:
    yi = YD[c] * 2
    for xi in range(XD[a] * 2,  XD[b] * 2 + 1):
        grid[xi][yi] = 1


for d, e, f in hor:
    xi = XD[d] * 2
    for yi in range(YD[e] * 2,  YD[f] * 2 + 1):
        grid[xi][yi] = 1


ans = x_range[sx] * y_range[sy]
grid[sx][sy] = 1


ans = 0
dq = deque([(sx, sy)])
grid[sx][sy] = 1
diff = ((0, 1), (1, 0), (-1, 0), (0, -1))
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 grid[nx][ny]:
            continue
        nx += dx;
        ny += dy
        if grid[nx][ny]:
            continue
        grid[nx][ny] = 1
        dq.append((nx, ny))
        ans += x_range[nx] * y_range[ny]
        if ans >= INF:
            print("INF")
            exit()

print(ans)

Submission status: Accepted

Solution code:
import sys
from itertools import accumulate
input = sys.stdin.buffer.readline

N, M = map(int, input().split())
abcs = [tuple(map(int, input().split())) for _ in range(N)]
defs = [tuple(map(int, input().split())) for _ in range(M)]


xs = set([-10**9-2, 0, 10**9+2])
ys = set([-10**9-2, 0, 10**9+2])
for a, b, c in abcs:
    xs.add(a)
    xs.add(b)
    ys.add(c)
for d, e, f in defs:
    xs.add(d)
    ys.add(e)
    ys.add(f)

scatter_x = sorted(xs)
scatter_y = sorted(ys)

gather_x = {e:i for i, e in enumerate(scatter_x)}
gather_y = {e:i for i, e in enumerate(scatter_y)}

x_size = 2 * len(scatter_x)
y_size = 2 * len(scatter_y)

field = [[0] * y_size for _ in range(x_size)]

for a, b, c in abcs:
    field[2 * gather_x[a]][2 * gather_y[c]] += 1
    field[2 * gather_x[b] + 1][2 * gather_y[c]] -= 1
    field[2 * gather_x[a]][2 * gather_y[c] + 1] -= 1
    field[2 * gather_x[b] + 1][2 * gather_y[c] + 1] += 1

for d, e, f in defs:
    field[2 * gather_x[d]][2 * gather_y[e]] += 1
    field[2 * gather_x[d]][2 * gather_y[f] + 1] -= 1
    field[2 * gather_x[d] + 1][2 * gather_y[e]] -= 1
    field[2 * gather_x[d] + 1][2 * gather_y[f] + 1] += 1


for x in range(x_size):
    field[x] = list(accumulate(field[x]))

for x in range(x_size-1):
    for y in range(y_size):
        field[x+1][y] += field[x][y]


#print(*[''.join(map(lambda c: str(c).center(3, ' '), row)) for row in field], sep = '\n')

area = 0
sx = gather_x[0] * 2 + 1
sy = gather_y[0] * 2 + 1
field[sx][sy] = 1
stack_x = [sx]
stack_y = [sy]
while stack_x:
    x = stack_x.pop()
    y = stack_y.pop()
    if x == 1 or y == 1 or x == x_size-1 or y == y_size-1:
        print("INF")
        exit()
    
    if field[x+1][y] == field[x+2][y] == 0:
        stack_x.append(x+2)
        stack_y.append(y)
        field[x+2][y] = 1
    if field[x][y+1] == field[x][y+2] == 0:
        stack_x.append(x)
        stack_y.append(y+2)
        field[x][y+2] = 1
    if field[x-1][y] == field[x-2][y] == 0:
        stack_x.append(x-2)
        stack_y.append(y)
        field[x-2][y] = 1
    if field[x][y-1] == field[x][y-2] == 0:
        stack_x.append(x)
        stack_y.append(y-2)
        field[x][y-2] = 1

    delta_x = scatter_x[x//2 + 1] - scatter_x[x//2]
    delta_y = scatter_y[y//2 + 1] - scatter_y[y//2]       
    area += delta_x * delta_y

print(area)

Submission status: Accepted

Solution code:
#写経
#https://atcoder.jp/contests/abc168/submissions/14421546
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
from bisect import bisect_left, bisect_right
INF = 10 **18

def resolve():
    n, m = map(int, input().split())
    a = [list(map(int, input().split())) for i in range(n)]
    b = [list(map(int, input().split())) for i in range(m)]
 
    X = {-INF, INF}
    Y = {-INF, INF}
    for i in a:
        Y.add(i[2])
    for i in b:
        X.add(i[0])
 
    X = list(sorted(X))
    Y = list(sorted(Y))
    n = len(X) - 1
    m = len(Y) - 1
    wallx = [[False] * m for i in range(n)]
    wally = [[False] * m for i in range(n)]
 
    for x1, x2, y1 in a:
        x1 = bisect_left(X, x1)
        y1 = bisect_left(Y, y1)
        x2 = bisect_right(X, x2) - 1
        for i in range(x1, x2):
            wally[i][y1] = True
 
    for x1, y1, y2 in b:
        x1 = bisect_left(X, x1)
        y1 = bisect_left(Y, y1)
        y2 = bisect_right(Y, y2) - 1
        for i in range(y1, y2):
            wallx[x1][i] = True
 
    cow = [[False] * m for i in range(n)]
    cx = bisect_right(X, 0) - 1
    cy = bisect_right(Y, 0) - 1
    cow[cx][cy] = True
    q = [(cx, cy)]
    ans = 0
 
    while q:
        x, y = q.pop()
        if not x or not y:
            print("INF")
            sys.exit()
        ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
        if x and not wallx[x][y] and not cow[x - 1][y]:
            cow[x - 1][y] = True
            q.append((x - 1, y))
        if y and not wally[x][y] and not cow[x][y - 1]:
            cow[x][y - 1] = True
            q.append((x, y - 1))
        if x + 1 < n and not wallx[x + 1][y] and not cow[x + 1][y]:
            cow[x + 1][y] = True
            q.append((x + 1, y))
        if y + 1 < m and not wally[x][y + 1] and not cow[x][y + 1]:
            cow[x][y + 1] = True
            q.append((x, y + 1)) 
    print(ans)
resolve()

Submission status: Accepted

Solution code:
from collections import deque

def main():
    n, m = map(int, input().split())
    INF = 10**20
    mapX = {INF, -INF}
    mapY = {INF, -INF}
    dx = [-1, 0, 1, 0]
    dy = [0, -1, 0, 1]
    lh = [None]*n
    lv = [None]*m
    for i in range(n):
        a, b, c = map(int, input().split())
        mapX.add(a)
        mapX.add(b)
        mapY.add(c)
        lh[i] = [a, b, c]
    for i in range(m):
        d, e, f = map(int, input().split())
        mapX.add(d)
        mapY.add(e)
        mapY.add(f)
        lv[i] = [d, e, f]
        
    x_len = len(mapX)*2 - 1
    y_len = len(mapY)*2 - 1
    mapX, mapY = sorted(list(mapX)), sorted(list(mapY))
    mapXi, mapYi = {val:i for i, val in enumerate(mapX)}, {val:i for i, val in enumerate(mapY)}
    grid = [[0]*y_len for _ in range(x_len)]
    
    x_range = [0] * x_len
    y_range = [0] * y_len
    x_range[0] = x_range[-1] = INF
    y_range[0] = y_range[-1] = INF
    
    for i, (x1, x2) in enumerate(zip(mapX, mapX[1:])):
        x_range[i*2 + 1] = x2 - x1
        if x1 <= 0 <= x2:
            sx = i*2 + 1
    
    for i, (y1, y2) in enumerate(zip(mapY, mapY[1:])):
        y_range[i*2 + 1] = y2 - y1
        if y1 <= 0 <= y2:
            sy = i*2 + 1
    
    for a, b, c in lh:
        y = mapYi[c]*2
        for x in range(mapXi[a]*2+1, mapXi[b]*2+1, 2):
            grid[x][y] = 1
    for a, b, c in lv:
        x = mapXi[a]*2
        for y in range(mapYi[b]*2+1, mapYi[c]*2+1, 2):
            grid[x][y] = 1
    q = deque()
    grid[sx][sy] = 1
    q.appendleft([sx, sy])
    ans = x_range[sx] * y_range[sy]
    while q:
        x, y = q.pop()
        for i in range(4):
            nx, ny = x+dx[i], y+dy[i]
            if grid[nx][ny]:
                continue
            nx += dx[i]
            ny += dy[i]
            if grid[nx][ny]:
                continue
            grid[nx][ny] = 1
            q.appendleft([nx, ny])
            ans += x_range[nx]*y_range[ny]
            if ans >= INF:
                print("INF")
                return
    print(ans)
        
            
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    import sys
    readline = sys.stdin.readline
    # readlines = sys.stdin.readlines
    from collections import deque
    from bisect import bisect_left

    N, M = map(int, input().split())
    tate = []
    yoko = []
    X = set()
    Y = set()
    for _ in range(N):
        A, B, C = map(int, readline().split())
        X.add(A)
        X.add(B)
        Y.add(C)
        tate.append((C, A, B))
    for _ in range(M):
        D, E, F = map(int, readline().split())
        X.add(D)
        Y.add(E)
        Y.add(F)
        yoko.append((D, E, F))

    X = sorted(list(X))
    Y = sorted(list(Y))
    H = len(X)
    W = len(Y)

    wall = [[15] * W for _ in range(H)]

    for c, a, b in tate:
        ia = bisect_left(X, a)
        ib = bisect_left(X, b)
        jc = bisect_left(Y, c)
        for i in range(ia, ib):
            wall[i][jc - 1] &= 15 - (1 << 1)
            wall[i][jc] &= 15 - (1 << 3)
    for d, e, f in yoko:
        id = bisect_left(X, d)
        je = bisect_left(Y, e)
        jf = bisect_left(Y, f)
        for j in range(je, jf):
            wall[id - 1][j] &= 15 - (1 << 2)
            wall[id][j] &= 15 - (1 << 0)

    q = deque()
    x0 = bisect_left(X, 0) - (0 not in X)
    y0 = bisect_left(Y, 0) - (0 not in Y)
    if x0 == H - 1 or y0 == W - 1:
        print('INF')
        exit()

    path = [True] * (W * H)
    path[x0 * W + y0] = False
    q.append((x0, y0))
    direction = ((-1, 0), (0, 1), (1, 0), (0, -1))
    cnt = 0
    while q:
        x, y = q.popleft()
        cnt += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
        for i, (dx, dy) in enumerate(direction):
            if wall[x][y] & (1 << i):
                nx = x + dx
                ny = y + dy
                if 0 <= nx < H - 1 and 0 <= ny < W - 1:
                    if path[nx * W + ny]:
                        path[nx * W + ny] = False
                        q.append((nx, ny))
                else:
                    print('INF')
                    exit()
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def main():
    import sys
    readline = sys.stdin.readline
    # readlines = sys.stdin.readlines
    from collections import deque
    from bisect import bisect_left

    N, M = map(int, input().split())
    tate = []
    yoko = []
    X = set()
    Y = set()
    for _ in range(N):
        A, B, C = map(int, readline().split())
        X.add(A)
        X.add(B)
        Y.add(C)
        tate.append((C, A, B))
    for _ in range(M):
        D, E, F = map(int, readline().split())
        X.add(D)
        Y.add(E)
        Y.add(F)
        yoko.append((D, E, F))

    X = sorted(list(X))
    Y = sorted(list(Y))
    H = len(X)
    W = len(Y)

    ix = {}
    for i, x in enumerate(X):
        ix[x] = i
    jy = {}
    for j, y in enumerate(Y):
        jy[y] = j

    wall = [[15] * W for _ in range(H)]

    for c, a, b in tate:
        ia = ix[a]
        ib = ix[b]
        jc = jy[c]
        for i in range(ia, ib):
            wall[i][jc - 1] &= 15 - (1 << 1)
            wall[i][jc] &= 15 - (1 << 3)
    for d, e, f in yoko:
        i_d = ix[d]
        je = jy[e]
        jf = jy[f]
        for j in range(je, jf):
            wall[i_d - 1][j] &= 15 - (1 << 2)
            wall[i_d][j] &= 15 - (1 << 0)

    q = deque()
    x0 = bisect_left(X, 0) - (0 not in ix)
    y0 = bisect_left(Y, 0) - (0 not in jy)
    if x0 == H - 1 or y0 == W - 1:
        print('INF')
        exit()

    path = [True] * (W * H)
    path[x0 * W + y0] = False
    q.append((x0, y0))
    direction = ((-1, 0), (0, 1), (1, 0), (0, -1))
    cnt = 0
    while q:
        x, y = q.popleft()
        cnt += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
        for i, (dx, dy) in enumerate(direction):
            if wall[x][y] & (1 << i):
                nx = x + dx
                ny = y + dy
                if 0 <= nx < H - 1 and 0 <= ny < W - 1:
                    if path[nx * W + ny]:
                        path[nx * W + ny] = False
                        q.append((nx, ny))
                else:
                    print('INF')
                    exit()
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

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
lx = [[0 for _ in range(w + 1)] for _ in range(h + 1)]
ly = [[0 for _ in range(w + 1)] for _ in range(h + 1)]

for i in range(n):
    a, b, c = aa[i], bb[i], cc[i]
    for x in range(xp[a], xp[b]):
        lx[x][yp[c]] = 1

for i in range(m):
    d, e, f = dd[i], ee[i], ff[i]
    for y in range(yp[e], yp[f]):
        ly[xp[d]][y] = 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 = [(sx, sy)]
ans = 0

while q:
    x, y = q.pop()
    ans += (xx[x + 1] - xx[x]) * (yy[y + 1] - yy[y])
    if ly[x][y] == 0:
        if x == 0:
            print('INF'); exit();
        if not visited[x - 1][y]:
            visited[x - 1][y] = True
            q.append((x - 1, y))
    if lx[x][y] == 0:
        if y == 0:
            print('INF'); exit();
        if not visited[x][y - 1]:
            visited[x][y - 1] = True
            q.append((x, y - 1))
    if ly[x + 1][y] == 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 lx[x][y + 1] == 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)