Problem:


Score: 600 points

Problem Statement

M-kun is a brilliant air traffic controller.

On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude.

Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the direction of the airplane is as follows:

if U_i is U, it flies in the positive y direction;

if U_i is R, it flies in the positive x direction;

if U_i is D, it flies in the negative y direction;

if U_i is L, it flies in the negative x direction.

To help M-kun in his work, determine whether there is a pair of airplanes that will collide with each other if they keep flying as they are now.

If there is such a pair, find the number of seconds after which the first collision will happen.

We assume that the airplanes are negligibly small so that two airplanes only collide when they reach the same coordinates simultaneously.

Constraints

1 \leq N \leq 200000

0 \leq X_i, Y_i \leq 200000

U_i is U, R, D, or L.

The current positions of the N airplanes, (X_i, Y_i), are all distinct.

N, X_i, and Y_i are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 U_1
X_2 Y_2 U_2
X_3 Y_3 U_3
:
X_N Y_N U_N

Output

If there is a pair of airplanes that will collide with each other if they keep flying as they are now, print an integer representing the number of seconds after which the first collision will happen.

If there is no such pair, print SAFE.

Sample Input 1

2
11 1 U
11 47 D

Sample Output 1

230

If the airplanes keep flying as they are now, two airplanes numbered 1 and 2 will reach the coordinates (11, 24) simultaneously and collide.  

Sample Input 2

4
20 30 U
30 20 R
20 10 D
10 20 L

Sample Output 2

SAFE

No pair of airplanes will collide.

Sample Input 3

8
168 224 U
130 175 R
111 198 D
121 188 L
201 116 U
112 121 R
145 239 D
185 107 L

Sample Output 3

100



Sample input:
2
11 1 U
11 47 D


Sample output:
230

Submission status: Wrong Answer

Solution code:
check=200000

import sys

input=sys.stdin.readline

N=int(input())
U=[]
R=[]
D=[]
L=[]
for i in range(N):
    x,y,u=input().split()
    print(x,y,u)
    x,y=int(x),int(y)
    if u=="U":
        U.append((x,y,u))
    elif u=="R":
        R.append((x,y,u))
    elif u=="D":
        D.append((x,y,u))
    else:
        L.append((x,y,u))

ans=10**18

#DR
DR=D+R
DR.sort()
data=[[] for i in range(2*check+1)]
for x,y,u in DR:
    t=y-x+check
    if u=="R":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*x-2*X)

#DL
DL=D+L
DL.sort(reverse=True)
data=[[] for i in range(2*check+1)]
for x,y,u in DL:
    t=x+y
    if u=="L":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*X-2*x)

#UR
UR=U+R
UR.sort()
data=[[] for i in range(2*check+1)]
for x,y,u in UR:
    t=x+y
    if u=="R":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*x-2*X)

#UL
UL=U+L
UL.sort(reverse=True)
data=[[] for i in range(2*check+1)]
for x,y,u in UL:
    t=y-x+check
    if u=="L":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*X-2*x)

#UD
UD=U+D
UD.sort(key=lambda x:x[1])
data=[[] for i in range(check+1)]
for x,y,u in UD:
    if u=="U":
        data[x].append(y)
    else:
        if data[x]:
            Y=data[x][-1]
            ans=min(ans,(y-Y))

#LR
LR=L+R
LR.sort()
data=[[] for i in range(check+1)]
for x,y,u in LR:
    if u=="R":
        data[y].append(x)
    else:
        if data[y]:
            X=data[y][-1]
            ans=min(ans,(x-X))

if ans==10**18:
    print("SAFE")
    exit()
print(int(ans*5))

Submission status: Wrong Answer

Solution code:
check=200000

import sys

input=sys.stdin.readline

N=int(input())
U=[]
R=[]
D=[]
L=[]
for i in range(N):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=="U":
        U.append((x,y,u))
    elif u=="R":
        R.append((x,y,u))
    elif u=="D":
        D.append((x,y,u))
    else:
        L.append((x,y,u))

ans=10**18

