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:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    x_dic = {val:idx for idx, val in enumerate(x_list)}
    y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = [x_list[0]]+x_list
    tmp2 = x_list+[x_list[-1]]
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = [y_list[0]]+y_list
    tmp2 = y_list+[y_list[-1]]
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = x_dic[a]
        b_i = x_dic[b]
        c_i = y_dic[c]
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = x_dic[d]
        e_i = y_dic[e]
        f_i = y_dic[f]
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]
    if not ret:
        print('INF')
        return None

    while queue:
        x, y = queue.popleft()
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            next_sq = x_grid[n_x] * y_grid[n_y]
            if not seen[n_x][n_y] and not walls[x][y] & (1 << w_i):
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                ret += next_sq
                if not next_sq:
                    print('INF')
                    return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    x_dic = {val:idx for idx, val in enumerate(x_list)}
    y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = [x_list[0]]+x_list
    tmp2 = x_list+[x_list[-1]]
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = [y_list[0]]+y_list
    tmp2 = y_list+[y_list[-1]]
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = x_dic[a]
        b_i = x_dic[b]
        c_i = y_dic[c]
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = x_dic[d]
        e_i = y_dic[e]
        f_i = y_dic[f]
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = x_grid[start_x] * y_grid[start_y]

    while queue:
        x, y = queue.popleft()
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            if seen[n_x][n_y] or walls[x][y] & (1 << w_i):continue
            next_sq = x_grid[n_x] * y_grid[n_y]
            if next_sq:
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True
                ret += next_sq
            else:
                print('INF')
                return None

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    x_dic = {val:idx for idx, val in enumerate(x_list)}
    y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = [x_list[0]]+x_list
    tmp2 = x_list+[x_list[-1]]
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = [y_list[0]]+y_list
    tmp2 = y_list+[y_list[-1]]
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = x_dic[a]
        b_i = x_dic[b]
        c_i = y_dic[c]
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = x_dic[d]
        e_i = y_dic[e]
        f_i = y_dic[f]
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = 0

    while queue:
        x, y = queue.popleft()
        next_sq = x_grid[x] * y_grid[y]
        ret += next_sq
        if not next_sq:
            print('INF')
            return None
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            if seen[n_x][n_y] or walls[x][y] & (1 << w_i):continue
            if 0 <= n_x <= max_x and 0 <= n_y <= max_y:
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
from bisect import bisect_left
def input(): return sys.stdin.readline().strip()

"""
    全く分からなかったので解説放送の写し。
        ・マス目に対してもBFSはできるのか！
        ・(NEW!)座標圧縮という技を使って計算量を削減できるのか
    あと壁に厚みを持たせて黒マスとして扱えばBFSがしやすくなる
"""

