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: Runtime Error

Solution code:
def main():  
  import sys
  input = sys.stdin.readline
  from bisect import bisect

  XU = [[] for i in range(2*10**5+1)]
  XD = [[] for i in range(2*10**5+1)]
  YL = [[] for i in range(2*10**5+1)]
  YR = [[] for i in range(2*10**5+1)]
  xu = []
  xd = []
  yls = [[] for i in range(4*10**5+1)]
  yrs = [[] for i in range(4*10**5+1)]
  ylsa = [[] for i in range(4*10**5+1)]
  yrsa = [[] for i in range(4*10**5+1)]

  n = int(input())
  ans = float('inf')

  for i in range(n):
    x,y,u = input().split()
    x = int(x); y = int(y)
    if u == 'U':
      XU[x].append(y)
      xu.append((x,y))
    if u == 'D':
      XD[x].append(y)
      xd.append((x,y))
    if u == 'L':
      YL[y].append(x)
      yls[x+y].append(x)
      ylsa[x-y+2*10**5].append(x)
    if u == 'R':
      YR[y].append(x)
      yrs[x+y].append(x)
      yrsa[x-y+2*10**5].append(x)

  for x,y in xu: #上
    if yrs[x+y] != []:
      yrs[x+y].sort()
      ind = bisect(yrs[x+y],x)
      if ind > 0:
        ans = min(ans,abs(x-yrs[x+y][ind-1])*10)
    if ylsa[x-y+2*10**5] != []:
      ylsa[x-y+2*10**5].append(10**9)
      ylsa[x-y+2*10**5].sort()
      ind = bisect(ylsa[x-y+2*10**5],x)
      if ylsa[x-y+2*10**5][ind] != 10**9:
        ans = min(ans,abs(ylsa[x-y+2*10**5][ind]-x)*10)

  for x,y in xd: #下
    if yls[x+y] != []:
      yls[x+y].append(10**9)
      yls[x+y].sort()
      ind = bisect(yls[x+y],x)
      if yls[x+y][ind] != 10**9:
        ans = min(ans,abs(x-yls[x+y][ind])*10)
    if yrsa[x-y+2*10**5] != []:
      yrsa[x-y+2*10**5].sort()
      ind = bisect(yrsa[x-y+2*10**5],x)
      if ind != 0:
        ans = min(ans,abs(yrsa[x-y+2*10**5][ind]-x)*10)

  for i in range(2*10**5+1):
    if XU[i] != [] and XD[i] != []:
      XU[i].append(10**9)
      XU[i].sort()
      for j in XD[i]:
        ind = bisect(XU[i],j)
        if ind > 0:
          chk = min(abs(XU[i][ind]-j),abs(XU[i][ind-1]-j))
          ans = min(ans,5*chk)
    if YL[i] != [] and YR[i] != []:
      YR[i].append(10**9)
      YR[i].sort()
      for j in YL[i]:
        ind = bisect(YR[i],j)
        if ind > 0:
          chk = min(abs(YR[i][ind]-j),abs(YR[i][ind-1]-j))
          ans = min(ans,5*chk)

  if ans == float('inf'):
    print('SAFE')
  else:
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from bisect import bisect,bisect_left
N = int(input())
XYU = [input().split() for _ in range(N)]
for i in range(N):
    XYU[i][0] = int(XYU[i][0])
    XYU[i][1] = int(XYU[i][1])
dp = defaultdict(lambda :defaultdict(list))
dn = defaultdict(lambda :defaultdict(list))
d1 = defaultdict(lambda :defaultdict(list))
d2 = defaultdict(lambda :defaultdict(list))

for i in range(N):
    x,y,u = XYU[i]
    dp[u][x+y].append(x)
    dn[u][x-y].append(x)
    d1[u][x].append(y)
    d2[u][y].append(x)

for u in ['U','R','D','L']:
    for z in dp[u]:
        dp[u][z].sort()
    for z in dn[u]:
        dn[u][z].sort()
    for z in d1[u]:
        d1[u][z].sort()
    for z in d2[u]:
        d2[u][z].sort()