#DR
DR=D+R
DR.sort()
data=[[] for i in range(2*check+1)]
for x,y,u in DR:
    t=y-x+check
    if u=="R":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*x-2*X)

#DL
DL=D+L
DL.sort(reverse=True)
data=[[] for i in range(2*check+1)]
for x,y,u in DL:
    t=x+y
    if u=="L":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*X-2*x)

#UR
UR=U+R
UR.sort()
data=[[] for i in range(2*check+1)]
for x,y,u in UR:
    t=x+y
    if u=="R":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*x-2*X)

#UL
UL=U+L
UL.sort(reverse=True)
data=[[] for i in range(2*check+1)]
for x,y,u in UL:
    t=y-x+check
    if u=="L":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*X-2*x)

#UD
UD=U+D
UD.sort(key=lambda x:x[1])
data=[[] for i in range(check+1)]
for x,y,u in UD:
    if u=="U":
        data[x].append(y)
    else:
        if data[x]:
            Y=data[x][-1]
            ans=min(ans,(y-Y))

#LR
LR=L+R
LR.sort()
data=[[] for i in range(check+1)]
for x,y,i in LR:
    if u=="R":
        data[y].append(x)
    else:
        if data[y]:
            X=data[y][-1]
            ans=min(ans,(x-X))

if ans==10**18:
    print("SAFE")
    exit()
print(int(ans*5))

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
xyu = [None]*n
from collections import defaultdict
dx = defaultdict(list)
dy = defaultdict(list)
dxpy = defaultdict(list)
dxmy = defaultdict(list)
for i in range(n):
    x,y,u = input().split()
    x,y = (int(x), int(y))
    dx[x].append((y, u))
    dy[y].append((x, u))
    dxpy[x+y].append((x,u))
    dxmy[x-y].append((x,u))

def sub(maru, batu):
    ans = float("inf")
    if not maru or not batu:
        return ans
    maru.sort()
    batu.sort()
    j = -1
    for i in range(len(maru)):
        if j<i:
            j = i
        while j+1<len(batu) and batu[j+1]<=maru[i]:
            j += 1
        if j<len(batu) and batu[j]-maru[i]>=0:
            ans = min(ans, batu[j]-maru[i])
    return ans
ans = float("inf")
for v in dy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*5)
for v in dx.values():
    maru = [item[0] for item in v if item[1]=="U"]
    batu = [item[0] for item in v if item[1]=="D"]
    ans = min(ans, sub(maru, batu)*5)
for v in dxpy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="U"]
    ans = min(ans, sub(maru, batu)*10)
    maru = [item[0] for item in v if item[1]=="D"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*10)
for v in dxmy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="D"]
    ans = min(ans, sub(maru, batu)*10)
    maru = [item[0] for item in v if item[1]=="U"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*10)
if ans==float("inf"):
    ans = "SAFE"
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
xyu = [None]*n
from collections import defaultdict
dx = defaultdict(list)
dy = defaultdict(list)
dxpy = defaultdict(list)
dxmy = defaultdict(list)
for i in range(n):
    x,y,u = input().split()
    x,y = (int(x), int(y))
    dx[x].append((y, u))
    dy[y].append((x, u))
    dxpy[x+y].append((x,u))
    dxmy[x-y].append((x,u))

def sub(maru, batu):
    ans = float("inf")
    if not maru or not batu:
        return ans
    maru.sort()
    batu.sort()
    j = -1
    for i in range(len(maru)):
        while j+1<len(batu) and batu[j+1]<=maru[i]:
            j += 1
        if batu[j]-maru[i]>=0:
            ans = min(ans, batu[j]-maru[i])
    return ans
ans = float("inf")
for v in dy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*5)
for v in dx.values():
    maru = [item[0] for item in v if item[1]=="U"]
    batu = [item[0] for item in v if item[1]=="D"]
    ans = min(ans, sub(maru, batu)*5)
for v in dxpy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="U"]
    ans = min(ans, sub(maru, batu)*10)
    maru = [item[0] for item in v if item[1]=="D"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*10)
