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:
from collections import deque
import bisect

INF = float("inf")

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

xtic = {0}
ytic = {0}

hor = []
for _ in range(N):
  a,b,c = map(int,input().split())
  hor.append((c,a,b))
  xtic.add(a)
  xtic.add(b)
  ytic.add(c)
  
ver = []
for _ in range(M):
  d,e,f = map(int,input().split())
  ver.append((d,e,f))
  xtic.add(d)
  ytic.add(e)
  ytic.add(f)

xtic = list(xtic)
ytic = list(ytic)
xtic.sort()
ytic.sort()
xdic = {xtic[i]:i+1 for i in range(len(xtic))}
ydic = {ytic[i]:i+1 for i in range(len(ytic))}

gyaku_xdic = {xdic[k]:k for k in xdic}
gyaku_ydic = {ydic[k]:k for k in ydic}

hor.sort()
ver.sort()

hor_dic = {}
ver_dic = {}

now = None
for c,a,b in hor:
  c,a,b = ydic[c],xdic[a],xdic[b]
  if c != now:
    hor_dic[c] = [(a,b)]
  else:
    hor_dic[c].append((a,b))
  now = c

now = None
for d,e,f in ver:
  d,e,f = xdic[d],ydic[e],ydic[f]
  if d != now:
    ver_dic[d] = [(e,f)]
  else:
    ver_dic[d].append((e,f))
  now = d

hor_wall = [-INF] + [k for k in hor_dic] + [INF]
ver_wall = [-INF] + [k for k in ver_dic] + [INF]

def is_connected(x,y,dx,dy):
  if dx == 0:
    if dy > 0:
      p = bisect.bisect_left(hor_wall,y+1)
      if hor_wall[p] != y+1:
        return True
      else:
        for l,r in hor_dic[y+1]:
          if l<=x<r:
            return False
        return True
    else:
      p = bisect.bisect_left(hor_wall,y)
      if hor_wall[p] != y:
        return True
      else:
        for l,r in hor_dic[y]:
          if l<=x<r:
            return False
        return True
  else:
    if dx > 0:
      p = bisect.bisect_left(ver_wall,x+1)
      if ver_wall[p] != x+1:
        return True
      else:
        for l,r in ver_dic[x+1]:
          if l<=y<r:
            return False
        return True
    else:
      p = bisect.bisect_left(ver_wall,x)
      if ver_wall[p] != x:
        return True
      else:
        for l,r in ver_dic[x]:
          if l<=y<r:
            return False
        return True
      
def calc_area(x,y):
  X = gyaku_xdic[x+1] - gyaku_xdic[x]
  Y = gyaku_ydic[y+1] - gyaku_ydic[y]
  return X*Y

offset = [(1,0),(0,1),(-1,0),(0,-1)]
x0 = bisect.bisect(xtic,0)
y0 = bisect.bisect(ytic,0)
W,H = len(xtic)+1 ,len(ytic)+1

gyaku_xdic[0] = -INF
gyaku_ydic[0] = -INF
gyaku_xdic[W] = INF
gyaku_ydic[H] = INF

d = [[0 for i in range(W)] for j in range(H)]
d[y0][x0] = 1
q = deque([(x0,y0)])

area = 0

while q:
  x,y = q.popleft()
  area += calc_area(x,y)
  if area == INF:
    print("INF")
    exit()
  for dx,dy in offset:
    nx,ny = x+dx,y+dy
    if 0<=nx<W and 0<=ny<H:
      if is_connected(x,y,dx,dy):
        if d[ny][nx] == 0:
          d[ny][nx] = 1
          q.append((nx,ny))

print(area)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from numba import njit, types
from numba.typed import Dict

n, m, *abcdef = map(int, sys.stdin.buffer.read().split())

ver_lines = []
hor_lines = []
x_list = set()
y_list = set()
n3 = n * 3
for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):
    y_list.add(a)
    y_list.add(b)
    x_list.add(c)
    ver_lines.append((a, b, c))

for d, e, f in zip(abcdef[n3 + 0::3], abcdef[n3 + 1::3], abcdef[n3 + 2::3]):
    y_list.add(d)
    x_list.add(e)
    x_list.add(f)
    hor_lines.append((d, e, f))
x_list.add(0)
y_list.add(0)


@njit
def create_dict(x_list):
    d = Dict.empty(key_type=types.int64, value_type=types.int64)
    for i in range(len(x_list)):
        d[x_list[i]] = i + 1
    return d