ans = float('inf')
for i in range(N):
    x,y,u = XYU[i]
    if u=='U':
        j = bisect_left(dp['R'][x+y],x)-1
        if j>=0:
            ans = min(ans,10*(x-dp['R'][x+y][j]))
        j = bisect(dn['L'][x-y],x)
        if j<len(dn['L'][x-y]):
            ans = min(ans,10*(dn['L'][x-y][j]-x))
        j = bisect(d1['D'][x],y)
        if j<len(d1['D'][x]):
            ans = min(ans,5*(d1['D'][x][j]-y))

    elif u=='D':
        j = bisect_left(dn['R'][x-y],x)-1
        if j>=0:
            ans = min(ans,10*(x-dn['R'][x-y][j]))
        j = bisect(dp['L'][x+y],x)
        if j<len(dp['L'][x+y]):
            ans = min(ans,10*(dp['L'][x+y][j]-x))
        j = bisect_left(d1['U'][x],y)-1
        if j>=0:
            ans = min(ans,5*(y-d1['U'][x][j]))
    elif u=='R':
        j = bisect(dp['U'][x+y],x)
        if j<len(dp['U'][x+y]):
            ans = min(ans,10*(dp['U'][x+y][j]-x))
        j = bisect(dn['D'][x-y],x)
        if j<len(dn['D'][x-y]):
            ans = min(ans,10*(dn['D'][x-y][j]-x))
        j = bisect(d2['L'][y],x)
        if j<len(d2['L'][y]):
            ans = min(ans,5*(d2['L'][y][j]-x))
            
    elif u=='L':
        j = bisect_left(dp['D'][x+y],x)-1
        if j>=0:
            ans = min(ans,10*(x-dp['D'][x+y][j]))
        j = bisect_left(dn['U'][x-y],x)-1
        if j>=0:
            ans = min(ans,10(x-dp['U'][x-y][j]))
        j = bisect_left(d2[y]['R'],x)-1
        if j>=0:
            ans = min(ans,5*(x-d2[y]['R'][j]))

if ans==float('inf'):
    ans = 'SAFE'
else:
    print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
Lu = []
Lr = []
Ld = []
Ll = []

a = 400000

for i in range(n):
    t = list(map(str,input().split()))
    if t[2] == 'U':
        Lu.append(t)
    elif t[2] == 'R':
        Lr.append(t)
    elif t[2] == 'D':
        Ld.append(t)
    elif t[2] == 'L':
        Ll.append(t)
#print(Lu,Lr,Ld,Ll)

def check(L1,L2,a):
    if (L1[0][2] == 'U' or L1[0][2] == 'D') and (L2[0][2] == 'U' or L2[0][2] == 'D'):
        for i in range(len(L1)):
            for j in range(len(L2)):
                if L1[i][0] == L2[i][0]:
                    if (L1[i][1] < L2[i][1] and L1[i][2] == 'U') or (L1[i][1] > L2[i][1] and L1[i][2] == 'D'):
                        t = abs(int(L1[i][1])-int(L2[i][1]))//2
                        if a > t:
                            a = t
    elif (L1[0][2] == 'L' or L1[0][2] == 'R') and (L2[0][2] == 'L' or L2[0][2] == 'R'):
        for i in range(len(L1)):
            for j in range(len(L2)):
                if L1[i][1] == L2[i][1]:
                    if (L1[i][0] < L2[i][0] and L1[i][2] == 'R') or (L1[i][0] > L2[i][0] and L1[i][2] == 'L'):
                        t = abs(int(L1[i][0])-int(L2[i][0]))//2
                        if a > t:
                            a = t
    else:
        for i in range(len(L1)):
            for j in range(len(L2)):
                if abs(int(L1[i][0])-int(L2[i][0])) == abs(int(L1[i][1])-int(L2[i][1])):
                    t = abs(int(L1[i][0])-int(L2[i][0]))

                    if L1[i][2] == 'U' and ((L2[i][2] == 'R' and L2[i][0] < L1[i][0]) or (L2[i][2] == 'L' and L2[i][0] > L1[i][0])):
                        if a > t:
                            a = t
                    elif L1[i][2] == 'D' and ((L2[i][2] == 'R' and L2[i][0] < L1[i][0]) or (L2[i][2] == 'L' and L2[i][0] > L1[i][0])):
                        if a > t:
                            a = t
                    elif L1[i][2] == 'R' and ((L2[i][2] == 'U' and L2[i][1] < L1[i][1]) or (L2[i][2] == 'D' and L2[i][1] > L1[i][1])):
                        if a > t:
                            a = t
                    elif L1[i][2] == 'L' and ((L2[i][2] == 'U' and L2[i][1] > L1[i][1]) or (L2[i][2] == 'D' and L2[i][1] < L1[i][1])):
                        if a > t:
                            a = t
    return a