for v in dxmy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="D"]
    ans = min(ans, sub(maru, batu)*10)
    maru = [item[0] for item in v if item[1]=="U"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*10)
if ans==float("inf"):
    ans = "SAFE"
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
import numba
from numba import njit
i8 = numba.int64

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit((i8[:], i8[:], i8[:], i8[:]), cache=True)
def f(X1, Y1, X2, Y2):
    # x1,y1 から y が増える側に移動 vs x2,y2 から y が減る側に移動
    ret = 10**18
    key1 = (X1 << 32) + Y1
    key2 = (X2 << 32) + Y2
    ind = key1.argsort()
    X1, Y1, key1 = X1[ind], Y1[ind], key1[ind]
    ind = key2.argsort()
    X2, Y2, key2 = X2[ind], Y2[ind], key2[ind]
    js = np.searchsorted(key2, key1)
    for i in range(len(key1)):
        j = js[i]
        if j == len(key2):
            continue
        if X1[i] != X2[j]:
            continue
        ret = min(ret, Y2[j] - Y1[i])
    return ret

N = int(readline())
X = []
Y = []
U = []
for _ in range(N):
    x, y, u = readline().split()
    X.append(int(x))
    Y.append(int(y))
    U.append(u)

X = np.array(X, np.int64)
Y = np.array(Y, np.int64)
U = np.array(U, 'S1')

i_u = U == b'U'
i_r = U == b'R'
i_d = U == b'D'
i_l = U == b'L'

Xu, Yu = X[i_u], Y[i_u]
Xr, Yr = X[i_r], Y[i_r]
Xd, Yd = X[i_d], Y[i_d]
Xl, Yl = X[i_l], Y[i_l]

INF = 10**18
ans = INF
ans = min(ans, f(Xu, Yu, Xd, Yd))  # 上、下
ans = min(ans, f(Xr, Yr, Xl, Yl))  # 右、左
ans = min(ans, f(Xr + Yr, Xr - Yr, Xu + Yu, Xu - Yu))  # 右、上
ans = min(ans, f(Xu - Yu, Xu + Yu, Xl - Yl, Xl + Yl))  # 上、左
ans = min(ans, f(Xr - Yr, Xr + Yr, Xd - Yd, Xd + Yd))  # 右、下
ans = min(ans, f(Xd + Yd, Xd - Yd, Xl + Yl, Xl - Yl))  # 下、左
print('SAFE' if ans == INF else 5 * ans)

Submission status: Wrong Answer

Solution code:
import bisect
from collections import defaultdict
n = int(input())
setx = set([])
sety = set([])
x = [[] for _ in range(200001)]
y = [[] for _ in range(200001)]
for i in range(n):
	a,b,c = input().split()
	x[int(a)].append((int(a),int(b),c))
	y[int(b)].append((int(a),int(b),c))
	setx.add(int(a))
	sety.add(int(b))
ans = 20200725
for i in setx:
	#U D
	tmppy = []
	tmpny = []
	for j in x[i]:
		if j[2] == "U":
			tmppy.append(j[1])
		elif j[2] == "D":
			tmpny.append(j[1])
	tmppy.sort()
	for j in tmpny:
		tmp = bisect.bisect_left(tmppy, j)
		if tmp >= 1:
			targ = j-tmppy[tmp-1]
			ans = min(5*targ, ans)
for i in sety:
	tmppx = []
	tmpnx = []
	for j in x[i]:
		if j[2] == "R":
			tmppx.append(j[0])
		elif j[2] == "L":
			tmpnx.append(j[0])
	tmppx.sort()
	for j in tmpnx:
		tmp = bisect.bisect_left(tmppx, j)
		if tmp >= 1:
			targ = j-tmppx[tmp-1]
			ans = min(5*targ, ans)
if ans == 20200725:
	print("SAFE")
else:
	print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from bisect import *

def into_dict(dics,x,y,u):
  x,y = int(x),int(y)
  insort(dics[u+'_x'][x],y)
  insort(dics[u+'_y'][y],x)
  insort(dics[u+'_xpy'][x+y],x)
  insort(dics[u+'_ymx'][y-x],x)
  return dics