x_list = np.array(sorted(x_list), dtype=np.int64)
y_list = np.array(sorted(y_list), dtype=np.int64)
# x_dict = {x: i for i, x in enumerate(x_list, start=1)}
# y_dict = {y: i for i, y in enumerate(y_list, start=1)}
x_dict = create_dict(x_list)
y_dict = create_dict(y_list)
row_real = len(x_list)
col_real = len(y_list)
row = row_real + 2
col = col_real + 2
total = row * col

banned_up = np.zeros(total, dtype=np.int16)
banned_down = np.zeros(total, dtype=np.int16)
banned_left = np.zeros(total, dtype=np.int16)
banned_right = np.zeros(total, dtype=np.int16)


@njit
def register_ver_lines(a, b, c, banned_left, banned_right, x_dict, y_dict):
    if a > b:
        a, b = b, a
    ai = y_dict[a] * row
    bi = y_dict[b] * row
    j = x_dict[c]
    banned_left[ai + j] += 1
    banned_left[bi + j] -= 1
    banned_right[ai + j - 1] += 1
    banned_right[bi + j - 1] -= 1


@njit
def register_hor_lines(d, e, f, banned_up, banned_down, x_dict, y_dict):
    if e > f:
        e, f = f, e
    ri = y_dict[d] * row
    ej = x_dict[e]
    fj = x_dict[f]
    banned_up[ri + ej] += 1
    banned_up[ri + fj] -= 1
    banned_down[ri - row + ej] += 1
    banned_down[ri - row + fj] -= 1


@njit
def accumulate_banned(banned_up, banned_down, banned_left, banned_right):
    for i in range(1, col):
        ri0 = row * (i - 1)
        ri1 = row * i
        for j in range(1, row):
            banned_up[ri1 + j] += banned_up[ri1 + j - 1]
            banned_down[ri1 + j] += banned_down[ri1 + j - 1]
            banned_left[ri1 + j] += banned_left[ri0 + j]
            banned_right[ri1 + j] += banned_right[ri0 + j]


@njit
def dfs(x_list, y_list, x_dict, y_dict, banned_up, banned_down, banned_left, banned_right):
    s = row * y_dict[0] + x_dict[0]
    enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row

    q = [s]
    moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]
    while q:
        c = q.pop()
        if enable[c] == 1:
            continue
        elif enable[c] == -1:
            return -1
        enable[c] = 1
        for dc, banned in moves:
            if banned[c]:
                continue
            nc = c + dc
            if enable[nc] == 1:
                continue
            q.append(nc)

    ans = 0
    for i in range(col):
        ri = i * row
        for j in range(row):
            if enable[ri + j] != 1:
                continue
            t = y_list[i - 1]
            b = y_list[i]
            l = x_list[j - 1]
            r = x_list[j]
            ans += (b - t) * (r - l)
    return ans


for a, b, c in ver_lines:
    register_ver_lines(a, b, c, banned_left, banned_right, x_dict, y_dict)
for d, e, f in hor_lines:
    register_hor_lines(d, e, f, banned_up, banned_down, x_dict, y_dict)

accumulate_banned(banned_up, banned_down, banned_left, banned_right)

ans = dfs(x_list, y_list, x_dict, y_dict, banned_up, banned_down, banned_left, banned_right)
print(ans if ans != -1 else 'INF')

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from numba import njit, types
from numba.typed import Dict

n, m, *abcdef = map(int, sys.stdin.buffer.read().split())

ver_lines = []
hor_lines = []
x_list = set()
y_list = set()
n3 = n * 3
for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):
    y_list.add(a)
    y_list.add(b)
    x_list.add(c)
    ver_lines.append((a, b, c))

for d, e, f in zip(abcdef[n3 + 0::3], abcdef[n3 + 1::3], abcdef[n3 + 2::3]):
    y_list.add(d)
    x_list.add(e)
    x_list.add(f)
    hor_lines.append((d, e, f))
x_list.add(0)
y_list.add(0)


@njit
def create_dict(x_list):
    d = Dict.empty(key_type=types.int64, value_type=types.int64)
    for i in range(len(x_list)):
        d[x_list[i]] = i + 1
    return d


x_list = np.array(sorted(x_list), dtype=np.int64)
y_list = np.array(sorted(y_list), dtype=np.int64)
# x_dict = {x: i for i, x in enumerate(x_list, start=1)}
# y_dict = {y: i for i, y in enumerate(y_list, start=1)}
x_dict = create_dict(x_list)
y_dict = create_dict(y_list)
row_real = len(x_list)
col_real = len(y_list)
row = row_real + 2
col = col_real + 2
total = row * col