a = check(Lu,Lr,a)
a = check(Lu,Ld,a)
a = check(Lu,Ll,a)
a = check(Lr,Ld,a)
a = check(Lr,Ll,a)
a = check(Ld,Ll,a)

if a < 400000:
    print(a*10)
else:
    print('SAFE')

Submission status: Runtime Error

Solution code:
from collections import deque, Counter, defaultdict
from itertools import chain, combinations
import json
# import numpy as np
import bisect
import sys
import math
import bisect
from functools import lru_cache
import itertools

sys.setrecursionlimit(10 ** 8)

M = 10 ** 9 + 7
INF = 10 ** 17


def main():
    N = int(input())
    XYU = [
        [a for a in input().split()]
        for _ in range(N)
    ]

    # N, K = [int(a) for a in input().split()]
    # A = [int(a) for a in input().split()]
    # T1, T2, T3 = [int(a) for a in input().split()]

    up = []
    down = []
    right = []
    left = []
    for xi, yi, ui in XYU:
        if ui == 'U':
            up.append((int(xi), int(yi)))
            continue
        if ui == 'D':
            down.append((int(xi), int(yi)))
            continue
        if ui == 'R':
            right.append((int(xi), int(yi)))
            continue
        if ui == 'L':
            left.append((int(xi), int(yi)))
            continue

    def a():
        conflict = 10 ** 50
        xtable = {}
        for xi, yi in down:
            if xi not in xtable:
                xtable[xi] = []
            ind = bisect.bisect_left(xtable[xi], yi)
            xtable[xi].insert(ind, yi)
        for xi, yi in up:
            if xi in xtable:
                ind = bisect.bisect_left(xtable[xi], yi)
                if ind != len(xtable[xi]):
                    conflict = min(conflict, (xtable[xi][ind] - yi) * 5)
        ytable = {}
        for xi, yi in left:
            if yi not in ytable:
                ytable[yi] = []
            ind = bisect.bisect_left(ytable[yi], xi)
            ytable[yi].insert(ind, xi)
        for xi, yi in right:
            if yi in ytable:
                ind = bisect.bisect_left(ytable[yi], xi)
                if ind != len(ytable[yi]):
                    conflict = min(conflict, (ytable[yi][ind] - xi) * 5)
        return conflict

    left_l1 = {}
    left_l2 = {}
    for xi, yi in left:
        v1 = yi - xi
        if v1 not in left_l1:
            left_l1[v1] = []
        ind = bisect.bisect_left(left_l1[v1], xi)
        left_l1[v1].insert(ind, xi)

        v2 = xi + yi
        if v2 not in left_l2:
            left_l2[v2] = []
        ind = bisect.bisect_left(left_l2[v2], xi)
        left_l2[v2].insert(ind, xi)

    right_l1 = {}
    right_l2 = {}
    for xi, yi in right:
        v1 = yi - xi
        if v1 not in right_l1:
            right_l1[v1] = []
        ind = bisect.bisect_left(right_l1[v1], xi)
        right_l1[v1].insert(ind, xi)

        v2 = xi + yi
        if v2 not in right_l2:
            right_l2[v2] = []
        ind = bisect.bisect_left(right_l2[v2], xi)
        right_l2[v2].insert(ind, xi)

    conflict = a()

    for xi, yi in up:
        v1 = yi - xi
        v2 = xi + yi
        if v1 in left_l1:
            l = left_l1[v1]
            ind = bisect.bisect_left(l, xi)
            if ind != len(l):
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
        if v2 in right_l2:
            l = right_l2[v2]
            ind = bisect.bisect_right(l, xi)
            if ind != 0:
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
    for xi, yi in down:
        v1 = yi - xi
        v2 = xi + yi
        if v1 in right_l1:
            l = right_l1[v1]
            ind = bisect.bisect_right(l, xi)
            if ind != 0:
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
        if v2 in left_l2:
            l = left_l2[v2]
            ind = bisect.bisect_left(l, xi)
            if ind != len(l):
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
    if conflict == 10**50:
        print('SAFE')
        return
    print(conflict)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import bisect_right
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
#import numpy as np
INF = float("inf")
#d = defaultdict(int)
#d = defaultdict(list)
N = int(input())
M = 4*10**5
num1 = [[] for _ in range(M+1)]
num2 = [[] for _ in range(M+1)]
num3 = [[] for _ in range(2*10**5+1)]
num4 = [[] for _ in range(2*10**5+1)]
for i in range(N):
    x,y,sss = input().split()
    x = int(x)
    y = int(y)
    num1[x+y].append([x,sss])
    num2[x-y+2*10**5].append([x,sss])
    num3[x].append([y,sss])
    num4[y].append([x,sss])