def para(dics,dic1,dic2):
  ans = float('inf')
  for k,v in dics[dic1].items():
    for zahyou in v[1:-1]:
      ind = bisect_right(dics[dic2][k],zahyou)
      dis = zahyou-dics[dic2][k][ind-1]
      ans = min(ans,dis)
  return ans

import sys; input=sys.stdin.readline
def solve():
  ans = []
  N = int(input())
  dics = defaultdict(lambda: defaultdict(lambda: [-float('inf'),float('inf')]))
  for i in range(N):
    dics = into_dict(dics,*input().split())
  lis1 = [['L_y','R_y'],['D_x','U_x']]
  lis2 = [['L_ymx','U_ymx'],['U_xpy','R_xpy'],['L_xpy','D_xpy'],['D_ymx','R_ymx']]
  for arg in lis1:
    ans.append(para(dics,*arg)*5)
  for arg in lis2:
    ans.append(para(dics,*arg)*10)
  ans = min(ans)
  return ans if ans<float('inf') else 'SAFE'
print(solve())

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
from enum import IntEnum

rl = sys.stdin.buffer.readline
INF = sys.maxsize

class Direction(IntEnum):
  UP = 1
  RIGHT = 2
  DOWN = 3
  LEFT = 4

direction_of_str = {
  b'U': Direction.UP,
  b'R': Direction.RIGHT,
  b'D': Direction.DOWN,
  b'L': Direction.LEFT,
}

X = 0
Y = 1

def read_data(n):
  d = {
    Direction.UP: [],
    Direction.RIGHT: [],
    Direction.DOWN: [],
    Direction.LEFT: []
  }
  for _ in range(n):
    l = rl().split()
    d[direction_of_str[l[2]]].append((int(l[0]), int(l[1])))
  return d

N = int(rl())
PS = read_data(N)

col_dist = INF