banned_up = np.zeros(total, dtype=np.int16)
banned_down = np.zeros(total, dtype=np.int16)
banned_left = np.zeros(total, dtype=np.int16)
banned_right = np.zeros(total, dtype=np.int16)


@njit
def register_ver_lines(a, b, c, banned_left, banned_right, x_dict, y_dict):
    if a > b:
        a, b = b, a
    ai = y_dict[a] * row
    bi = y_dict[b] * row
    j = x_dict[c]
    banned_left[ai + j] += 1
    banned_left[bi + j] -= 1
    banned_right[ai + j - 1] += 1
    banned_right[bi + j - 1] -= 1


@njit
def register_hor_lines(d, e, f, banned_up, banned_down, x_dict, y_dict):
    if e > f:
        e, f = f, e
    ri = y_dict[d] * row
    ej = x_dict[e]
    fj = x_dict[f]
    banned_up[ri + ej] += 1
    banned_up[ri + fj] -= 1
    banned_down[ri - row + ej] += 1
    banned_down[ri - row + fj] -= 1


@njit
def accumulate_banned(banned_up, banned_down, banned_left, banned_right):
    for i in range(1, col):
        ri0 = row * (i - 1)
        ri1 = row * i
        for j in range(1, row):
            banned_up[ri1 + j] += banned_up[ri1 + j - 1]
            banned_down[ri1 + j] += banned_down[ri1 + j - 1]
            banned_left[ri1 + j] += banned_left[ri0 + j]
            banned_right[ri1 + j] += banned_right[ri0 + j]


for a, b, c in ver_lines:
    register_ver_lines(a, b, c, banned_left, banned_right, x_dict, y_dict)
for d, e, f in hor_lines:
    register_hor_lines(d, e, f, banned_up, banned_down, x_dict, y_dict)

accumulate_banned(banned_up, banned_down, banned_left, banned_right)
banned_up = banned_up.tolist()
banned_down = banned_down.tolist()
banned_left = banned_left.tolist()
banned_right = banned_right.tolist()

s = row * y_dict[0] + x_dict[0]
enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row

q = [s]
moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]
while q:
    c = q.pop()
    if enable[c] == 1:
        continue
    elif enable[c] == -1:
        print('INF')
        exit()
    enable[c] = 1
    for dc, banned in moves:
        if banned[c]:
            continue
        nc = c + dc
        if enable[nc] == 1:
            continue
        q.append(nc)
# for i in range(col):
#     print(enable[i * row:(i + 1) * row])


ans = 0
for i in range(col):
    ri = i * row
    for j in range(row):
        if enable[ri + j] != 1:
            continue
        t = y_list[i - 1]
        b = y_list[i]
        l = x_list[j - 1]
        r = x_list[j]
        ans += (b - t) * (r - l)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import bisect

INF = float("inf")

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

xtic = {0}
ytic = {0}

hor = []
for _ in range(N):
  a,b,c = map(int,input().split())
  hor.append((c,a,b))
  xtic.add(a)
  xtic.add(b)
  ytic.add(c)
  
ver = []
for _ in range(M):
  d,e,f = map(int,input().split())
  ver.append((d,e,f))
  xtic.add(d)
  ytic.add(e)
  ytic.add(f)

xtic = list(xtic)
ytic = list(ytic)
xtic.sort()
ytic.sort()
xdic = {xtic[i]:i+1 for i in range(len(xtic))}
ydic = {ytic[i]:i+1 for i in range(len(ytic))}

gyaku_xdic = {xdic[k]:k for k in xdic}
gyaku_ydic = {ydic[k]:k for k in ydic}

hor.sort()
ver.sort()

hor_dic = {}
ver_dic = {}

now = None
for c,a,b in hor:
  c,a,b = ydic[c],xdic[a],xdic[b]
  if c != now:
    hor_dic[c] = [(a,b)]
  else:
    hor_dic[c].append((a,b))
  now = c

now = None
for d,e,f in ver:
  d,e,f = xdic[d],ydic[e],ydic[f]
  if d != now:
    ver_dic[d] = [(e,f)]
  else:
    ver_dic[d].append((e,f))
  now = d

hor_wall = [-INF] + [k for k in hor_dic] + [INF]
ver_wall = [-INF] + [k for k in ver_dic] + [INF]