flag = 0
MIN = 10**25
for i in range(4*10**5):
    n = len(num1[i])
    if n >= 2:
        li = num1[i]
        ue = []
        migi = []
        for j in range(n):
            xx,ar = li[j]
            if ar == "U" or ar == "D":
                ue.append(xx)
            else:
                migi.append(xx)
        un = len(ue)
        mn = len(migi)
        if un != 0 and mn != 0:
            flag = 1
            vMIN = 10**26
            for uu in range(un):
                for mm in range(mn):
                    vMIN = min(vMIN,abs(ue[uu]-migi[mm]))
            MIN = min(MIN,vMIN)
    n2 = len(num2[i])
    if n2 >= 2:
        li2 = num2[i]
        ue2 = []
        migi2 = []
        for j2 in range(n2):
            xx2,ar2 = li[j2]
            if ar2 == "U" or ar2 == "D":
                ue2.append(xx2)
            else:
                migi2.append(xx2)
        un2 = len(ue2)
        mn2 = len(migi2)
        if un2 != 0 and mn2 != 0:
            flag = 1
            vMIN2 = 10**26
            for uu2 in range(un2):
                for mm2 in range(mn2):
                    vMIN2 = min(vMIN2,abs(ue2[uu2]-migi2[mm2]))
            MIN = min(MIN,vMIN2)
    if i < 2*10**5:
        n3 = len(num3[i])
        if n3 >= 2:
            li3 = num3[i]
            uemax = -1
            shitamin = 10**10
            for j3 in range(n3):
                xx3,ar3 = li3[j3]

                if ar3 == "U" :
                    uemax = max(uemax,xx3)
                elif ar3 == "D":
                    shitamin = min(shitamin,xx3)
            if uemax != -1 and shitamin != 10**10:
                flag = 1
                vmin3 = shitamin-uemax
                MIN = min(MIN,vmin3)
        n4 = len(num4[i])
        if n4 >= 2:
            li4 = num4[i]
            uemax1 = -1
            shitamin1 = 10**10
            for j4 in range(n4):
                xx4,ar4 = li4[j4]
                if ar4 == "R" :
                    uemax1 = max(uemax1,xx4)
                elif ar3 == "L":
                    shitamin1 = min(shitamin1,xx4)
            if uemax1 != -1 and shitamin1 != 10**10:
                flag = 1
                vmin4 = shitamin1-uemax1
                MIN = min(MIN,vmin4)
    
if flag == 0:
    print("SAFE")
else:
    print(MIN*10)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from bisect import bisect

XU = [[] for i in range(2*10**5+1)]
XD = [[] for i in range(2*10**5+1)]
YL = [[] for i in range(2*10**5+1)]
YR = [[] for i in range(2*10**5+1)]
xu = []
xd = []
yls = [[] for i in range(4*10**5+1)]
yrs = [[] for i in range(4*10**5+1)]
ylsa = [[] for i in range(4*10**5+1)]
yrsa = [[] for i in range(4*10**5+1)]

n = int(input())
ans = float('inf')

for i in range(n):
  x,y,u = input().split()
  x = int(x); y = int(y)
  if u == 'U':
    XU[x].append(y)
    xu.append((x,y))
  if u == 'D':
    XD[x].append(y)
    xd.append((x,y))
  if u == 'L':
    YL[y].append(x)
    yls[x+y].append(x)
    ylsa[x-y+2*10**5].append(x)
  if u == 'R':
    YR[y].append(x)
    yrs[x+y].append(x)
    yrsa[x-y+2*10**5].append(x)
    
