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:
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([x,sss])
    num3[y].append([y,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)
    n3 = len(num3[i])
    if n3 >= 2:
        li3 = num3[i]
        uemax = -1
        shitamin = 10**10
        for j3 in range(n3):
            xx3,ar3 = li[j3]

            if ar3 == "U" :
                uemax = max(uemax,xx3)
            elif ar3 == "D":
                shitamin = max(shitamax,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]
        uemax = -1
        shitamin = 10**10
        for j4 in range(n4):
            xx4,ar4 = li[j4]

            if ar4 == "R" :
                uemax = max(uemax,xx4)
            elif ar3 == "L":
                shitamin = max(shitamax,xx4)
        if uemax != -1 and shitamin != 10**10:
            flag = 1
            vmin4 = shitamin-uemax
            MIN = min(MIN,vmin4)
    
if flag == 0:
    print("SAFE")
else:
    print(MIN*10)

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:
                min_val = accident

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:
                min_val = accident
        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 > (incident[0]-U_posi)/2:
                min_val = (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 > (incident[0]-R_posi)/2:
                min_val = (incident[0]-R_posi)/2
if min_val < 300000:
    print(int(min_val*10))
else:
    print("SAFE")

Submission status: Runtime Error

Solution code:
from bisect import bisect

N = int(input())

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

R_minus = {}
L_minus = {}
R_plus = {}
L_plus = {}
for r in dic["R"]:
    if r[0]+r[1] in R_plus:
        R_plus[r[0]+r[1]].append(r[0])
    else:
        R_plus[r[0]+r[1]]=[]
        R_plus[r[0]+r[1]].append(r[0])

    if r[0]-r[1] in R_minus:
        R_minus[r[0]-r[1]].append(r[0])
    else:
        R_minus[r[0]-r[1]]=[r[0]]

for l in dic["L"]:
    if l[0]+l[1] in L_plus:
        L_plus[l[0]+l[1]].append(l[0])
    else:
        L_plus[l[0]+l[1]]=[l[0]]

    if l[0]-l[1] in R_minus:
        L_minus[l[0]-l[1]].append(l[0])
    else:
        L_minus[l[0]-l[1]]=[l[0]]


ans = 10**10

for d in dic["D"]:
    if d[0]+d[1] in L_plus:
        for i in L_plus[d[0]+d[1]]:
            ans = min(ans,abs(d[0]-i))
    if d[0]-d[1] in R_minus:
        for i in R_minus[d[0]-d[1]]:
            ans = min(ans,abs(d[0]-i))

for u in dic["U"]:
    if u[0]+u[1] in R_plus:
        for i in R_plus[d[0]-d[1]]:
            ans = min(ans,abs(d[0]-i))
    if u[0]-u[1] in L_minus:
        for i in L_minus[d[0]-d[1]]:
            ans = min(ans,abs(d[0]-i))

print(ans*10)

Submission status: Runtime Error

Solution code:
INF = float("inf")
MOD = 10 ** 9 + 7
# ----------

L = 200001
Y = [[[] for _ in range(4)] for _ in range(L)]
X = [[[] for _ in range(4)] for _ in range(L)]

N = ii()
for i in range(N):
    x, y, u = msi()
    x = int(x)
    y = int(y)
    if u == 'U':
        X[x][0].append(y)
    if u == 'D':
        X[x][2].append(y)
    if u == 'R':
        Y[y][1].append(x)
    if u == 'L':
        Y[y][3].append(x)

mn = INF
for i in range(L):
    if X[i][0] and X[i][2]:
        bat = min(X[i][2]) - max(X[i][0])
        if bat < 0:
            continue
        bat *= 5
        mn = min(mn, bat)
    if Y[i][1] and Y[i][3]:
        bat = min(Y[i][3]) - max(Y[i][1])
        if bat < 0:
            continue
        bat *= 5
        mn = min(mn, bat)
    if i > 0:
        if X[i][0] and Y[i][1]:
            mn = min(mn, i * 10)
        if X[i][2] and Y[i][3]:
            mn = min(mn, i * 10)


if mn == INF:
    print('SAFE')
else:
    print(mn)

Submission status: Runtime Error

Solution code:
from collections import deque
n = int(input())
time = 10**8
l_u = []
l_d = []
l_r = []
l_l = []
for i in range(n):
  a,b,c = input().split()
  a = int(a)
  b = int(b)
  if c=="U":
    l_u.append([a,b])
  elif c=="D":
    l_d.append([a,b])
  elif c=="R":
    l_r.append([b,a])
  else:
    l_l.append([b,a])
l_u = deque(sorted(l_u))
l_d = deque(sorted(l_d))
l_r = deque(sorted(l_r))
l_l = deque(sorted(l_l))
ma_dy = -10**7
mi_uy = 10**7
ma_rx = -10**7
mi_lx = 10**7
#####RとLについて調べる
#print(l_u,l_d)
while l_u and l_d:
  ux,uy = l_u[0]
  dx,dy = l_d[0]
  if ux<dx:
    l_u.popleft()
  elif ux>dx:
    l_d.popleft()
  else:
    ma_dy = max(dy,ma_dy)
    mi_uy = min(uy,mi_uy)
    l_u.popleft()
    l_d.popleft()
if ma_dy!=-10**7 and mi_uy != 10**7:
  time = max(0,ma_dy-mi_uy)   
while l_r and l_l:
  rx,ry = l_r[0]
  lx,ly = l_l[0]
  if ry<ly:
    l_r.popleft()
  elif ry>ly:
    l_l.popleft()
  else:
      ma_rx = max(rx,ma_rx)
      mi_lx = min(lx,ma_lx)
      l_r.popleft()
#print(ma_rx,mi_lx)
if ma_rx!=-10**7 and mi_lx!= 10**7:
  time = max(0,ma_rx-mi_lx)   
if time==10**8:
  print("Safe")
else:
  print(time*5)

Submission status: Runtime Error

Solution code:
n = int(input())
index = {
  "U":[],
  "R":[],
  "D":[],
  "L":[]
}
time = 1e9
for i in range(n):
  x,y,dist = input().split(" ")
  index[dist].append([int(x),int(y)])
for i in index["U"]:
  k = [s for s in index["D"] if s[1] > i[1] and s[0] == i[0]]
  if len(k) > 0:
    minimum = k.sorted(key = lambda x: x[1],reverse = True)[0]
    time = min(time,(minimum[1] - i[1])//2)
  k = [s for s in index["L"] if s[1] > i[1] and s[0] > i[0]]    
  l = [s for s in k if s[1]-i[1] == s[0]-i[0]]
  if len(l) > 0:
    minimum = l.sorted(key = lambda x:x[1],reverse=True)[0]
    time = min(time,(minimum[1]-i[1]))
  k = [s for s in index["R"] if s[1] > i[1] and s[0] < i[0]]    
  l = [s for s in k if s[1]-i[1] == i[0]-s[0]]
  if len(l) > 0:
    minimum = l.sorted(key = lambda x: x[1],reverse=True)[0]
    time = min(time,(minimum[1]-i[1]))
for i in index["R"]:
  k = [s for s in index["L"] if s[0] > i[0] and s[1] == i[1]]
  if len(k) > 0:
    minimum = k.sorted(key = lambda x: x[0],reverse = True)[0]
    time = min(time,(minimum[0] - i[0])//2)
  k = [s for s in index["D"] if s[1] > i[1] and s[0] > i[0]]    
  l = [s for s in k if s[1]-i[1] == s[0]-i[0]]
  if len(l) > 0:
    minimum = l.sorted(key = lambda x:x[1],reverse=True)[0]
    time = min(time,(minimum[1]-i[1]))
for i in index["L"]:
  k = [s for s in index["D"] if s[1] > i[1] and s[0] < i[0]]
  l = [s for s in k if s[1]-i[1] == i[0]-s[0]]
  if len(k) > 0:
    minimum = k.sorted(key = lambda x: x[1],reverse = True)[0]
    time = min(time,(minimum[1] - i[1]))
if time == 1e9:
  print("SAFE")
else:
  print(time*10)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

from operator import itemgetter

n = readint()

ans = 10**10

u = []
d = []
l = []
r = []
uu = [[]for i in range(2*10**5+1)]
dd = [[]for i in range(2*10**5+1)]
ll = [[]for i in range(2*10**5+1)]
rr = [[]for i in range(2*10**5+1)]
for i in range(n):
    x,y,a = readstrs()
    x = int(x)
    y = int(y)
    if a=='U':
        u.append([x,y,x+y,x-y])
        uu[x].append(y)
    elif a == 'D':
        d.append([x,y,x+y,x-y])
        dd[x].append(y)
    elif a == 'L':
        l.append([x,y,x+y,x-y])
        ll[y].append(x)
    elif a == 'R':
        r.append([x,y,x+y,x-y])
        rr[y].append(x)

for i in range(2*10**5+1):
    if uu[i] and dd[i]:
        uu[i].sort()
        dd[i].sort()
        lenu = len(uu[i])
        lend = len(dd[i])
        k = 0
        j = 0
        while k<lenu and j<lend:
            if dd[i][j]>uu[i][k]:
                ans = min(ans,(dd[i][j]-uu[i][k])/2)
                k += 1
            else:
                j += 1
    if ll[i] and rr[i]:
        ll[i].sort()
        rr[i].sort()
        lenl = len(ll[i])
        lenr = len(rr[i])
        k = 0
        j = 0
        while k<lenl and j<lenr:
            if ll[i][j]>rr[i][k]:
                ans = min(ans,(ll[i][j]-rr[i][k])/2)
                k += 1
            else:
                j += 1

uu = [[]for i in range(4*10**5+1)]
dd = [[]for i in range(4*10**5+1)]
ll = [[]for i in range(4*10**5+1)]
rr = [[]for i in range(4*10**5+1)]

for a in u:
    uu[a[3]].append(a[0])
for a in d:
    dd[a[3]].append(a[0])    
for a in l:
    ll[a[3]].append(a[0])
for a in r:
    rr[a[3]].append(a[0])

for i in range(4*10**5+1):
    if uu[i] and ll[i]:
        uu[i].sort()
        ll[i].sort()
        lenu = len(uu[i])
        lenl = len(ll[i])
        k = 0
        j = 0
        while k<lenu and j<lenl:
            if ll[i][j]>uu[i][k]:
                ans = min(ans,ll[i][j]-uu[i][k])
                k += 1
            else:
                j += 1
    if dd[i] and rr[i]:
        dd[i].sort()
        rr[i].sort()
        lend = len(dd[i])
        lenr = len(rr[i])
        k = 0
        j = 0
        while j<lend and k<lenr:
            if dd[i][j]>rr[i][k]:
                ans = min(ans,dd[i][j]-rr[i][k])
                k += 1
            else:
                j += 1

        
uu = [[]for i in range(4*10**5+1)]
dd = [[]for i in range(4*10**5+1)]
ll = [[]for i in range(4*10**5+1)]
rr = [[]for i in range(4*10**5+1)]

for a in u:
    uu[a[2]].append(a[0])
for a in d:
    dd[a[2]].append(a[0])    
for a in l:
    ll[a[2]].append(a[0])
for a in r:
    rr[a[2]].append(a[0])

for i in range(4*10**5+1):
    if uu[i] and rr[i]:
        uu[i].sort()
        rr[i].sort()
        lenu = len(uu[i])
        lenr = len(rr[i])
        k = 0
        j = 0
        while k<lenu and j<lenr:
            if rr[i][j]<uu[i][k]:
                ans = min(ans,-rr[i][j]+uu[i][k])
                j += 1
            else:
                k += 1
    if dd[i] and ll[i]:
        dd[i].sort()
        ll[i].sort()
        lend = len(dd[i])
        lenl = len(ll[i])
        k = 0
        j = 0
        while j<lend and k<lenl:
            if dd[i][j]<ll[i][k]:
                ans = min(ans,-dd[i][j]+ll[i][k])
                j += 1
            else:
                k += 1

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

Submission status: Runtime Error

Solution code:
from operator import itemgetter
N = int(input())

PP = {
  "D" : [],
  "U" : [],
  "L" : [],
  "R" : [],
}

for i in range(N):
  x,y,d = input().split()
  x,y = int(x), int(y)
  PP[d].append((x,y,x+y, y-x))
  
#print(PP)
ans = 1e10
# DvsU
PD = sorted(PP['D'])
PU = sorted(PP['U'])
j = 0
for i in range(len(PD)):
  while j < len(PU)-1 and PD[i][0] > PU[j][0]:
    j += 1
  
  if PD[i][0] == PU[j][0]:
    if PD[i][1] >= PU[j][1]:
      ans = min(ans, (PD[i][1] - PU[j][1]) * 5)
  
# L vs R
PL = sorted(PP["L"], key=itemgetter(1))
PR = sorted(PP["R"], key=itemgetter(1))
j = 0
for i in range(len(PL)):
  while j < len(PR)-1 and PL[i][1] > PR[j][1]:
    j += 1
  
  if PL[i][1] == PR[j][1]:
    if PL[i][0] >= PR[j][0]:
       ans = min(ans, (PL[i][0] - PR[j][0]) * 5)

# D vs R
# y = x + k <-> y-x = k が同一の点は当たる可能性
PD = sorted(PP['D'], key=itemgetter(3))
PR = sorted(PP['R'], key=itemgetter(3))
j = 0
for i in range(len(PD)):
  while j < len(PR)-1 and PD[i][3] > PR[j][3]:
    j += 1
  if PD[i][3] == PR[j][3]:
    if PD[i][2] >= PR[j][2]:
       ans = min(ans, abs(PD[i][2] - PR[j][2]) * 5)

# R vs U
# y = -x + k <-> y+x = k が同一の点は当たる可能性
PR = sorted(PP['R'], key=itemgetter(2))
PU = sorted(PP['U'], key=itemgetter(2))
j = 0
for i in range(len(PR)):
  while j < len(PU)-1 and PR[i][2] > PU[j][2]:
    j += 1
  if PR[i][2] == PU[j][2]:
    if PR[i][3] >= PU[j][3]:
       ans = min(ans, abs(PR[i][3] - PU[j][3]) * 5)
    
# D vs R
# U vs L
# y = x + k <-> y-x = k が同一の点は当たる可能性
PU = sorted(PP['U'], key=itemgetter(3))
PL = sorted(PP['L'], key=itemgetter(3))
j = 0
for i in range(len(PU)):
  while j < len(PL)-1 and PU[i][3] > PL[j][3]:
    j += 1
  if PU[i][3] == PL[j][3]:
    if PU[i][2] <= PL[j][2]:
       ans = min(ans, abs(PU[i][2] - PL[j][2]) * 5)

# R vs U
# L vs D
# y = -x + k <-> y+x = k が同一の点は当たる可能性
PL = sorted(PP['L'], key=itemgetter(2))
PD = sorted(PP['D'], key=itemgetter(2))
j = 0
for i in range(len(PL)):
  while j < len(PD)-1 and PL[i][2] > PD[j][2]:
    j += 1
  if PL[i][2] == PD[j][2]:
    if PL[i][3] <= PD[j][3]:
       ans = min(ans, abs(PL[i][3] - PD[j][3]) * 5)

print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
n = int(input())
time = 10**8
l_u = []
l_d = []
l_r = []
l_l = []
for i in range(n):
  a,b,c = input().split()
  a = int(a)
  b = int(b)
  if c=="U":
    l_u.append([a,b])
  elif c=="D":
    l_d.append([a,b])
  elif c=="R":
    l_r.append([b,a])
  else:
    l_l.append([b,a])
l_u = deque(sorted(l_u))
l_d = deque(sorted(l_d))
l_r = deque(sorted(l_r))
l_l = deque(sorted(l_l))
ma_dy = -10**7
mi_uy = 10**7
ma_rx = -10**7
mi_lx = 10**7
#####RとLについて調べる
#print(l_u,l_d)
while l_u and l_d:
  ux,uy = l_u[0]
  dx,dy = l_d[0]
  if ux<dx:
    l_u.popleft()
  elif ux>dx:
    l_d.popleft()
  else:
    ma_dy = max(dy,ma_dy)
    mi_uy = min(uy,mi_uy)
    l_u.popleft()
    l_d.popleft()
if ma_dy!=-10**7 and mi_uy != 10**7:
  time = max(0,ma_dy-mi_uy)   
while l_r and l_l:
  rx,ry = l_r[0]
  lx,ly = l_l[0]
  if ry<ly:
    l_r.popleft()
  elif ry>ly:
    l_l.popleft()
  else:
      ma_rx = max(rx,ma_rx)
      mi_lx = min(lx,ma_lx)
      l_r.popleft()
print(ma_rx,mi_lx)
if ma_rx!=-10**7 and mi_lx!= 10**7:
  time = max(0,ma_rx-mi_lx)   
if time==10**8:
  print("Safe")
else:
  print(time*5)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

from operator import itemgetter

n = readint()

ans = 10**10

u = []
d = []
l = []
r = []
uu = [[]for i in range(2*10**5+1)]
dd = [[]for i in range(2*10**5+1)]
ll = [[]for i in range(2*10**5+1)]
rr = [[]for i in range(2*10**5+1)]
for i in range(n):
    x,y,a = readstrs()
    x = int(x)
    y = int(y)
    if a=='U':
        u.append([x,y,x+y,x-y])
        uu[x].append(y)
    elif a == 'D':
        d.append([x,y,x+y,x-y])
        dd[x].append(y)
    elif a == 'L':
        l.append([x,y,x+y,x-y])
        ll[y].append(x)
    elif a == 'R':
        r.append([x,y,x+y,x-y])
        rr[y].append(x)

for i in range(2*10**5+1):
    if uu[i] and dd[i]:
        uu[i].sort()
        dd[i].sort()
        lenu = len(uu[i])
        lend = len(dd[i])
        k = 0
        j = 0
        while k<lenu and j<lend:
            if dd[i][j]>uu[i][k]:
                ans = min(ans,(dd[i][j]-uu[i][k])//2)
                k += 1
            else:
                j += 1
    if ll[i] and rr[i]:
        ll[i].sort()
        rr[i].sort()
        lenl = len(ll[i])
        lenr = len(rr[i])
        k = 0
        j = 0
        while k<lenl and j<lenr:
            if ll[i][j]>rr[i][k]:
                ans = min(ans,(ll[i][j]-rr[i][k])//2)
                k += 1
            else:
                j += 1

uu = [[]for i in range(4*10**5+1)]
dd = [[]for i in range(4*10**5+1)]
ll = [[]for i in range(4*10**5+1)]
rr = [[]for i in range(4*10**5+1)]

for a in u:
    uu[a[3]].append(a[0])
for a in d:
    dd[a[3]].append(a[0])    
for a in l:
    ll[a[3]].append(a[0])
for a in r:
    rr[a[3]].append(a[0])

for i in range(4*10**5+1):
    if uu[i] and ll[i]:
        uu[i].sort()
        ll[i].sort()
        lenu = len(uu[i])
        lenl = len(ll[i])
        k = 0
        j = 0
        while k<lenu and j<lenl:
            if ll[i][j]>uu[i][k]:
                ans = min(ans,ll[i][j]-uu[i][k])
                k += 1
            else:
                j += 1
    if dd[i] and rr[i]:
        dd[i].sort()
        rr[i].sort()
        lend = len(dd[i])
        lenr = len(rr[i])
        k = 0
        j = 0
        while j<lend and k<lenr:
            if dd[i][j]>rr[i][k]:
                ans = min(ans,dd[i][j]-rr[i][k])
                k += 1
            else:
                j += 1

        
uu = [[]for i in range(4*10**5+1)]
dd = [[]for i in range(4*10**5+1)]
ll = [[]for i in range(4*10**5+1)]
rr = [[]for i in range(4*10**5+1)]

for a in u:
    uu[a[2]].append(a[0])
for a in d:
    dd[a[2]].append(a[0])    
for a in l:
    ll[a[2]].append(a[0])
for a in r:
    rr[a[2]].append(a[0])

for i in range(4*10**5+1):
    if uu[i] and rr[i]:
        uu[i].sort()
        rr[i].sort()
        lenu = len(uu[i])
        lenr = len(rr[i])
        k = 0
        j = 0
        while k<lenu and j<lenr:
            if rr[i][j]<uu[i][k]:
                ans = min(ans,-rr[i][j]+uu[i][k])
                j += 1
            else:
                k += 1
    if dd[i] and ll[i]:
        dd[i].sort()
        ll[i].sort()
        lend = len(dd[i])
        lenl = len(ll[i])
        k = 0
        j = 0
        while j<lend and k<lenl:
            if dd[i][j]<ll[i][k]:
                ans = min(ans,-dd[i][j]+ll[i][k])
                j += 1
            else:
                k += 1

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

Submission status: Runtime Error

Solution code:
from bisect import bisect_left

N = int(input())
xdict = {}
ydict = {}
d1 = {}
d2 = {}
for i in range(N):
    X,Y,U = list(input().split())
    X = int(X)
    Y = int(Y)

    if U == "U" or U == "D":
        if X in xdict:
            if U in xdict[X]:
                xdict[X][U].append(Y)
            else:
                xdict[X][U] = [Y]
        else:
            xdict[X] = {U: [Y]}

    if U == "R" or U == "L":
        if Y in ydict:
            if U in ydict[Y]:
                ydict[Y][U].append(X)
            else:
                ydict[Y][U] = [X]
        else:
            ydict[Y] = {U: [X]}

    if X-Y in d1:
        if U in d1[X-Y]:
            d1[X-Y][U].append(Y)
        else:
            d1[X-Y][U] = [Y]
    else:
        d1[X-Y] = {U: [Y]}

    if X+Y in d2:
        if U in d2[X+Y]:
            d2[X+Y][U].append(Y)
        else:
            d2[X+Y][U] = [Y]
    else:
        d2[X+Y] = {U: [Y]}

flg = True
time = float('inf')

for key in xdict.keys():
    if "U" in xdict[key] and "D" in xdict[key]:
        lst = sorted(xdict[key]["D"])
        for y in xdict[key]["U"]:
            idx = bisect_left(lst,y)
            if idx != len(lst):
                flg = False
                time = min(time,(lst[idx]-y)*5)

for key in ydict.keys():
    if "R" in ydict[key] and "L" in ydict[key]:
        lst = sorted(ydict[key]["L"])
        for x in ydict[key]["R"]:
            idx = bisect_left(lst,x)
            if idx != len(lst):
                flg = False
                time = min(time,(lst[idx]-y)*5)

for key in d1.keys():
    if "R" in d1[key] and "D" in d1[key]:
        lst = sorted(d1[key]["D"])
        for y in d1[key]["R"]:
            idx = bisect_left(lst,y)
            if idx != len(lst):
                flg = False
                time = min(time,(lst[idx]-y)*10)
    if "U" in d1[key] and "L" in d1[key]:
        lst = sorted(d1[key]["L"])
        for y in d1[key]["U"]:
            idx = bisect_left(lst,y)
            if idx != len(lst):
                flg = False
                time = min(time,(lst[idx]-y)*10)
for key in d2.keys():
    if "R" in d2[key] and "U" in d2[key]:
        lst = sorted(d2[key]["R"])
        for y in d2[key]["U"]:
            idx = bisect_left(lst,y)
            if idx != len(lst):
                flg = False
                time = min(time,(lst[idx]-y)*10)
    if "D" in d2[key] and "L" in d2[key]:
        lst = sorted(d2[key]["D"])
        for y in d2[key]["L"]:
            idx = bisect_left(lst,y)
            if idx != len(lst):
                flg = False
                time = min(time,(lst[idx]-y)*10)

if flg:
    print("SAFE")
else:
    print(time)

Submission status: Runtime Error

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

N = int(input().rstrip('\n'))
ds= {'U':[],'R':[],'D':[],'L':[]}
for _ in range(N):
  X,Y,U = (x for x in input().rstrip('\n').split())
  ds[U].append([int(X),int(Y)])
hit = []
if len(ds['U'])>0:
  if len(ds['D'])>0:
    h = [[x[1],y[1]] for x in ds['U'] for y in ds['D'] if x[0]==y[0]]
    h = [y-x for x,y in h if x<y]
    if len(h)>0:
      hit.append(min(x*5 for x in h))
  if len(ds['R'])>0:
    h = [[x,y] for x in ds['U'] for y in ds['R'] if sum(x) == sum(y)]
    h = [x for x,y in h if x[0]>y[0]]
    if len(h)>0:
      hit.append(min(10*abs(x-y) for x,y in h))
  if len(ds['L'])>0:
    h = [[x,y] for x in ds['U'] for y in ds['L'] if x[0]-x[1] == y[0]-y[1]]
    h = [y[0]-x[0] for x,y in h if x[0]<y[0]]
    if len(h)>0:
      hit.append(min(10*x for x in h))
if len(ds['R'])>0:
  if len(ds['L'])>0:
    h = [[x[0],y[0]] for x in ds['R'] for y in ds['L'] if x[1] == y[1]]
    h = [y-x for x,y in h if x<y]
    if len(h)>0:
      hit.append(min(5*x for x in h))
  if len(ds['D'])>0:
    h = [[x,y] for x in ds['R'] for y in ds['D'] if x[0]-x[1] == y[0]-y[1]]
    h = [y[0]-x[0] for x,y in h if x[0]<y[0]]
    if len(h)>0:    
      hit.append(min(10*abs(x-y) for x,y in h))
if len(ds['L'])>0:
  if len(ds['D'])>0:
    h = [[x,y] for x in ds['L'] for y in ds['D'] if x[0]+x[1] == y[0]+y[1]]
    h = [x[0]-y[0] for x,y in h if x[0]>y[0]]
    if len(h)>0:
      hit.append(min(10*x for x in h))
if len(hit)==0:
  print('SAFE')
else:
  print(min(hit))

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].append(10**9)
    XU[i].sort()
    for j in XD[i]:
      ind = bisect(XU[i],j)
      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 yrsa[x-y+2*10**5][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].append(10**9)
    YR[i].sort()
    for j in YL[i]:
      ind = bisect(YR[i],j)
      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)