def is_connected(x,y,dx,dy):
  if dx == 0:
    if dy > 0:
      p = bisect.bisect_left(hor_wall,y+1)
      if hor_wall[p] != y+1:
        return True
      else:
        for l,r in hor_dic[y+1]:
          if l<=x<r:
            return False
        return True
    else:
      p = bisect.bisect_left(hor_wall,y)
      if hor_wall[p] != y:
        return True
      else:
        for l,r in hor_dic[y]:
          if l<=x<r:
            return False
        return True
  else:
    if dx > 0:
      p = bisect.bisect_left(ver_wall,x+1)
      if ver_wall[p] != x+1:
        return True
      else:
        for l,r in ver_dic[x+1]:
          if l<=y<r:
            return False
        return True
    else:
      p = bisect.bisect_left(ver_wall,x)
      if ver_wall[p] != x:
        return True
      else:
        for l,r in ver_dic[x]:
          if l<=y<r:
            return False
        return True
      
def calc_area(x,y):
  X = gyaku_xdic[x+1] - gyaku_xdic[x]
  Y = gyaku_ydic[y+1] - gyaku_ydic[y]
  return X*Y

offset = [(1,0),(0,1),(-1,0),(0,-1)]
x0 = bisect.bisect(xtic,0)
y0 = bisect.bisect(ytic,0)
W,H = len(xtic)+1 ,len(ytic)+1

gyaku_xdic[0] = -INF
gyaku_ydic[0] = -INF
gyaku_xdic[H] = INF
gyaku_ydic[W] = INF

d = [[0 for i in range(W)] for j in range(H)]
d[y0][x0] = 1
q = deque([(x0,y0)])

area = 0

while q:
  x,y = q.popleft()
  """
  area += calc_area(x,y)
  if area == INF:
    print("INF")
    exit()
  """
  for dx,dy in offset:
    nx,ny = x+dx,y+dy
    if 0<=nx<W and 0<=ny<H:
      d[ny][nx] = 1
      q.append((nx,ny))
      """
      if is_connected(x,y,dx,dy):
        if d[ny][nx] == 0:
          d[ny][nx] = 1
          q.append((nx,ny))
      """

print(area)
print("xtic",xtic)
print("ytic",ytic)
print("xdic",xdic)
print("ydic",ydic)
print("gyaku_xdic",gyaku_xdic)
print("gyaku_ydic",gyaku_ydic)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import bisect

INF = float("inf")

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

xtic = {0}
ytic = {0}

hor = []
for _ in range(N):
  a,b,c = map(int,input().split())
  hor.append((c,a,b))
  xtic.add(a)
  xtic.add(b)
  ytic.add(c)
  
ver = []
for _ in range(M):
  d,e,f = map(int,input().split())
  ver.append((d,e,f))
  xtic.add(d)
  ytic.add(e)
  ytic.add(f)

xtic = list(xtic)
ytic = list(ytic)
xtic.sort()
ytic.sort()
xdic = {xtic[i]:i+1 for i in range(len(xtic))}
ydic = {ytic[i]:i+1 for i in range(len(ytic))}

gyaku_xdic = {xdic[k]:k for k in xdic}
gyaku_ydic = {ydic[k]:k for k in ydic}

hor.sort()
ver.sort()

hor_dic = {}
ver_dic = {}

now = None
for c,a,b in hor:
  c,a,b = ydic[c],xdic[a],xdic[b]
  if c != now:
    hor_dic[c] = [(a,b)]
  else:
    hor_dic[c].append((a,b))
  now = c

now = None
for d,e,f in ver:
  d,e,f = xdic[d],ydic[e],ydic[f]
  if d != now:
    ver_dic[d] = [(e,f)]
  else:
    ver_dic[d].append((e,f))
  now = d

hor_wall = [-INF] + [k for k in hor_dic] + [INF]
ver_wall = [-INF] + [k for k in ver_dic] + [INF]

def is_connected(x,y,dx,dy):
  if dx == 0:
    if dy > 0:
      p = bisect.bisect_left(hor_wall,y+1)
      if hor_wall[p] != y+1:
        return True
      else:
        for l,r in hor_dic[y+1]:
          if l<=x<r:
            return False
        return True
    else:
      p = bisect.bisect_left(hor_wall,y)
      if hor_wall[p] != y:
        return True
      else:
        for l,r in hor_dic[y]:
          if l<=x<r:
            return False
        return True
  else:
    if dx > 0:
      p = bisect.bisect_left(ver_wall,x+1)
      if ver_wall[p] != x+1:
        return True
      else:
        for l,r in ver_dic[x+1]:
          if l<=y<r:
            return False
        return True
    else:
      p = bisect.bisect_left(ver_wall,x)
      if ver_wall[p] != x:
        return True
      else:
        for l,r in ver_dic[x]:
          if l<=y<r:
            return False
        return True
      