for i in range(2*10**5+1):
  if XU[i] != [] and XD[i] != []:
    XU[i].append(10**9)
    XU[i].sort()
    for j in XD[i]:
      ind = bisect(XU[i],j)
      if ind > 0:
        chk = min(abs(XU[i][ind]-j),abs(XU[i][ind-1]-j))
        ans = min(ans,5*chk)

for x,y in xu: #上
  if yrs[x+y] != []:
    yrs[x+y].sort()
    ind = bisect(yrs[x+y],x)
    if ind > 0:
      ans = min(ans,abs(x-yrs[x+y][ind-1])*10)
  if ylsa[x-y+2*10**5] != []:
    ylsa[x-y+2*10**5].append(10**9)
    ylsa[x-y+2*10**5].sort()
    ind = bisect(ylsa[x-y+2*10**5],x)
    if ylsa[x-y+2*10**5][ind] != 10**9:
      ans = min(ans,abs(ylsa[x-y+2*10**5][ind]-x)*10)
  
for x,y in xd: #下
  if yls[x+y] != []:
    yls[x+y].append(10**9)
    yls[x+y].sort()
    ind = bisect(yls[x+y],x)
    if yls[x+y][ind] != 10**9:
      ans = min(ans,abs(x-yls[x+y][ind])*10)
  if yrsa[x-y+2*10**5] != []:
    yrsa[x-y+2*10**5].sort()
    ind = bisect(yrsa[x-y+2*10**5],x)
    if ind != 0:
      ans = min(ans,abs(yrsa[x-y+2*10**5][ind]-x)*10)

for i in range(2*10**5+1):
  if YL[i] != [] and YR[i] != []:
    YR[i].append(10**9)
    YR[i].sort()
    for j in YL[i]:
      ind = bisect(YR[i],j)
      if ind > 0:
        chk = min(abs(YR[i][ind]-j),abs(YR[i][ind-1]-j))
        ans = min(ans,5*chk)
      
if ans == float('inf'):
  print('SAFE')
else:
  print(ans)

Submission status: Runtime Error

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [list(map(str, input().split())) for _ in range(row)]
        return map(list, zip(*read_all))

#################

N = I()
X,Y,U = LIR(N,3)
X = [int(x) for x in X]
Y = [int(y) for y in Y]

d1 = defaultdict(lambda:defaultdict(list))
d2 = defaultdict(lambda:defaultdict(list))

u = defaultdict(list)
r = defaultdict(list)
d = defaultdict(list)
l = defaultdict(list)

for i in range(N):
    if U[i] == 'U':
        u[X[i]].append(Y[i])
    elif U[i] == 'D':
        d[X[i]].append(Y[i])
    elif U[i] == 'R':
        r[Y[i]].append(X[i])
    else:
        l[Y[i]].append(X[i])

for k in u.keys():
    u[k].sort()

for k in d.keys():
    d[k].sort()

for k in r.keys():
    r[k].sort()

for k in l.keys():
    l[k].sort()

for i in range(N):
    d1[U[i]][Y[i]-X[i]].append(X[i])
    d2[U[i]][Y[i]+X[i]].append(X[i])