def main():
    N, M = map(int, input().split())
    X = set([])
    Y = set([])
    mapX = {}  # mapX[x] = (柵の座標xが小さい方から何番目か)
    mapY = {}  # mapX[y] = (柵の座標yが小さい方から何番目か)
    horizontal = []
    vertical = []
    for _ in range(N):
        a, b, c = map(int, input().split())
        X.add(a)
        X.add(b)
        Y.add(c)
        vertical.append((a, b, c))
    for _ in range(M):
        d, e, f = map(int, input().split())
        X.add(d)
        Y.add(e)
        Y.add(f)
        horizontal.append((d, e, f))
    X = list(X)
    Y =list(Y)
    X.sort()
    Y.sort()

    # 座標圧縮とはすなわち左（下）から何番目かを求めることに他ならない
    for i, x in enumerate(X):
        mapX[x] = i
    for i, y in enumerate(Y):
        mapY[y] = i

    # 圧縮後の座標平面に対してグリッドを張るので、そのサイズを求めておく
    # 柵は偶数マス目に乗るようにするので２倍しておく
    h = len(mapX) * 2
    w = len(mapY) * 2
    #print("grid size: (h,w)=({},{})".format(h, w))

    # グリッド作成、柵部分は-1の値を入れたブロックとして扱う
    # また偶数グリッドは面積0として扱う
    grid = [[0] * w for _ in range(h)]
    for i in range(N):
        a = mapX[vertical[i][0]] * 2
        b = mapX[vertical[i][1]] * 2
        c = mapY[vertical[i][2]] * 2
        for x in range(a, b + 1): grid[x][c] = -1
    for j in range(M):
        d = mapX[horizontal[j][0]] * 2
        e = mapY[horizontal[j][1]] * 2
        f = mapY[horizontal[j][2]] * 2
        for y in range(e, f + 1): grid[d][y] = -1
    
    # BFSをする前に、スタート地点が柵単位で数えたためにもはや(0, 0)ではなくなっているため、
    # まずは開始位置を二分探索で求めておく
    start_x = bisect_left(X, 0) * 2 - 1
    start_y = bisect_left(Y, 0) * 2 - 1
    if start_x < 0 or start_y < 0:
        print("INF")
        return
    grid[start_x][start_y] = 1

    # BFS
    dx = [-1, 0, 1, 0]
    dy = [0, -1, 0, 1]
    q = deque([(start_x, start_y)])
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if nx < 0 or nx >= h: continue # 範囲外へのはみだしは無視
            if ny < 0 or ny >= w: continue # 範囲外へのはみだしは無視
            if (grid[nx][ny] != 0): continue  # 既に訪れたか、柵に乗ったら無視
            grid[nx][ny] = 1
            q.append((nx, ny))

    # 行けるマスは1としておいたので、後はそのマスを実寸の面積に拡大
    ans = 0
    for x in range(h):
        for y in range(w):
            if grid[x][y] != 1: continue # 行けなかったマスは無視
            if x == 0 or x == h - 1 or y == 0 or y == w - 1: # 範囲外に出たことになるのでINF
                print("INF")
                return
            if x % 2 == 0 or y % 2 == 0: continue # 壁用に割り当てたマスは面積0の扱い
            ex = X[x // 2 + 1] - X[x // 2]
            ey = Y[y // 2 + 1] - Y[y // 2]
            ans += ex * ey
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,M = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(N)]
DEF = [tuple(map(int,input().split())) for i in range(M)]
INF = float('inf')

def solve():
    xs = set([-INF,0,INF])
    ys = set([-INF,0,INF])
    for a,b,c in ABC:
        xs.add(a)
        xs.add(b)
        ys.add(c)
    for d,e,f in DEF:
        xs.add(d)
        ys.add(e)
        ys.add(f)
    xs = sorted(xs)
    ys = sorted(ys)
    xd = {x:i*2 for i,x in enumerate(xs)}
    yd = {y:i*2 for i,y in enumerate(ys)}

    W = len(xs)*2 - 1
    H = len(ys)*2 - 1
    S = [[0]*W for _ in range(H)]
    for y in (0,-1):
        for x in range(W):
            S[y][x] = 1
    for x in (0,-1):
        for y in range(H):
            S[y][x] = 1
    for a,b,c in ABC:
        for x in range(xd[a], xd[b]+1):
            S[yd[c]][x] = 1
    for d,e,f in DEF:
        for y in range(yd[e], yd[f]+1):
            S[y][xd[d]] = 1

    from collections import deque
    sx,sy = xd[0]+1, yd[0]+1
    q = deque([(sx,sy)])
    visited = [[0]*W for _ in range(H)]
    visited[sy][sx] = 1
    dxy = [(0,1),(1,0),(0,-1),(-1,0)]
    ans = (xs[sx//2+1] - xs[sx//2]) * (ys[sy//2+1] - ys[sy//2])
    while q:
        x,y = q.popleft()
        for dx,dy in dxy:
            nx,ny = x+dx,y+dy
            if S[ny][nx] == 1: continue
            nnx,nny = nx+dx,ny+dy
            if visited[nny][nnx]: continue
            visited[nny][nnx] = 1
            q.append((nnx,nny))
            tx,ty = (nx,nny) if nx%2 else (nnx,ny)
            assert tx%2 and ty%2
            w = xs[tx//2+1] - xs[tx//2]
            h = ys[ty//2+1] - ys[ty//2]
            ans += w*h
            if ans==INF:
                print('INF')
                exit()
    print(ans)
solve()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
#import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_x = len(x_list)
    max_y = len(y_list)
    x_dic = {val:idx for idx, val in enumerate(x_list)}
    y_dic = {val:idx for idx, val in enumerate(y_list)}
    #print(x_list)
    tmp1 = [x_list[0]]+x_list
    tmp2 = x_list+[x_list[-1]]
    x_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        x_grid.append(t2-t1)
    #print(x_grid)
    tmp1 = [y_list[0]]+y_list
    tmp2 = y_list+[y_list[-1]]
    y_grid = []
    for t1, t2 in zip(tmp1, tmp2):
        y_grid.append(t2-t1)
    #print(y_list)
    #print(y_grid)
    #grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = x_dic[a]
        b_i = x_dic[b]
        c_i = y_dic[c]
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] |= 1 << 1
            walls[_x][c_i+1] |= 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = x_dic[d]
        e_i = y_dic[e]
        f_i = y_dic[f]
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] |= 1 << 0
            walls[d_i+1][_y] |= 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    ret = 0

    while queue:
        x, y = queue.popleft()
        next_sq = x_grid[x] * y_grid[y]
        ret += next_sq
        if not next_sq:
            print('INF')
            return None
        for w_i, i, j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            n_x, n_y = x+i, y+j
            if seen[n_x][n_y]:continue
            if walls[x][y] & (1 << w_i):continue
            if 0 <= n_x <= max_x and 0 <= n_y <= max_y:
                queue.append((n_x, n_y))
                seen[n_x][n_y] = True

    print(int(ret))

if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,M = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(N)]
DEF = [tuple(map(int,input().split())) for i in range(M)]
INF = float('inf')

def solve():
    xs = set([-INF,0,INF])
    ys = set([-INF,0,INF])
    for a,b,c in ABC:
        xs.add(a)
        xs.add(b)
        ys.add(c)
    for d,e,f in DEF:
        xs.add(d)
        ys.add(e)
        ys.add(f)
    xs = sorted(xs)
    ys = sorted(ys)
    xd = {x:i*2 for i,x in enumerate(xs)}
    yd = {y:i*2 for i,y in enumerate(ys)}

    W = len(xs)*2 - 1
    H = len(ys)*2 - 1
    S = [[0]*W for _ in range(H)]
    for y in (0,-1):
        for x in range(W):
            S[y][x] = 1
    for x in (0,-1):
        for y in range(H):
            S[y][x] = 1
    for a,b,c in ABC:
        for x in range(xd[a], xd[b]+1):
            S[yd[c]][x] = 1
    for d,e,f in DEF:
        for y in range(yd[e], yd[f]+1):
            S[y][xd[d]] = 1

    from collections import deque
    q = deque([(xd[0], yd[0])])
    visited = [[0]*W for _ in range(H)]
    visited[yd[0]][xd[0]] = 1
    dxy = [(0,1),(1,0),(0,-1),(-1,0)]
    ans = 0
    while q:
        x,y = q.popleft()
        for dx,dy in dxy:
            nx,ny = x+dx,y+dy
            if visited[ny][nx]: continue
            if S[ny][nx] == 1: continue
            visited[ny][nx] = 1
            q.append((nx,ny))
            if nx%2 and ny%2:
                w = xs[nx//2+1] - xs[nx//2]
                h = ys[ny//2+1] - ys[ny//2]
                ans += w*h
                if ans==INF:
                    print('INF')
                    exit()
    print(ans)
solve()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N,M = map(int,input().split())
ABC = [tuple(map(int,input().split())) for i in range(N)]
DEF = [tuple(map(int,input().split())) for i in range(M)]
INF = float('inf')

xs = set([-INF,0,INF])
ys = set([-INF,0,INF])
for a,b,c in ABC:
    xs.add(a)
    xs.add(b)
    ys.add(c)
for d,e,f in DEF:
    xs.add(d)
    ys.add(e)
    ys.add(f)
xs = sorted(xs)
ys = sorted(ys)
xd = {x:i*2 for i,x in enumerate(xs)}
yd = {y:i*2 for i,y in enumerate(ys)}

W = len(xs)*2 - 1
H = len(ys)*2 - 1
S = [[0]*W for _ in range(H)]
for y in (0,-1):
    for x in range(W):
        S[y][x] = 1
for x in (0,-1):
    for y in range(H):
        S[y][x] = 1
for a,b,c in ABC:
    for x in range(xd[a], xd[b]+1):
        S[yd[c]][x] = 1
for d,e,f in DEF:
    for y in range(yd[e], yd[f]+1):
        S[y][xd[d]] = 1

from collections import deque
q = deque([(xd[0], yd[0])])
visited = [[0]*W for _ in range(H)]
visited[yd[0]][xd[0]] = 1
dxy = [(0,1),(1,0),(0,-1),(-1,0)]
ans = 0
while q:
    x,y = q.popleft()
    for dx,dy in dxy:
        nx,ny = x+dx,y+dy
        if visited[ny][nx]: continue
        if S[ny][nx] == 1: continue
        visited[ny][nx] = 1
        q.append((nx,ny))
        if nx%2 and ny%2:
            w = xs[nx//2+1] - xs[nx//2]
            h = ys[ny//2+1] - ys[ny//2]
            ans += w*h
            if ans==INF:
                print('INF')
                exit()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_sq = (x_list[-1]-x_list[0]) * (y_list[-1] - y_list[0])
    max_x = len(x_list)
    max_y = len(y_list)
    #print(x_list)
    tmp1 = np.array([x_list[0]]+x_list)
    tmp2 = np.array(x_list+[x_list[-1]])
    x_grid = tmp2 - tmp1
    #print(x_grid)
    tmp1 = np.array([y_list[0]] + y_list)
    tmp2 = np.array(y_list + [y_list[-1]])
    y_grid = tmp2 - tmp1
    #print(y_list)
    #print(y_grid)
    grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = [[False] * (max_y+1) for _ in range(max_x+1)]
    walls = [[0] * (max_y+1) for _ in range(max_x+1)]
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        for _x in range(a_i+1, b_i+1):
            walls[_x][c_i] += 1 << 1
            walls[_x][c_i+1] += 1 << 3

    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        for _y in range(e_i+1, f_i+1):
            walls[d_i][_y] += 1 << 0
            walls[d_i+1][_y] += 1 << 2


    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True


    ret = grid[start_x][start_y]
    while queue:
        x, y = queue.popleft()
        if x * y == 0 or x == max_x or y == max_y:
            print('INF')
            return None
        for w_i, i,j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            if not seen[x+i][y+j] and not walls[x][y] & 1 << w_i and 0 <= x+i <= max_x and 0 <= y+j <= max_y:
                queue.append((x + i, y + j))
                seen[x + i][y + j] = True
                ret += grid[x + i][y + j]

    print(ret)
if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_sq = (x_list[-1]-x_list[0]) * (y_list[-1] - y_list[0])
    #print(x_list)
    tmp1 = np.array([x_list[0]]+x_list)
    tmp2 = np.array(x_list+[x_list[-1]])
    x_grid = tmp2 - tmp1
    #print(x_grid)
    tmp1 = np.array([y_list[0]] + y_list)
    tmp2 = np.array(y_list + [y_list[-1]])
    y_grid = tmp2 - tmp1
    #print(y_list)
    #print(y_grid)
    grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1)).tolist()
    seen = np.zeros_like(grid, dtype=np.bool).tolist()
    walls = np.zeros_like(grid, dtype=np.int32)
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        walls[a_i+1:b_i+1, c_i] += 1 << 1
        walls[a_i+1:b_i+1, c_i+1] += 1 << 3
    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        walls[d_i,e_i+1:f_i+1] += 1 << 0
        walls[d_i+1,e_i+1:f_i+1] += 1 << 2
    walls = walls.tolist()

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x][start_y] = True
    max_x = len(x_list)
    max_y = len(y_list)

    ret = grid[start_x][start_y]
    while queue:
        x, y = queue.popleft()
        if x * y == 0 or x == max_x or y == max_y:
            print('INF')
            return None
        for w_i, i,j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            if not seen[x+i][y+j] and not walls[x][y] & 1 << w_i and 0 <= x+i <= max_x and 0 <= y+j <= max_y:
                queue.append((x + i, y + j))
                seen[x + i][y + j] = True
                ret += grid[x + i][y + j]




    print(ret)
if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_sq = (x_list[-1]-x_list[0]) * (y_list[-1] - y_list[0])
    #print(x_list)
    tmp1 = np.array([x_list[0]]+x_list)
    tmp2 = np.array(x_list+[x_list[-1]])
    x_grid = tmp2 - tmp1
    #print(x_grid)
    tmp1 = np.array([y_list[0]] + y_list)
    tmp2 = np.array(y_list + [y_list[-1]])
    y_grid = tmp2 - tmp1
    #print(y_list)
    #print(y_grid)
    grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1))
    seen = np.zeros_like(grid, dtype=np.bool)
    walls = np.zeros_like(grid, dtype=np.int32)
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        walls[a_i+1:b_i+1, c_i] += 1 << 1
        walls[a_i+1:b_i+1, c_i+1] += 1 << 3
    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        walls[d_i,e_i+1:f_i+1] += 1 << 0
        walls[d_i+1,e_i+1:f_i+1] += 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x, start_y] = True
    max_x = len(x_list)
    max_y = len(y_list)

    ret = grid[start_x, start_y]
    while queue:
        x, y = queue.popleft()
        if x * y == 0 or x == max_x or y == max_y:
            print('INF')
            return None
        for w_i, i,j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            if not seen[x+i, y+j] and not walls[x, y] & 1 << w_i and 0 <= x+i <= max_x and 0 <= y+j <= max_y:
                queue.append((x + i, y + j))
                seen[x + i, y + j] = True
                ret += grid[x + i, y + j]




    print(ret)