def calc_area(x,y):
  X = gyaku_xdic[x+1] - gyaku_xdic[x]
  Y = gyaku_ydic[y+1] - gyaku_ydic[y]
  return X*Y

offset = [(1,0),(0,1),(-1,0),(0,-1)]
x0 = bisect.bisect(xtic,0)
y0 = bisect.bisect(ytic,0)
W,H = len(xtic)+1 ,len(ytic)+1

gyaku_xdic[0] = -INF
gyaku_ydic[0] = -INF
gyaku_xdic[H] = INF
gyaku_ydic[W] = INF

d = [[0 for i in range(W)] for j in range(H)]
d[y0][x0] = 1
q = deque([(x0,y0)])

area = 0

while q:
  x,y = q.popleft()
  """
  area += calc_area(x,y)
  if area == INF:
    print("INF")
    exit()
  """
  for dx,dy in offset:
    nx,ny = x+dx,y+dy
    if 0<=nx<W and 0<=ny<H:
      q.append((nx,ny))
      """
      if is_connected(x,y,dx,dy):
        if d[ny][nx] == 0:
          d[ny][nx] = 1
          q.append((nx,ny))
      """

print(area)
print("xtic",xtic)
print("ytic",ytic)
print("xdic",xdic)
print("ydic",ydic)
print("gyaku_xdic",gyaku_xdic)
print("gyaku_ydic",gyaku_ydic)

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
ABC = [list(map(int,input().split())) for _ in [0]*N ]
DEF = [list(map(int,input().split())) for _ in [0]*M ]

X = [0]*3003
Y = [0]*3003
INF = 10**9 + 10
X[-1] = -INF
Y[-1] = -INF
X[-2] = INF
Y[-2] = INF
i = 0
j = 0
for a,b,c in ABC:
    X[i] = a
    X[i+1] = b
    Y[j] = c
    i += 2
    j += 1
for d,e,f in DEF:
    X[i] = d
    Y[j] = e
    Y[j+1] = f
    i += 1
    j += 2
X = sorted(set(X))
Y = sorted(set(Y))
Xdict = {x:i for i,x in enumerate(X)}
Ydict = {y:i for i,y in enumerate(Y)}

nx = len(X)
ny = len(Y)
nxy = nx * ny
E = {(x,y):{(X[i-1],y),(X[i+1],y),(x,Y[j-1]),(x,Y[j+1])} for i,x in enumerate(X[1:-1],1) for j,y in enumerate(Y[1:-1],1)}

x0 = X[0]
x1 = X[-1]
for y in Y:
    E[(x0,y)] = set()
    E[(x1,y)] = set()
y0 = Y[0]
y1 = Y[-1]
for x in X:
    E[(x,y0)] = set()
    E[(x,y1)] = set()

for a,b,c in ABC:
    y = Y[Ydict[c]-1]
    for x in X[Xdict[a]:Xdict[b]]:
        E[(x,c)].discard((x,y))
        E[(x,y)].discard((x,c))

for d,e,f in DEF:
    x = X[Xdict[d]-1]
    for y in Y[Ydict[e]:Ydict[f]]:
        E[(d,y)].discard((x,y))
        E[(x,y)].discard((d,y))

dX = {x:x2-x for x,x2 in zip(X[:-1],X[1:])}
dY = {y:y2-y for y,y2 in zip(Y[:-1],Y[1:])}
burst = False
ans = dX[0]*dY[0]
done = {(0,0)}
q = [(0,0)]
while q:
    qq = []
    for i in q:
        for j in E[i]:
            if j in done:continue
            done.add(j)
            x,y = j
            if abs(x)==INF or abs(y)==INF:
                burst = True
                ans = "INF"
                qq = []
                break
            ans += dX[x]*dY[y]
            qq.append(j)
        if burst:break
    q = qq

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

N, M = map(int, input().split())
Vs = []
Hs = []
Xs = {0}
Ys = {0}

for _ in range(N):
    x1, x2, y = map(int, input().split())
    Xs.add(x1)
    Xs.add(x2)
    Ys.add(y)
    Vs.append((x1, x2, y))