ans = float('inf')
for i in range(N):
    if U[i] == 'U':
        p = bisect_left(d[X[i]],Y[i])
        if p <= len(d[X[i]])-1 and len(d[X[i]]):
            ans = min(ans,(d[X[i]][p]-Y[i])*5)

        p = bisect_left(d1['L'][Y[i]-X[i]],X[i])
        if p <= len(d1['L'][Y[i]-X[i]])-1 and len(d1['L'][Y[i]-X[i]]):
            ans = min(ans,(d1['L'][Y[i]-X[i]][p]-X[i])*10)  

        p = bisect_left(d2['R'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d2['R'][Y[i]+X[i]])-1 and len(d2['R'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d2['R'][Y[i]+X[i]][p-1])*10)

    elif U[i] == 'D':
        p = bisect_left(u[X[i]],Y[i])
        if 0 <= p-1 <= len(u[X[i]])-1 and len(u[X[i]]):
            ans = min(ans,(Y[i]-u[X[i]][p-1])*5)

        p = bisect_left(d1['R'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d1['R'][Y[i]-X[i]])-1 and len(d1['R'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d1['R'][Y[i]-X[i]][p-1])*10)       

        p = bisect_left(d2['L'][Y[i]+X[i]],X[i])
        if p <= len(d2['L'][Y[i]+X[i]])-1 and len(d2['L'][Y[i]+X[i]]):
            ans = min(ans,(d2['L'][Y[i]+X[i]][p]-X[i])*10)

    elif U[i] == 'R':
        p = bisect_left(l[Y[i]],X[i])
        if p <= len(l[Y[i]])-1 and len(l[Y[i]]):
            ans = min(ans,(l[Y[i]][p]-X[i])*5)

        p = bisect_left(d1['D'][Y[i]-X[i]],X[i])
        if p <= len(d1['D'][Y[i]-X[i]])-1 and len(d1['D'][Y[i]-X[i]]):
            ans = min(ans,(d1['D'][Y[i]-X[i]][p]-X[i])*10)       

        p = bisect_left(d2['U'][Y[i]+X[i]],X[i])
        if p <= len(d2['U'][Y[i]+X[i]])-1 and len(d2['U'][Y[i]+X[i]]):
            ans = min(ans,(d2['U'][Y[i]+X[i]][p]-X[i])*10)
    else:
        p = bisect_left(r[Y[i]],X[i])
        if 0 <=p-1 <= len(r[Y[i]])-1 and len(r[Y[i]]):
            ans = min(ans,(X[i]-l[Y[i]][p-1])*5)

        p = bisect_left(d2['D'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d2['D'][Y[i]-X[i]])-1 and len(d2['D'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d2['D'][Y[i]-X[i]][p-1])*10)       

        p = bisect_left(d1['U'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d1['U'][Y[i]+X[i]])-1 and len(d1['U'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d1['U'][Y[i]+X[i]][p-1])*10)


if ans == float('inf'):
    print('SAFE')
else:
    print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from bisect import bisect

XU = [[] for i in range(2*10**5+1)]
XD = [[] for i in range(2*10**5+1)]
YL = [[] for i in range(2*10**5+1)]
YR = [[] for i in range(2*10**5+1)]
xu = []
xd = []
yls = [[] for i in range(4*10**5+1)]
yrs = [[] for i in range(4*10**5+1)]
ylsa = [[] for i in range(4*10**5+1)]
yrsa = [[] for i in range(4*10**5+1)]

n = int(input())
ans = float('inf')

for i in range(n):
  x,y,u = input().split()
  x = int(x); y = int(y)
  if u == 'U':
    XU[x].append(y)
    xu.append((x,y))
  if u == 'D':
    XD[x].append(y)
    xd.append((x,y))
  if u == 'L':
    YL[y].append(x)
    yls[x+y].append(x)
    ylsa[x-y+2*10**5].append(x)
  if u == 'R':
    YR[y].append(x)
    yrs[x+y].append(x)
    yrsa[x-y+2*10**5].append(x)
    
for i in range(2*10**5+1):
  if XU[i] != [] and XD[i] != []:
    XU[i].append(10**9)
    XU[i].sort()
    for j in XD[i]:
      ind = bisect(XU[i],j)
      if ind > 0:
        chk = min(abs(XU[i][ind]-j),abs(XU[i][ind-1]-j))
        ans = min(ans,10*chk)

for x,y in xu: #上
  if yrs[x+y] != []:
    yrs[x+y].sort()
    ind = bisect(yrs[x+y],x)
    if ind > 0:
      ans = min(ans,abs(x-yrs[x+y][ind-1])*10)
  if ylsa[x-y+2*10**5] != []:
    ylsa[x-y+2*10**5].append(10**9)
    ylsa[x-y+2*10**5].sort()
    ind = bisect(ylsa[x-y+2*10**5],x)
    if ylsa[x-y+2*10**5][ind] != 10**9:
      ans = min(ans,abs(ylsa[x-y+2*10**5][ind]-x)*10)
  
for x,y in xd: #下
  if yls[x+y] != []:
    yls[x+y].append(10**9)
    yls[x+y].sort()
    ind = bisect(yls[x+y],x)
    if yls[x+y][ind] != 10**9:
      ans = min(ans,abs(x-yls[x+y][ind])*10)
  if yrsa[x-y+2*10**5] != []:
    yrsa[x-y+2*10**5].sort()
    ind = bisect(yrsa[x-y+2*10**5],x)
    if ind != 0:
      ans = min(ans,abs(yrsa[x-y+2*10**5][ind]-x)*10)

for i in range(2*10**5+1):
  if YL[i] != [] and YR[i] != []:
    YR[i].append(10**9)
    YR[i].sort()
    for j in YL[i]:
      ind = bisect(YR[i],j)
      if ind > 0:
        chk = min(abs(YR[i][ind]-j),abs(YR[i][ind-1]-j))
        ans = min(ans,10*chk)
      
if ans == float('inf'):
  print('SAFE')
else:
  print(ans)

Submission status: Runtime Error

Solution code:
import copy
f = open("/Users/naoki/Documents/Atcoder/input.txt")

N = int(f.readline())
XYUs = [list(map(str,f.readline().split())) for _ in range(N)]

up_slopes = [[] for _ in range(400005)]
down_slopes = [[] for _ in range(400005)]
xs = [[] for _ in range(200005)]
ys = [[] for _ in range(200005)]



for XYU in XYUs:
    #y切片
    up_slopes[int(XYU[1])-int(XYU[0])+200000].append([int(XYU[0]),XYU[2]])
    down_slopes[int(XYU[1])+int(XYU[0])].append([int(XYU[0]),XYU[2]])
    xs[int(XYU[0])].append([int(XYU[1]),XYU[2]])
    ys[int(XYU[1])].append([int(XYU[0]),XYU[2]])
    
min_val = int(1e+100)
for up_slope in up_slopes:
    U_posi = -1
    R_posi = -1
    incidents = copy.deepcopy(up_slope)
    incidents = sorted(incidents)
    for incident in up_slope:
        if incident[1] == "U":
            U_posi = incident[0]
        elif incident[1] == "R":
            R_posi = incident[0]
        elif incident[1] == "D" and R_posi != -1:
            accident = incident[0]-R_posi
            if min_val > accident:
                min_val = accident
        elif incident[1] == "L" and U_posi != -1:
            accident = incident[0]-U_posi
            if min_val > accident*10:
                min_val = accident*10

for down_slope in down_slopes:
    D_posi = -1
    R_posi = -1
    incidents = copy.deepcopy(down_slope)
    incidents = sorted(incidents)
    for incident in incidents:
        if incident[1] == "D":
            D_posi = incident[0]
        elif incident[1] == "R":
            R_posi = incident[0]
        elif incident[1] == "U" and R_posi != -1:
            accident = incident[0]-R_posi
            if min_val > accident*10:
                min_val = accident*10
        elif incident[1] == "L" and D_posi != -1:
            accident = incident[0]-D_posi
            if min_val > accident:
                min_val = accident


for x in xs:
    U_posi = -1
    incidents = copy.deepcopy(x)
    incidents = sorted(incidents)
    for incident in incidents:
        if incident[1] == "U":
            U_posi = incident[0]
        elif incident[1] == "D" and U_posi!=-1:
            if min_val > 10*(incident[0]-U_posi)/2:
                min_val = 10*(incident[0]-U_posi)/2
            
for y in ys:
    R_posi = -1
    incidents = copy.deepcopy(y)
    incidents = sorted(incidents)
    for incident in incidents:
        if incident[1] == "R":
            R_posi = incident[0]
        elif incident[1] == "L" and R_posi!=-1:
            if min_val > 10*(incident[0]-R_posi)/2:
                min_val = 10*(incident[0]-R_posi)/2
if min_val < 3000000:
    print(int(min_val))
else:
    print("SAFE")

Submission status: Runtime Error

Solution code:
import bisect

n = int(input())
a = []
for _ in range(n):
    b = input().split()
    b[0] = int(b[0])
    b[1] = int(b[1])
    b.append(b[0] + b[1])
    b.append(b[0] - b[1])
    a.append(b)
ans = 0
high = []
low = []
a.sort(key = lambda x: x[0])
if a[0][2] == "U":
    high.append(a[0][1])
if a[0][2] == "D":
    low.append(a[0][1])
for i in range(n - 1):
    if a[i][0] == a[i + 1][0]:
        if a[i + 1][2] == "U":
            high.append(a[i + 1][1])
        elif a[i + 1][2] == "D":
            low.append(a[i + 1][1])
    if a[i][0] != a[i + 1][0] or i == n-2:
        if high and low:
            mi = min(high)
            ma = max(low)
            if mi < ma:
                high.sort()
                low.sort()
                for j in range(len(high)):
                    if high[i] > ma:
                        break
                    index = bisect.bisect(low, high[i])
                    ans = max(ans, (low[index] - high[i]) * 5)
        high = []
        low = []

high = []
low = []
a.sort(key = lambda x: x[1])
if a[0][2] == "U":
    high.append(a[0][1])
if a[0][2] == "D":
    low.append(a[0][1])
for i in range(n - 1):
    if a[i][1] == a[i + 1][1]:
        if a[i + 1][2] == "U":
            high.append(a[i + 1][0])
        elif a[i + 1][2] == "D":
            low.append(a[i + 1][0])
    if a[i][1] != a[i + 1][1] or i == n-2:
        if high and low:
            mi = min(high)
            ma = max(low)
            if mi < ma:
                high.sort()
                low.sort()
                for j in range(len(high)):
                    if high[i] > ma:
                        break
                    index = bisect.bisect(low, high[i])
                    ans = max(ans, (low[index] - high[i]) * 5)
        high = []
        low = []

vecR = []
vecL = []
vecD = []
vecU = []
a.sort(key = lambda x: x[3])
if a[0][2] == "U":
    vecU.append(a[0][0])
if a[0][2] == "D":
    vecD.append(a[0][0])
if a[0][2] == "L":
    vecL.append(a[0][0])
if a[0][2] == "R":
    vecR.append(a[0][0])
for i in range(n - 1):
    if a[i][3] == a[i + 1][3]:
        if a[i + 1][2] == "U":
            vecU.append(a[i + 1][0])
        elif a[i + 1][2] == "R":
            vecR.append(a[i + 1][0])
        elif a[i + 1][2] == "L":
            vecL.append(a[i + 1][0])
        elif a[i + 1][2] == "D":
            vecD.append(a[i + 1][0])
    if a[i][3] != a[i + 1][3] or i == n-2:
        if vecU and vecR:
            mi = min(vecR)
            ma = max(vecU)
            if mi < ma:
                vecR.sort()
                vecU.sort()
                for j in range(len(vecR)):
                    if vecR[i] > ma:
                        break
                    index = bisect.bisect(vecU, vecR[i])
                    ans = max(ans, (vecU[index] - vecR[i]) * 10)
        if vecL and vecD:
            mi = min(vecD)
            ma = max(vecL)
            if mi < ma:
                vecD.sort()
                vecL.sort()
                for j in range(len(vecD)):
                    if vecD[i] > ma:
                        break
                    index = bisect.bisect(vecL, vecD[i])
                    ans = max(ans, (vecL[index] - vecD[i]) * 10)
        vecR = []
        vecL = []
        vecD = []
        vecU = []


vecR = []
vecL = []
vecD = []
vecU = []
a.sort(key = lambda x: x[4])
if a[0][2] == "U":
    vecU.append(a[0][0])
if a[0][2] == "D":
    vecD.append(a[0][0])
if a[0][2] == "L":
    vecL.append(a[0][0])
if a[0][2] == "R":
    vecR.append(a[0][0])
for i in range(n - 1):
    if a[i][4] == a[i + 1][4]:
        if a[i + 1][2] == "U":
            vecU.append(a[i + 1][0])
        elif a[i + 1][2] == "R":
            vecR.append(a[i + 1][0])
        elif a[i + 1][2] == "L":
            vecL.append(a[i + 1][0])
        elif a[i + 1][2] == "D":
            vecD.append(a[i + 1][0])
    if a[i][4] != a[i + 1][4] or i == n-2:
        if vecD and vecR:
            mi = min(vecR)
            ma = max(vecD)
            if mi < ma:
                vecR.sort()
                vecD.sort()
                for j in range(len(vecR)):
                    if vecR[i] > ma:
                        break
                    index = bisect.bisect(vecD, vecR[i])
                    ans = max(ans, (vecD[index] - vecR[i]) * 10)
        if vecL and vecU:
            mi = min(vecU)
            ma = max(vecL)
            if mi < ma:
                vecU.sort()
                vecL.sort()
                for j in range(len(vecU)):
                    if vecU[i] > ma:
                        break
                    index = bisect.bisect(vecL, vecU[i])
                    ans = max(ans, (vecL[index] - vecU[i]) * 10)
        vecR = []
        vecL = []
        vecD = []
        vecU = []

if ans:
    print(ans)
else:
    print("SAFE")