# UP
for u in PS[Direction.UP]:
  # 正面衝突
  for d in PS[Direction.DOWN]:
    if u[X] == d[X] and u[Y] < d[Y]:
      col_dist = min(col_dist, ((d[Y]-u[Y]) * 10) // 2)
  # 横
  for r in PS[Direction.RIGHT]:
    if u[Y] < r[Y] and r[Y]-u[Y] == u[X]-r[X]:
      col_dist = min(col_dist, (r[Y]-u[Y]) * 10)
  for l in PS[Direction.LEFT]:
    if u[Y] < l[Y] and l[Y]-u[Y] == l[X]-u[X]:
      col_dist = min(col_dist, (l[Y]-u[Y]) * 10)

# RIGHT
for r in PS[Direction.RIGHT]:
  # 正面衝突
  for l in PS[Direction.LEFT]:
    if r[Y] == l[Y] and r[X] < l[X]:
      col_dist = min(col_dist, ((l[X]-r[X]) * 10) // 2)
  # 横
  for d in PS[Direction.DOWN]:
    if r[X] < d[X] and d[X]-r[X] == d[Y]-r[Y]:
      col_dist = min(col_dist, (d[X]-r[X]) * 10)

# DOWN
for d in PS[Direction.DOWN]:
  # 横
  for l in PS[Direction.LEFT]:
    if d[X] < l[X] and l[X]-d[X] == d[Y]-l[Y]:
      col_dist = min(col_dist, (l[X]-d[X]) * 10)

print(col_dist if col_dist < INF else 'SAFE')

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

dic_up = {}
dic_down = {}
dic_hor = {}
dic_ver = {}
lst = []
for i in range(n):
    xi, yi, ui = input().split()
    xi, yi = int(xi), int(yi)
    up = xi - yi
    down = xi + yi
    if (ui, up) in dic_up:
        dic_up[(ui, up)].append(xi)
    else:
        dic_up[(ui, up)] = [xi]
    if (ui, down) in dic_down:
        dic_down[(ui, down)].append(xi)
    else:
        dic_down[(ui, down)] = [xi]
    if (ui, xi) in dic_ver:
        dic_ver[(ui, xi)].append(yi)
    else:
        dic_ver[(ui, xi)] = [yi]
    if (ui, yi) in dic_hor:
        dic_hor[(ui, yi)].append(xi)
    else:
        dic_hor[(ui, yi)] = [xi]
    lst.append([xi, yi, ui, up, down])

for key in dic_up.keys():
    dic_up[key].sort()
for key in dic_down.keys():
    dic_down[key].sort()
for key in dic_hor.keys():
    dic_hor[key].sort()
for key in dic_ver.keys():
    dic_ver[key].sort()

ans = 10**9
for i in range(n):
    xi, yi, ui, up, down = lst[i]
    if ui == 'U':
        if ('D', xi) in dic_ver:
            kouho = 10**9
            for dy in dic_ver[('D', xi)]:
                if dy > yi:
                    kouho = min(kouho, (dy-yi)*5)
            ans = min(ans, kouho)
        if ('L', up) in dic_up:
            kouho = 10**9
            for lx in dic_up[('L', up)]:
                if lx > xi:
                    kouho = min(kouho, (lx-xi)*10)
            ans = min(ans, kouho)
    if ui == 'R':
        if ('U', down) in dic_down:
            kouho = 10**9
            for ux in dic_down[('U', down)]:
                if ux > xi:
                    kouho = min(kouho, (ux-xi)*10)
            ans = min(ans, kouho)
        if ('D', up) in dic_up:
            kouho = 10**9
            for dx in dic_up[('D', up)]:
                if dx > xi:
                    kouho = min(kouho, (dx-xi)*10)
            ans = min(ans, kouho)
        if ('L', yi) in dic_hor:
            kouho = 10**9
            for lx in dic_hor[('L', yi)]:
                if lx > xi:
                    kouho = min(kouho, (lx-xi)*5)
            ans = min(ans, kouho)
    if ui == 'D':
        if ('L', down) in dic_down:
            kouho = 10**9
            for lx in dic_down[('L', down)]:
                if lx > xi:
                    kouho = min(kouho, (lx-xi)*10)
            ans = min(ans, kouho)

if ans == 10**9:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

dic_up = {}
dic_down = {}
dic_hor = {}
dic_ver = {}
lst = []
for i in range(n):
    xi, yi, ui = input().split()
    xi, yi = int(xi), int(yi)
    up = xi - yi
    down = xi + yi
    if (ui, up) in dic_up:
        dic_up[(ui, up)].append([xi, yi])
    else:
        dic_up[(ui, up)] = [[xi, yi]]
    if (ui, down) in dic_down:
        dic_down[(ui, down)].append([xi, yi])
    else:
        dic_down[(ui, down)] = [[xi, yi]]
    if (ui, xi) in dic_ver:
        dic_ver[(ui, xi)].append(yi)
    else:
        dic_ver[(ui, xi)] = [yi]
    if (ui, yi) in dic_hor:
        dic_hor[(ui, yi)].append(xi)
    else:
        dic_hor[(ui, yi)] = [xi]
    lst.append([xi, yi, ui, up, down])

ans = 10**9
for i in range(n):
    xi, yi, ui, up, down = lst[i]
    if ui == 'U':
        if ('R', down) in dic_down:
            kouho = 10**9
            for rx, ry in dic_down[('R', down)]:
                if xi > rx:
                    kouho = min(kouho, (xi-rx)*10)
            ans = min(ans, kouho)
        if ('D', xi) in dic_ver:
            kouho = 10**9
            for dy in dic_ver[('D', xi)]:
                if dy > yi:
                    kouho = min(kouho, (dy-yi)*5)
            ans = min(ans, kouho)
        if ('L', up) in dic_up:
            kouho = 10**9
            for lx, ly in dic_up[('L', up)]:
                if lx > xi:
                    kouho = min(kouho, (lx-xi)*10)
            ans = min(ans, kouho)
    if ui == 'R':
        if ('D', up) in dic_up:
            kouho = 10**9
            for dx, dy in dic_up[('D', up)]:
                if dx > xi:
                    kouho = min(kouho, (dx-xi)*10)
            ans = min(ans, kouho)
        if ('L', yi) in dic_hor:
            kouho = 10**9
            for lx in dic_hor[('L', yi)]:
                if lx > xi:
                    kouho = min(kouho, (lx-xi)*5)
            ans = min(ans, kouho)
    if ui == 'D':
        if ('L', down) in dic_down:
            kouho = 10**9
            for lx, ly in dic_down[('L', down)]:
                if lx > xi:
                    kouho = min(kouho, (lx-xi)*10)
            ans = min(ans, kouho)

if ans == 10**9:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
INF = float("inf")

sc = iter(open(0).read().split())
ni = lambda: int(next(sc))
ns = lambda: next(sc)

LR, UD, RU, LD, LU, RD = [[[] for _ in range(400_100)] for _ in range(6)]

U = []

N = ni()
for i in range(N):
    x, y, u = ni(), ni(), ns()
    U.append(u)

    if u in "LR":
        LR[y].append((x, i))
    if u in "UD":
        UD[x].append((y, i))
    if u in "LD":
        LD[x + y].append((y, i))
    if u in "RU":
        RU[x + y].append((y, i))
    if u in "LU":
        LU[y - x + 200_000].append((x, i))
    if u in "RD":
        RD[y - x + 200_000].append((x, i))

ans = INF
for i in range(400_001):
    LR[i].sort()
    UD[i].sort()
    LD[i].sort()
    RU[i].sort()
    LU[i].sort()
    RD[i].sort()

    ans = min(
        ans,
        5 * min(
            ((LR[i][j + 1][0] - LR[i][j][0])
            for j in range(len(LR[i]) - 1)
            if U[LR[i][j][1]] == "R" and U[LR[i][j + 1][1]] == "L"),
            default=INF
        ),
        5 * min(
            ((UD[i][j + 1][0] - UD[i][j][0])
            for j in range(len(UD[i]) - 1)
            if U[UD[i][j][1]] == "U" and U[UD[i][j + 1][1]] == "D"),
            default=INF
        ),
        10 * min(
            ((LD[i][j + 1][0] - LD[i][j][0])
            for j in range(len(LD[i]) - 1)
            if U[LD[i][j][1]] == "L" and U[LD[i][j + 1][1]] == "D"),
            default=INF
        ),
        10 * min(
            ((RU[i][j + 1][0] - RU[i][j][0])
            for j in range(len(RU[i]) - 1)
            if U[RU[i][j][1]] == "U" and U[RU[i][j + 1][1]] == "R"),
            default=INF
        ),
        10 * min(
            ((LU[i][j + 1][0] - LU[i][j][0])
            for j in range(len(LU[i]) - 1)
            if U[LU[i][j][1]] == "U" and U[LU[i][j + 1][1]] == "L"),
            default=INF
        ),
        10 * min(
            ((RD[i][j + 1][0] - RD[i][j][0])
            for j in range(len(RD[i]) - 1)
            if U[RD[i][j][1]] == "R" and U[RD[i][j + 1][1]] == "D"),
            default=INF
        )
    )

print("SAFE" if ans == INF else ans)

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
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50

def calc(Asum, Bsum, A, B, ans, ope = 1):
    if not len(A) or not len(B):
        return ans

    #print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        x1, y1 = A[ai]
        while bi < len(B_):
            val = B_[bi]
            #print(bi, val, asum)
            if val == asum:
                bi2 = Bsum[bi][1]
                x2, y2 = B[bi2]
                time = (x2 - x1) * ope
                if time < 0:
                    bi += 1
                    continue
                ans = min(ans, time*10)
            else:
                break
            bi += 1
    return ans

def calc_line(Asum, Bsum, A, B, ans):
    if not len(A) or not len(B):
        return ans

    # print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        x1, y1 = A[ai]
        while bi < len(B_):
            val = B_[bi]
            if val == asum:
                bi2 = Bsum[bi][1]
                x2, y2 = B[bi2]
                time = y2 - y1 if x1 == x2 else x2 - x1

                if time < 0:
                    bi += 1
                    continue
                ans = min(ans, time*5)
            else:
                break
            bi += 1
    return ans

def run():
    U, D, R, L = [],[],[],[]
    N = int(sysread())
    for i in range(N):
        x,y,u = input().split()
        #print(x, y, u)
        x,y = int(x), int(y)
        if u == 'U':
            U.append((x,y))
        elif u == 'D':
            D.append((x,y))
        elif u == 'R':
            R.append((x,y))
        elif u == 'L':
            L.append((x,y))

    #print(U, D, R, L)
    ans = INF
    # U vs R
    Usum = sorted([(x+y, i) for i, (x,y) in enumerate(U)])
    Rsum = sorted([(x+y, i) for i, (x,y) in enumerate(R)])
    ans = calc(Usum, Rsum, U, R, ans, ope=-1)

    # D vs L
    Dsum = sorted([(x + y, i) for i, (x, y) in enumerate(D)])
    Lsum = sorted([(x + y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Dsum, Lsum, D, L, ans, ope=1)

    # U vs L
    Usub = sorted([(x - y, i) for i, (x, y) in enumerate(U)])
    Lsub = sorted([(x - y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Usub, Lsub, U, L, ans, ope=1)

    # D vs R
    Dsub = sorted([(x - y, i) for i, (x, y) in enumerate(D)])
    Rsub = sorted([(x - y, i) for i, (x, y) in enumerate(R)])
    ans = calc(Dsub, Rsub, D, R, ans, ope=-1)

    # U vs D
    UU = sorted([(x, i) for i, (x,y) in enumerate(U)])
    DD = sorted([(x, i) for i, (x, y) in enumerate(D)])
    ans = calc_line(UU, DD, U, D, ans)

    # R vs L
    RR = sorted([(y, i) for i, (x, y) in enumerate(R)])
    LL = sorted([(y, i) for i, (x, y) in enumerate(L)])
    ans = calc_line(RR, LL, R, L, ans)

    if ans == INF:
        print('SAFE')
    else:
        print(int(ans))



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
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50

def calc(Asum, Bsum, A, B, ans, ope = 1):
    if not len(A) or not len(B):
        return ans

    #print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        x1, y1 = A[ai]
        while bi < len(B_):
            val = B_[bi]
            #print(bi, val, asum)
            if val == asum:
                bi2 = Bsum[bi][1]
                x2, y2 = B[bi2]
                time = (x2 - x1) * ope
                if time < 0:
                    bi += 1
                    continue
                ans = min(ans, time*10)
            else:
                break
            bi += 1
    return ans

def calc_line(Asum, Bsum, A, B, ans):
    if not len(A) or not len(B):
        return ans

    # print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        x1, y1 = A[ai]
        while bi < len(B_):
            val = B_[bi]
            if val == asum:
                bi2 = Bsum[bi][1]
                x2, y2 = B[bi2]
                if x1 == x2:
                    time = y2 - y1
                else:
                    time = x2 - x1
                if time < 0:
                    bi += 1
                    continue
                ans = min(ans, time*5)
            else:
                break
            bi += 1
    return ans

def run():
    U, D, R, L = [],[],[],[]
    N = int(sysread())
    for i in range(N):
        x,y,u = input().split()
        #print(x, y, u)
        x,y = int(x), int(y)
        if u == 'U':
            U.append((x,y))
        elif u == 'D':
            D.append((x,y))
        elif u == 'R':
            R.append((x,y))
        elif u == 'L':
            L.append((x,y))

    #print(U, D, R, L)
    ans = INF
    # U vs R
    Usum = sorted([(x+y, i) for i, (x,y) in enumerate(U)])
    Rsum = sorted([(x+y, i) for i, (x,y) in enumerate(R)])
    ans = calc(Usum, Rsum, U, R, ans, ope=-1)

    # D vs L
    Dsum = sorted([(x + y, i) for i, (x, y) in enumerate(D)])
    Lsum = sorted([(x + y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Dsum, Lsum, D, L, ans, ope=1)

    # U vs L
    Usub = sorted([(x - y, i) for i, (x, y) in enumerate(U)])
    Lsub = sorted([(x - y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Usub, Lsub, U, L, ans, ope=1)

    # D vs R
    Dsub = sorted([(x - y, i) for i, (x, y) in enumerate(D)])
    Rsub = sorted([(x - y, i) for i, (x, y) in enumerate(R)])
    ans = calc(Dsub, Rsub, D, R, ans, ope=-1)

    # U vs D
    UU = sorted([(x, i) for i, (x,y) in enumerate(U)])
    DD = sorted([(x, i) for i, (x, y) in enumerate(D)])
    ans = calc_line(UU, DD, U, D, ans)

    # R vs L
    RR = sorted([(y, i) for i, (x, y) in enumerate(R)])
    LL = sorted([(y, i) for i, (x, y) in enumerate(L)])
    ans = calc_line(RR, LL, R, L, ans)

    if ans == INF:
        print('SAFE')
    else:
        print(int(ans))



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
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50

def calc(Asum, Bsum, A, B, ans, ope = 1):
    if not len(A) or not len(B):
        return ans

    #print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        while bi < len(B_):
            val = B_[bi]
            #print(bi, val, asum)
            if val == asum:
                bi2 = Bsum[bi][1]
                x1, y1 = A[ai]
                x2, y2 = B[bi2]
                time = (x2 - x1) * ope
                if time < 0:
                    bi += 1
                    continue
                ans = min(ans, time*10)
            else:
                break
            bi += 1
    return ans

def calc_line(Asum, Bsum, A, B, ans):
    if not len(A) or not len(B):
        return ans

    # print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        while bi < len(B_):
            val = B_[bi]
            if val == asum:
                bi2 = Bsum[bi][1]
                x1, y1 = A[ai]
                x2, y2 = B[bi2]
                if x1 == x2:
                    time = y2 - y1
                else:
                    time = x2 - x1
                if time < 0:
                    bi += 1
                    continue
                ans = min(ans, time*5)
            else:
                break
            bi += 1
    return ans

def run():
    U, D, R, L = [],[],[],[]
    N = int(sysread())
    for i in range(N):
        x,y,u = input().split()
        #print(x, y, u)
        x,y = int(x), int(y)
        if u == 'U':
            U.append((x,y))
        elif u == 'D':
            D.append((x,y))
        elif u == 'R':
            R.append((x,y))
        elif u == 'L':
            L.append((x,y))

    #print(U, D, R, L)
    ans = INF
    # U vs R
    Usum = sorted([(x+y, i) for i, (x,y) in enumerate(U)])
    Rsum = sorted([(x+y, i) for i, (x,y) in enumerate(R)])
    ans = calc(Usum, Rsum, U, R, ans, ope=-1)

    # D vs L
    Dsum = sorted([(x + y, i) for i, (x, y) in enumerate(D)])
    Lsum = sorted([(x + y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Dsum, Lsum, D, L, ans, ope=1)

    # U vs L
    Usub = sorted([(x - y, i) for i, (x, y) in enumerate(U)])
    Lsub = sorted([(x - y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Usub, Lsub, U, L, ans, ope=1)

    # D vs R
    Dsub = sorted([(x - y, i) for i, (x, y) in enumerate(D)])
    Rsub = sorted([(x - y, i) for i, (x, y) in enumerate(R)])
    ans = calc(Dsub, Rsub, D, R, ans, ope=-1)

    # U vs D
    UU = sorted([(x, i) for i, (x,y) in enumerate(U)])
    DD = sorted([(x, i) for i, (x, y) in enumerate(D)])
    ans = calc_line(UU, DD, U, D, ans)

    # R vs L
    RR = sorted([(y, i) for i, (x, y) in enumerate(R)])
    LL = sorted([(y, i) for i, (x, y) in enumerate(L)])
    ans = calc_line(RR, LL, R, L, ans)

    if ans == INF:
        print('SAFE')
    else:
        print(int(ans))



if __name__ == "__main__":
    run()