for _ in range(M):
    x, y1, y2 = map(int, input().split())
    Xs.add(x)
    Ys.add(y1)
    Ys.add(y2)
    Hs.append((x, y1, y2))

Xs = list(Xs)
Ys = list(Ys)
Xs.sort()
Ys.sort()

def area(ix, iy):
    if ix % 2 == 0 or iy % 2 == 0:
        return 0
    ix = (ix-1) // 2
    iy = (iy-1) // 2

    wx = Xs[ix+1] - Xs[ix]
    wy = Ys[iy+1] - Ys[iy]
    return wx * wy

# True := can move to
W = 2*len(Xs)-1
H = 2*len(Ys)-1
Gs = [[True]*H for _ in range(W)]
for (x1, x2, y) in Vs:
    ix1 = Xs.index(x1)
    ix2 = Xs.index(x2)
    iy = Ys.index(y)
    for x in range(2*ix1, 2*ix2+1):
        Gs[x][2*iy] = False
for (x, y1, y2) in Hs:
    ix = Xs.index(x)
    iy1 = Ys.index(y1)
    iy2 = Ys.index(y2)
    for y in range(2*iy1, 2*iy2+1):
        Gs[2*ix][y] = False

sp = (2*Xs.index(0), 2*Ys.index(0))

# bfs
res = 0
queue = deque([sp])
visited = [[False]*H for _ in range(W)]
while queue:
    x, y = queue.popleft()
    if Gs[x][y] and (not visited[x][y]):
        res += area(x, y)
    else:
        continue

    visited[x][y] = True

    if 0 < x and x < W-1:
        queue.append((x-1, y)) 
        queue.append((x+1, y)) 
    else:
        print('INF')
        break
    if 0 < y and y < H-1:
        queue.append((x, y-1)) 
        queue.append((x, y+1)) 
    else:
        print('INF')
        break
else:
    print(res)

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
ABC = [list(map(int,input().split())) for _ in [0]*N ]
DEF = [list(map(int,input().split())) for _ in [0]*M ]

X = [0]*3003
Y = [0]*3003
INF = 10**9 + 10
X[-1] = -INF
Y[-1] = -INF
X[-2] = INF
Y[-2] = INF
i = 0
j = 0
for a,b,c in ABC:
    X[i] = a
    X[i+1] = b
    Y[j] = c
    i += 2
    j += 1
for d,e,f in DEF:
    X[i] = d
    Y[j] = e
    Y[j+1] = f
    i += 1
    j += 2
X = sorted(set(X))
Y = sorted(set(Y))
Xdict = {x:i for i,x in enumerate(X)}
Ydict = {y:i for i,y in enumerate(Y)}

nx = len(X)
ny = len(Y)
nxy = nx * ny
E = {(x,y):{(X[i-1],y),(X[i+1],y),(x,Y[j-1]),(x,Y[j+1])} for i,x in enumerate(X[1:-1],1) for j,y in enumerate(Y[1:-1],1)}

x0 = X[0]
x1 = X[-1]
for y in Y:
    E[(x0,y)] = set()
    E[(x1,y)] = set()
y0 = Y[0]
y1 = Y[-1]
for x in X:
    E[(x,y0)] = set()
    E[(x,y1)] = set()

for a,b,c in ABC:
    y = Y[Ydict[c]-1]
    for x in X[Xdict[a]:Xdict[b]]:
        E[(x,c)].discard((x,y))
        E[(x,y)].discard((x,c))

for d,e,f in DEF:
    x = X[Xdict[d]-1]
    for y in Y[Ydict[e]:Ydict[f]]:
        E[(d,y)].discard((x,y))
        E[(x,y)].discard((d,y))

def dist_bfs(N,E,start):
    d = {start:0}
    q = [start]
    while q:
        qq = []
        for i in q:
            di = d[i]
            for j in E[i]:
                if j in d:continue
                d[j] = di+1
                q.append(j)
        q = qq
    return d

d = dist_bfs(nxy,E,(0,0))
burst = False
ans = 0

dX = {x:x2-x for x,x2 in zip(X[:-1],X[1:])}
dY = {y:y2-y for y,y2 in zip(Y[:-1],Y[1:])}

for x,y in d:
    if abs(x) == INF or abs(y) == INF:
        ans = "INF"
        break
    ans += dX[x]*dY[y]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