if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
read = sys.stdin.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product#accumulate, combinations, product
import bisect# lower_bound etc
import numpy as np
#from copy import deepcopy
from collections import deque
def run():
    N,M, *A2F = map(int, read().split())
    A = A2F[0:3*N:3]
    B = A2F[1:3*N+1:3]
    C = A2F[2:3*N+2:3]
    D = A2F[3*N::3]
    E = A2F[3*N+1::3]
    F = A2F[3*N+2::3]

    x_list, y_list = sorted(list(set(A+B+D))), sorted(list(set(C+E+F)))
    max_sq = (x_list[-1]-x_list[0]) * (y_list[-1] - y_list[0])
    #print(x_list)
    tmp1 = np.array([x_list[0]]+x_list)
    tmp2 = np.array(x_list+[x_list[-1]])
    x_grid = tmp2 - tmp1
    #print(x_grid)
    tmp1 = np.array([y_list[0]] + y_list)
    tmp2 = np.array(y_list + [y_list[-1]])
    y_grid = tmp2 - tmp1
    #print(y_list)
    #print(y_grid)
    grid = np.dot(x_grid.reshape(-1,1), y_grid.reshape(1,-1))
    seen = np.zeros_like(grid, dtype=np.bool)
    walls = np.zeros_like(grid, dtype=np.int32)
    for a,b,c in zip(A,B,C):
        a_i = bisect.bisect_left(x_list, a)
        b_i = bisect.bisect_left(x_list, b)
        c_i = bisect.bisect_left(y_list, c)
        walls[a_i+1:b_i+1, c_i] += 1 << 1
        walls[a_i+1:b_i+1, c_i+1] += 1 << 3
    for d,e,f in zip(D,E,F):
        d_i = bisect.bisect_left(x_list, d)
        e_i = bisect.bisect_left(y_list, e)
        f_i = bisect.bisect_left(y_list, f)
        walls[d_i,e_i+1:f_i+1] += 1 << 0
        walls[d_i+1,e_i+1:f_i+1] += 1 << 2

    start_x = bisect.bisect_left(x_list, 0)
    start_y = bisect.bisect_left(y_list, 0)

    queue = deque([])
    queue.append((start_x, start_y))
    seen[start_x, start_y] = True
    max_x = len(x_list)
    max_y = len(y_list)

    ret = grid[start_x, start_y]
    while queue:
        x, y = queue.popleft()
        if x == 0 or y == 0 or x == max_x or y == max_y:
            print('INF')
            return None
        for w_i, i,j in ((1,0,1), (3,0,-1), (0,1,0),(2,-1,0)):
            if 0 <= x+i <= max_x and 0 <= y+j <= max_y:
                if not walls[x, y] & 1 << w_i:
                    if not seen[x+i, y+j]:
                        queue.append((x + i, y + j))
                        seen[x + i, y + j] = True
                        ret += grid[x + i, y + j]


    print(ret)
if __name__ == "__main__":
    run()