import sys
import bisect
from collections import deque
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LIR(n):
    return [LI() for i in range(n)]
def main():
    M = 3*10**9+1
    M2 = (M-10**9)**2
    n,m = LI()
    p = LIR(n)
    q = LIR(m)
    fx = set([-M,0,M])
    fy = set([-M,0,M])
    for i in range(n):
        p[i][0] <<= 1
        p[i][1] <<= 1
        p[i][2] <<= 1
        a,b,c = p[i]
        fy.add(a)
        fy.add(b)
        fy.add(b+1)
        fx.add(c)
        fx.add(c+1)

    for i in range(m):
        q[i][0] <<= 1
        q[i][1] <<= 1
        q[i][2] <<= 1
        d,e,f = q[i]
        fy.add(d)
        fy.add(d+1)
        fx.add(e)
        fx.add(f)
        fx.add(f+1)
    fy = list(fy)
    fx = list(fx)
    fy.sort()
    fx.sort()
    s = [0]*len(fx)*len(fy)
    for a,b,c in p:
        ai = bisect.bisect_left(fy,a)
        bi = bisect.bisect_left(fy,b)
        ci = bisect.bisect_left(fx,c)
        ka = ai*len(fx)
        kb = (bi+1)*len(fx)
        s[ka+ci] += 1
        s[kb+ci] -= 1
        s[ka+ci+1] -= 1
        s[kb+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)
        kd = di*len(fx)
        kdd = kd+len(fx)
        s[kd+ei] += 1
        s[kd+fi+1] -= 1
        s[kdd+ei] -= 1
        s[kdd+fi+1] += 1
    for i in range(len(fy)):
        k = i*len(fx)
        for j in range(len(fx)-1):
            ind = k+j
            s[ind+1] += s[ind]
    for i in range(len(fy)-1):
        k = i*len(fx)
        for j in range(len(fx)-1):
            ind = k+j
            s[ind+len(fx)] += s[ind]
    sx = bisect.bisect_left(fx,0)
    sy = bisect.bisect_left(fy,0)
    nh,nw = len(fy)-1,len(fx)-1
    for i in range(nw-1):
        fx[i+1] >>= 1
        fx[i] = fx[i+1]-fx[i]
    for i in range(nh-1):
        fy[i+1] >>= 1
        fy[i] = fy[i+1]-fy[i]
    ans = fx[sx]*fy[sy]
    q = deque()
    q.append((sy,sx))
    f = [1]*nh*nw
    f[sy*nw+sx] = 0
    d = [(1,0),(-1,0),(0,1),(0,-1)]
    while q:
        y,x = q.popleft()
        for dy,dx in d:
            ny,nx = y+dy,x+dx
            if 0 <= ny < nh and 0 <= nx < nw:
                ind = ny*nw+nx
                if f[ind] and not s[ind+ny]:
                    if ny < 1 or nx < 1 or ny+1 >= nh or nx+1 >= nw:
                        print("INF")
                        quit()
                    ans += fx[nx]*fy[ny]
                    f[ind] = 0
                    q.append((ny,nx))
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
import sys
import bisect
from collections import deque
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LIR(n):
    return [LI() for i in range(n)]

M = 3*10**9+1
M2 = (M-10**9)**2
n,m = LI()
p = LIR(n)
q = LIR(m)
fx = set([-M,0,M])
fy = set([-M,0,M])
for i in range(n):
    p[i][0] <<= 1
    p[i][1] <<= 1
    p[i][2] <<= 1
    a,b,c = p[i]
    fy.add(a)
    fy.add(b)
    fy.add(b+1)
    fx.add(c)
    fx.add(c+1)

for i in range(m):
    q[i][0] <<= 1
    q[i][1] <<= 1
    q[i][2] <<= 1
    d,e,f = q[i]
    fy.add(d)
    fy.add(d+1)
    fx.add(e)
    fx.add(f)
    fx.add(f+1)
fy = list(fy)
fx = list(fx)
fy.sort()
fx.sort()
h = len(fy)+1
w = len(fx)+1
s = [0]*h*w
for a,b,c in p:
    ai = bisect.bisect_left(fy,a)
    bi = bisect.bisect_left(fy,b)
    ci = bisect.bisect_left(fx,c)
    ka = ai*w
    kb = (bi+1)*w
    s[ka+ci] += 1
    s[kb+ci] -= 1
    s[ka+ci+1] -= 1
    s[kb+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)
    kd = di*w
    kdd = kd+w
    s[kd+ei] += 1
    s[kd+fi+1] -= 1
    s[kdd+ei] -= 1
    s[kdd+fi+1] += 1
for i in range(h):
    for j in range(len(fx)):
        ind = i*w+j
        s[ind+1] += s[ind]
for i in range(len(fy)):
    for j in range(w):
        ind = i*w+j
        s[ind+w] += s[ind]
sx = bisect.bisect_left(fx,0)
sy = bisect.bisect_left(fy,0)
nh,nw = len(fy)-1,len(fx)-1
for i in range(nw-1):
    fx[i+1] >>= 1
    fx[i] = fx[i+1]-fx[i]
for i in range(nh-1):
    fy[i+1] >>= 1
    fy[i] = fy[i+1]-fy[i]
ans = fx[sx]*fy[sy]
q = deque()
q.append((sy,sx))
f = [1]*nh*nw
f[sy*nw+sx] = 0
d = [(1,0),(-1,0),(0,1),(0,-1)]
while q:
    y,x = q.popleft()
    for dy,dx in d:
        ny,nx = y+dy,x+dx
        if 0 <= ny < nh and 0 <= nx < nw:
            ind = ny*nw+nx
            if f[ind] and not s[ind+(ny<<1)]:
                if ny < 1 or nx < 1 or ny+1 >= nh or nx+1 >= nw:
                    print("INF")
                    quit()
                ans += fx[nx]*fy[ny]
                f[ind] = 0
                q.append((ny,nx))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
import sys
import bisect
from collections import deque
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LIR(n):
    return [LI() for i in range(n)]

M = 3*10**9+1
M2 = (M-10**9)**2
def solve():
    n,m = LI()
    p = LIR(n)
    q = LIR(m)
    fx = set([-M,0,M])
    fy = set([-M,0,M])
    for i in range(n):
        p[i][0] <<= 1
        p[i][1] <<= 1
        p[i][2] <<= 1
        a,b,c = p[i]
        fy.add(a)
        fy.add(b)
        fy.add(b+1)
        fx.add(c)
        fx.add(c+1)

    for i in range(m):
        q[i][0] <<= 1
        q[i][1] <<= 1
        q[i][2] <<= 1
        d,e,f = q[i]
        fy.add(d)
        fy.add(d+1)
        fx.add(e)
        fx.add(f)
        fx.add(f+1)
    fy = list(fy)
    fx = list(fx)
    fy.sort()
    fx.sort()
    h = len(fy)+1
    w = len(fx)+1
    s = [0]*h*w
    for a,b,c in p:
        ai = bisect.bisect_left(fy,a)
        bi = bisect.bisect_left(fy,b)
        ci = bisect.bisect_left(fx,c)
        ka = ai*w
        kb = (bi+1)*w
        s[ka+ci] += 1
        s[kb+ci] -= 1
        s[ka+ci+1] -= 1
        s[kb+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)
        kd = di*w
        kdd = kd+w
        s[kd+ei] += 1
        s[kd+fi+1] -= 1
        s[kdd+ei] -= 1
        s[kdd+fi+1] += 1
    for i in range(h):
        for j in range(len(fx)):
            ind = i*w+j
            s[ind+1] += s[ind]
    for i in range(len(fy)):
        for j in range(w):
            ind = i*w+j
            s[ind+w] += s[ind]
    sx = bisect.bisect_left(fx,0)
    sy = bisect.bisect_left(fy,0)
    nh,nw = len(fy)-1,len(fx)-1
    for i in range(nw-1):
        fx[i+1] >>= 1
        fx[i] = fx[i+1]-fx[i]
    for i in range(nh-1):
        fy[i+1] >>= 1
        fy[i] = fy[i+1]-fy[i]
    ans = fx[sx]*fy[sy]
    q = deque()
    q.append((sy,sx))
    f = [1]*nh*nw
    f[sy*nw+sx] = 0
    d = [(1,0),(-1,0),(0,1),(0,-1)]
    while q:
        y,x = q.popleft()
        for dy,dx in d:
            ny,nx = y+dy,x+dx
            if 0 <= ny < nh and 0 <= nx < nw:
                ind = ny*nw+nx
                if f[ind] and not s[ind+(ny<<1)]:
                    if ny < 1 or nx < 1 or ny+1 >= nh or nx+1 >= nw:
                        print("INF")
                        return
                    ans += fx[nx]*fy[ny]
                    f[ind] = 0
                    q.append((ny,nx))
    print(ans)
    return

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