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

Solution (Python):
n = int(input())
big = 800001
sml = 400000
pp = [[[] for _ in range(big)] for _ in range(8)]
mm = [[[] for _ in range(big)] for _ in range(4)]
for _ in range(n):
  x,y,d = input().split()
  x = int(x)
  y = int(y)
  if d == 'R':
    pp[0][+x+y].append(+y)
    pp[2][+x-y].append(-y)
    mm[0][y].append(x)
  if d == 'L':
    pp[4][-x+y].append(+y)
    pp[6][-x-y].append(-y)
    mm[1][y].append(x)
  if d == 'U':
    pp[1][+x+y].append(+x)
    pp[5][-x+y].append(-x)
    mm[2][x].append(y)
  if d == 'D':
    pp[3][+x-y].append(+x)
    pp[7][-x-y].append(-x)
    mm[3][x].append(y)
import bisect
inf = 10**10
ans = inf
def ser(lx,ly,su):
  global ans
  for xx in lx:
    b = bisect.bisect_left(ly,su-xx)
    try:
      ans = min(ans,(xx+ly[b]-su)*10)
    except:
      pass
for d in range(4):
  xd = 2*d
  yd = 2*d+1
  for sun in range(-sml,sml+1):
    if pp[xd][sun] and pp[yd][sun]:
      pp[xd][sun].sort()
      pp[yd][sun].sort()
      
      ser(pp[xd][sun],pp[yd][sun],sun)
for sun in range(0,sml+1):
  if mm[0][sun] and mm[1][sun]:
    mm[0][sun].sort()
    mm[1][sun].sort()
    for xx in mm[0][sun]:
      b = bisect.bisect_left(mm[1][sun],xx)
      try:
        ans = min(ans,(mm[1][sun][b]-xx)*5)
      except:
        pass
for sun in range(0,sml+1):
  if mm[2][sun] and mm[3][sun]:
    mm[2][sun].sort()
    mm[3][sun].sort()
    for yy in mm[2][sun]:
      b = bisect.bisect_left(mm[3][sun],yy)
      try:
        ans = min(ans,(mm[3][sun][b]-yy)*5)
      except:
        pass

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

Solution (Python):
n = int(input())
nmx = 200000
sml = 2*nmx
big = 4*nmx
pp = [[[] for _ in range(big+1)] for _ in range(8)]
mm = [[[] for _ in range(nmx+1)] for _ in range(4)]
for _ in range(n):
  x,y,d = input().split()
  x = int(x)
  y = int(y)
  if d == 'R':
    pp[0][+x+y].append(+y)
    pp[2][+x-y].append(-y)
    mm[0][y].append(x)
  if d == 'L':
    pp[4][-x+y].append(+y)
    pp[6][-x-y].append(-y)
    mm[1][y].append(x)
  if d == 'U':
    pp[1][+x+y].append(+x)
    pp[5][-x+y].append(-x)
    mm[2][x].append(y)
  if d == 'D':
    pp[3][+x-y].append(+x)
    pp[7][-x-y].append(-x)
    mm[3][x].append(y)
import bisect
inf = 10**10
ans = inf
def ser(lx,ly,su):
  global ans
  lly = len(ly)
  for xx in lx:
    b = bisect.bisect_left(ly,su-xx)
    if b != lly:
      ans = min(ans,(xx+ly[b]-su)*10)
    else:
      pass
for d in range(4):
  xd = 2*d
  yd = 2*d+1
  for sun in range(-sml,sml+1):
    if pp[xd][sun] and pp[yd][sun]:
      pp[xd][sun].sort()
      pp[yd][sun].sort()
      
      ser(pp[xd][sun],pp[yd][sun],sun)
for sun in range(0,nmx+1):
  if mm[0][sun] and mm[1][sun]:
    llm = len(mm[1][sun])
    mm[0][sun].sort()
    mm[1][sun].sort()
    for xx in mm[0][sun]:
      b = bisect.bisect_left(mm[1][sun],xx)
      if b != llm:
        ans = min(ans,(mm[1][sun][b]-xx)*5)
      else:
        pass
for sun in range(0,nmx+1):
  if mm[2][sun] and mm[3][sun]:
    llm = len(mm[3][sun])
    mm[2][sun].sort()
    mm[3][sun].sort()
    for yy in mm[2][sun]:
      b = bisect.bisect_left(mm[3][sun],yy)
      if b != llm:
        ans = min(ans,(mm[3][sun][b]-yy)*5)
      else:
        pass

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

Solution (Python):
import sys
def input():return sys.stdin.readline()[:-1]
def N(): return int(input())
def NM():return map(int,input().split())
def L():return list(NM())
n=N()
import collections
from bisect import bisect, bisect_left, bisect_right

sei=[collections.defaultdict(list) for i in range(4)]
hu=[collections.defaultdict(list) for i in range(4)]
ziku=[collections.defaultdict(list) for i in range(4)]
s={"U":0 ,"R":1,"D":2,"L":3}
for i in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    t=s[u]
    
    sei[t][x-y].append(x)
    hu[t][x+y].append(x)
    if t%2==1:
        ziku[t][y].append(x)
    else:
        ziku[t][x].append(y)
def f(l,x):
    for i in l[x].keys():
        l[x][i].sort()
f(ziku,2)
f(ziku,3)
INF=float("inf")
ans=INF
def solve(l,x):
    ans=INF
    for k,v in l[x].items():
        if k in l[x^2]:
            for j in v:
                tmp=bisect(l[x^2][k],j)
                if tmp!=len(l[x^2][k]):
                    ans=min(ans,(l[x^2][k][tmp]-j)*5)
    return ans

ans=min(ans,solve(ziku,0))
ans=min(ans,solve(ziku,1))
f(sei,2)
f(sei,3)
def solve2(l,x):
    ans=INF
    for k,v in l[x].items():
        if k in l[3-x]:
            for j in v:
                tmp=bisect(l[3-x][k],j)
                if tmp!=len(l[3-x][k]):
                    ans=min(ans,(l[3-x][k][tmp]-j)*10)
    return ans
ans=min(ans,solve2(sei,0))
ans=min(ans,solve2(sei,1))
def solve3(l,x):
    ans=INF
    for k,v in l[x].items():
        if k in l[x^1]:
            for j in v:
                tmp=bisect(l[x^1][k],j)
                if tmp!=len(l[x^1][k]):
                    ans=min(ans,(l[x^1][k][tmp]-j)*10)
    return ans
f(hu,0)
f(hu,3)
ans=min(ans,solve3(hu,1))
ans=min(ans,solve3(hu,2))
if ans==INF:
    print("SAFE")
else:
    print(ans)

Solution (Python):
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

only = [[[]for i in range(2*10**5+1)]for j in range(4)]
plus = [[[]for i in range(4*10**5+1)]for j in range(4)]
minus = [[[]for i in range(4*10**5+1)]for j in range(4)]
a = ['D','U','L','R']
for i in range(n):
    x,y,z = readstrs()
    x = int(x)
    y = int(y)
    b = a.index(z)
    if b<2:
        only[b][x].append(y)
    else:
        only[b][y].append(x)
    plus[b][x+y].append(x)
    minus[b][x-y].append(x)

def keisan(a,b,ans):
    a.sort()
    b.sort()
    k = 0
    j = 0
    while k<len(a) and j<len(b):
        if a[k]>b[j]:
            ans = min(ans,a[k]-b[j])
            j += 1
        else:
            k += 1
    return ans

for m in [0,2]:
    for i in range(2*10**5+1):
        a = only[m][i]
        b = only[m+1][i]
        if a and b:
            ans = keisan(a,b,ans)

if ans != 10**10:
    ans/=2

for p,q in [[2,1],[0,3]]:
    for i in range(4*10**5+1):
        a = minus[p][i]
        b = minus[q][i]
        if a and b:
            ans = keisan(a,b,ans)

for p,q in [[1,3],[2,0]]:
    for i in range(4*10**5+1):
        a = plus[p][i]
        b = plus[q][i]
        if a and b:
            ans = keisan(a,b,ans)

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

Solution (Python):
from collections import defaultdict
from bisect import bisect_left

INF = 10**18


def calc(data, p, q):

    ret = INF
    for k in data.keys():
        for i in range(len(data[k][p])):
            now = data[k][p][i]
            j = bisect_left(data[k][q], now)

            if j < len(data[k][q]):
                next = data[k][q][j]
                ret = min(ret, (next - now) * 10)

    return ret


def main():

    N = int(input())

    X = defaultdict(lambda: [[] for _ in range(4)])
    Y = defaultdict(lambda: [[] for _ in range(4)])
    XY_plus = defaultdict(lambda: [[] for _ in range(4)])
    XY_minus = defaultdict(lambda: [[] for _ in range(4)])
    URDL = ['U', 'R', 'D', 'L']

    for i in range(N):
        x, y, u = input().split()
        x, y = int(x), int(y)
        u = URDL.index(u)

        X[y][u].append(x)
        Y[x][u].append(y)
        XY_plus[x + y][u].append(x)
        XY_minus[x - y][u].append(x)

    for s in (X, Y, XY_plus, XY_minus):
        for k in s.keys():
            for i in range(4):
                s[k][i].sort()

    ans = INF
    ans = min(ans, calc(X, 1, 3) // 2)
    ans = min(ans, calc(Y, 0, 2) // 2)
    ans = min(ans, calc(XY_plus, 1, 0))
    ans = min(ans, calc(XY_plus, 2, 3))
    ans = min(ans, calc(XY_minus, 1, 2))
    ans = min(ans, calc(XY_minus, 0, 3))

    if ans >= 5000000:
        print('SAFE')
    else:
        print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict
N=int(input())

uddic=defaultdict(list)
lrdic=defaultdict(list)
uldic=defaultdict(list)
urdic=defaultdict(list)
dldic=defaultdict(list)
drdic=defaultdict(list)

for _ in range(N):
  XS,YS,U=input().split()
  x=int(XS)
  y=int(YS)
  if U=="U":
    uddic[x].append((y,U))
    uldic[x-y].append((x,U))
    urdic[x+y].append((x,U))
  elif U=="D":
    uddic[x].append((y,U))
    dldic[x+y].append((x,U))
    drdic[x-y].append((x,U))
  elif U=="L":
    lrdic[y].append((x,U))
    uldic[x-y].append((x,U))
    dldic[x+y].append((x,U))
  else:
    lrdic[y].append((x,U))
    urdic[x+y].append((x,U))
    drdic[x-y].append((x,U))
    
answer=float("inf")

for x in uddic:
  ylist=sorted(uddic[x])
  for i in range(len(ylist)-1):
    y1,u1=ylist[i]
    y2,u2=ylist[i+1]
    if u1=="U" and u2=="D":
      answer=min(answer,(y2-y1)*5)

for y in lrdic:
  xlist=sorted(lrdic[y])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="R" and u2=="L":
      answer=min(answer,(x2-x1)*5)


for xmy in uldic:
  xlist=sorted(uldic[xmy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="U" and u2=="L":
      answer=min(answer,(x2-x1)*10)

for xpy in urdic:
  xlist=sorted(urdic[xpy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="R" and u2=="U":
      answer=min(answer,(x2-x1)*10)

for xpy in dldic:
  xlist=sorted(dldic[xpy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="D" and u2=="L":
      answer=min(answer,(x2-x1)*10)

for xmy in drdic:
  xlist=sorted(drdic[xmy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="R" and u2=="D":
      answer=min(answer,(x2-x1)*10)
  
if answer==float("inf"):
  print("SAFE")
else:
  print(answer)

Solution (Python):
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(500000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n=int(input())
xyu=[list(input().split()) for i in range(n)]
for i in range(n):
    x,y,u=xyu[i]
    xyu[i]=[int(x),int(y),u]

ans=mod

xyu.sort(lambda x: x[1])
tate=[-1]*200001
for i in range(n):
    x,y,u=xyu[i]
    if u=="D":
        if tate[x]!=-1:
            ans=min(ans,(y-tate[x])*5)
    elif u=="U":
        tate[x]=y

xyu.sort(lambda x: x[0])
yoko=[-1]*200001
for i in range(n):
    x,y,u=xyu[i]
    if u=="L":
        if yoko[y]!=-1:
            ans=min(ans,(x-yoko[y])*5)
    elif u=="R":
        yoko[y]=x



cnt=[[] for i in range(2*200001)]
for i in range(n):
    x,y,u=xyu[i]
    cnt[x+y].append(i)

for i in range(len(cnt)):
    ul=[-1]*2
    cnt[i].sort(lambda x: xyu[x][1])
    for j in range(len(cnt[i])):
        x,y,u=xyu[cnt[i][j]]
        if u=="U":
            ul[0]=y
        elif u=="L":
            ul[1]=y
        elif u=="D" and ul[1]!=-1:
            ans=min(ans,(y-ul[1])*10)
        elif u=="R" and ul[0]!=-1:
            ans=min(ans,(y-ul[0])*10)
    
cnt=[[] for i in range(2*200001)]
for i in range(n):
    x,y,u=xyu[i]
    cnt[200000-x+y].append(i)

for i in range(len(cnt)):
    ur=[-1]*2
    cnt[i].sort(lambda x: xyu[x][1])
    for j in range(len(cnt[i])):
        x,y,u=xyu[cnt[i][j]]
        if u=="U":
            ur[0]=y
        elif u=="R":
            ur[1]=y
        elif u=="D" and ur[1]!=-1:
            ans=min(ans,(y-ur[1])*10)
        elif u=="L" and ur[0]!=-1:
            ans=min(ans,(y-ur[0])*10)

if ans!=mod:
    print(ans)
else:
    print("SAFE")

Solution (Python):
from bisect import bisect_left
M = 200001
n = int(input())
l = [None] * n
ans = 10 ** 18
for i in range(n):
    x, y, u = input().split()
    u = ('R', 'U', 'L', 'D').index(u)
    l[i] = (int(x), int(y), u)
for _ in range(4):
    l.sort(key=lambda x: x[0])
    xy = [[] for _ in range(M * 2 - 1)]
    yx = [[] for _ in range(M * 2 - 1)]
    xs = [[] for _ in range(M)]
    k = []
    for i, t in enumerate(l):
        x, y, u = t
        u %= 4
        if u == 1:
            xy[x + y].append(x)
        elif u == 3:
            yx[x - y + M].append(x)
        elif u == 2:
            xs[y].append(x)
        else:
            k.append((x, y))
        l[i] = (-y + M - 1, x, u + 1)
    for x, y in k:
        idx = bisect_left(xs[y], x)
        if idx < len(xs[y]):
            ans = min(ans, (xs[y][idx] - x) * 5)
        idx = bisect_left(xy[x + y], x)
        if idx < len(xy[x + y]):
            ans = min(ans, (xy[x + y][idx] - x) * 10)
        idx = bisect_left(yx[x - y + M], x)
        if idx < len(yx[x - y + M]):
            ans = min(ans, (yx[x - y + M][idx] - x) * 10)
if ans == 10 ** 18:
    print('SAFE')
else:
    print(ans)

Solution (Python):
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-dn['U'][x-y][j]))
        j = bisect_left(d2['R'][y],x)-1
        if j>=0:
            ans = min(ans,5*(x-d2['R'][y][j]))

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

Solution (Python):
from bisect import bisect_left
import sys
input = sys.stdin.readline
M = 200001
n = int(input())
l = [None] * n
ans = 10 ** 18
for i in range(n):
    x, y, u = input().split()
    u = ('R', 'D', 'L', 'U').index(u)
    l[i] = (int(x), int(y), u)
for _ in range(3):
    l.sort(key=lambda x: x[0])
    xy = [[] for _ in range(M * 2 - 1)]
    yx = [[] for _ in range(M * 2 - 1)]
    xs = [[] for _ in range(M)]
    k = []
    for i, t in enumerate(l):
        x, y, u = t
        u %= 4
        if u == 3:
            xy[x + y].append(x)
        elif u == 1:
            yx[x - y + M - 1].append(x)
        elif u == 2:
            xs[y].append(x)
        elif u == 0:
            k.append((x, y))
        l[i] = (y, -x + M - 1, u + 1)
    for x, y in k:
        idx = bisect_left(xs[y], x)
        if idx < len(xs[y]):
            ans = min(ans, (xs[y][idx] - x) * 5)
        idx = bisect_left(xy[x + y], x)
        if idx < len(xy[x + y]):
            ans = min(ans, (xy[x + y][idx] - x) * 10)
        idx = bisect_left(yx[x - y + M - 1], x)
        if idx < len(yx[x - y + M - 1]):
            ans = min(ans, (yx[x - y + M - 1][idx] - x) * 10)
if ans == 10 ** 18:
    print('SAFE')
else:
    print(ans)

Solution (Python):
from collections import defaultdict

dx = defaultdict(list)
dy = defaultdict(list)
dxpy = [defaultdict(list), defaultdict(list)] 
dxmy = [defaultdict(list), defaultdict(list)] 

N = int(input())
for i in range(N):
    x, y, u = input().split()
    x = int(x); y = int(y)
    
    if u == 'U':
        dx[x].append((y, u))
        dxpy[0][x+y].append((y, u))
        dxmy[0][x-y].append((y, u))
    if u == 'R':
        dy[y].append((x, u))
        dxpy[0][x+y].append((y, u))
        dxmy[1][x-y].append((y, u))
    if u == 'D':
        dx[x].append((y, u))
        dxpy[1][x+y].append((y, u))
        dxmy[1][x-y].append((y, u))
    if u == 'L':
        dy[y].append((x, u))
        dxpy[1][x+y].append((y, u))
        dxmy[0][x-y].append((y, u))


INF = 10**12
def calc1(zs, m1, m2):
    temp = INF
    pre_z = -1; pre_u = m2
    for z, u in zs:
        if pre_u == m1:
            if u == m1:
                pre_z = z
            else:
                pre_u = m2
                temp = min(temp, (z-pre_z)*10//2)
        elif u == m1:
            pre_z = z
            pre_u = m1    
    return temp

def calc2(zs, m1, m2):
    temp = INF
    pre_z = -1; pre_u = m2
    for z, u in zs:
        if pre_u == m1:
            if u == m1:
                pre_z = z
            else:
                pre_u = m2
                temp = min(temp, (z-pre_z)*10)
        elif u == m1:
            pre_z = z
            pre_u = m1    
    return temp



time = []

for x in dx:
    dx[x].sort()
    t = calc1(dx[x], 'U', 'D')
    if t < INF:
        time.append(t)


for y in dy:
    dy[y].sort()
    t = calc1(dy[y], 'R', 'L')
    if t < INF:
        time.append(t)

m12 = [['U', 'R'], ['L', 'D']]
for i in range(2):
    for xpy in dxpy[i]:
        dxpy[i][xpy].sort()
        t = calc2(dxpy[i][xpy], m12[i][0], m12[i][1])
        if t < INF:
            time.append(t)

m12 = [['U', 'L'], ['R', 'D']]
for i in range(2):
    for xmy in dxmy[i]:
        dxmy[i][xmy].sort()
        t  = calc2(dxmy[i][xmy], m12[i][0], m12[i][1])
        if t < INF:
            time.append(t)

if time:
    print(min(time))
else:
    print('SAFE')

Solution (Python):
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

only = [[[]for i in range(2*10**5+1)]for j in range(4)]
plus = [[[]for i in range(4*10**5+1)]for j in range(4)]
minus = [[[]for i in range(4*10**5+1)]for j in range(4)]
a = ['D','U','L','R']
for i in range(n):
    x,y,z = readstrs()
    x = int(x)
    y = int(y)
    b = a.index(z)
    if b<2:
        only[b][x].append(y)
    else:
        only[b][y].append(x)
    plus[b][x+y].append(x)
    minus[b][x-y].append(x)

for m in [0,2]:
    for i in range(2*10**5+1):
        a = only[m][i]
        b = only[m+1][i]
        if a and b:
            a.sort()
            b.sort()
            k = 0
            j = 0
            while k<len(a) and j<len(b):
                if a[k]>b[j]:
                    ans = min(ans,(a[k]-b[j])/2)
                    j += 1
                else:
                    k += 1

for p,q in [[2,1],[0,3]]:
    for i in range(4*10**5+1):
        a = minus[p][i]
        b = minus[q][i]
        if a and b:
            a.sort()
            b.sort()
            k = 0
            j = 0
            while k<len(a) and j<len(b):
                if a[k]>b[j]:
                    ans = min(ans,a[k]-b[j])
                    j += 1
                else:
                    k += 1

for p,q in [[1,3],[2,0]]:
    for i in range(4*10**5+1):
        a = plus[p][i]
        b = plus[q][i]
        if a and b:
            a.sort()
            b.sort()
            k = 0
            j = 0
            while k<len(a) and j<len(b):
                if a[k]>b[j]:
                    ans = min(ans,a[k]-b[j])
                    j += 1
                else:
                    k += 1

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

Solution (Python):
import collections
import heapq
def main():

    N = int(input())

    RL = collections.defaultdict(list)
    UD = collections.defaultdict(list)
    UL = collections.defaultdict(list)
    UR = collections.defaultdict(list)
    DL = collections.defaultdict(list)
    DR = collections.defaultdict(list)
    for _ in range(N):
        X, Y, U = input().split()
        X = int(X)
        Y = int(Y)
        if U == 'R':
            RL[Y].append([X, 0])
            UR[X+Y].append([X, 0])
            DR[X-Y].append([X, 0])
        elif U == 'L':
            RL[Y].append([X, 1])
            UL[X-Y].append([X, 1])
            DL[X+Y].append([X, 1])
        elif U == 'U':
            UD[X].append([Y, 0])
            UL[X-Y].append([X, 0])
            UR[X+Y].append([X, 1])
        else:
            UD[X].append([Y, 1])
            DL[X+Y].append([X, 0])
            DR[X-Y].append([X, 1])
    
    

    ans = float('inf')
    for V in [UL, UR, DL, DR]:
        for X in V:
            V[X].sort()
            for j in range(len(V[X])-1):
                if V[X][j][1] == 0 and V[X][j+1][1] == 1:
                    ans = min(ans, 10 * (V[X][j+1][0]- V[X][j][0]))
    for V in [UD, RL]:
        for X in V:
            V[X].sort()
            for j in range(len(V[X])-1):
                if V[X][j][1] == 0 and V[X][j+1][1] == 1:
                    ans = min(ans, 5 * (V[X][j+1][0]- V[X][j][0]))

    if ans == float('inf'): return "SAFE"
    return ans

if __name__ == '__main__':
    print(main())

Solution (Python):
import sys
from collections import defaultdict
import bisect

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

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    N = in_n()

    X = defaultdict(lambda: [[] for _ in range(4)])
    Y = defaultdict(lambda: [[] for _ in range(4)])
    XYp = defaultdict(lambda: [[] for _ in range(4)])
    XYm = defaultdict(lambda: [[] for _ in range(4)])
    urdl = ['U', 'R', 'D', 'L']

    for i in range(N):
        x, y, u = in_s().split()
        x, y = int(x), int(y)
        u = urdl.index(u)

        X[y][u].append(x)
        Y[x][u].append(y)
        XYp[x + y][u].append(x)
        XYm[x - y][u].append(x)

    INF = 10**18
    ans = INF

    for k in X.keys():
        for i in range(4):
            X[k][i].sort()

    for k in X.keys():
        for i in range(len(X[k][1])):
            now = X[k][1][i]
            j = bisect.bisect_left(X[k][3], now)

            if j < len(X[k][3]):
                next = X[k][3][j]
                ans = min(ans, (next - now) * 10 // 2)

    for k in Y.keys():
        for i in range(4):
            Y[k][i].sort()

    for k in Y.keys():
        for i in range(len(Y[k][0])):
            now = Y[k][0][i]
            j = bisect.bisect_left(Y[k][2], now)

            if j < len(Y[k][2]):
                next = Y[k][2][j]
                ans = min(ans, (next - now) * 10 // 2)

    for k in XYp.keys():
        for i in range(4):
            XYp[k][i].sort()

    for k in XYp.keys():

        
        
        
        

        for i in range(len(XYp[k][1])):
            now = XYp[k][1][i]
            j = bisect.bisect_left(XYp[k][0], now)
            if j < len(XYp[k][0]):
                next = XYp[k][0][j]
                ans = min(ans, (next - now) * 10)

        for i in range(len(XYp[k][2])):
            now = XYp[k][2][i]
            j = bisect.bisect_left(XYp[k][3], now)
            if j < len(XYp[k][3]):
                next = XYp[k][3][j]
                ans = min(ans, (next - now) * 10)

    for k in XYm.keys():
        for i in range(4):
            XYm[k][i].sort()

    for k in XYm.keys():

        
        
        
        

        for i in range(len(XYm[k][1])):
            now = XYm[k][1][i]
            j = bisect.bisect_left(XYm[k][2], now)
            if j < len(XYm[k][2]):
                next = XYm[k][2][j]
                ans = min(ans, (next - now) * 10)

        for i in range(len(XYm[k][0])):
            now = XYm[k][0][i]
            j = bisect.bisect_left(XYm[k][3], now)
            if j < len(XYm[k][3]):
                next = XYm[k][3][j]
                ans = min(ans, (next - now) * 10)

    
    
    
    

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


if __name__ == '__main__':
    main()

Solution (Python):
from bisect import bisect
from collections import defaultdict

n = int(input())
up = [defaultdict(list), defaultdict(list), defaultdict(list)]
dp = [defaultdict(list), defaultdict(list), defaultdict(list)]
lp = [defaultdict(list), defaultdict(list), defaultdict(list)]
rp = [defaultdict(list), defaultdict(list), defaultdict(list)]

for _ in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == 'U':
        up[0][x].append(y)
        up[1][x + y].append(x)
        up[2][x - y].append(x)
    elif u == 'D':
        dp[0][x].append(y)
        dp[1][x + y].append(x)
        dp[2][x - y].append(x)
    elif u == 'L':
        lp[0][y].append(x)
        lp[1][x + y].append(x)
        lp[2][x - y].append(x)
    else:
        rp[0][y].append(x)
        rp[1][x + y].append(x)
        rp[2][x - y].append(x)

INF = 10 ** 18
ans = INF

for x in up[0]:
    if x not in dp[0]:
        continue
    us = up[0][x]
    us.sort()
    for y in dp[0][x]:
        i = bisect(us, y)
        if i > 0:
            tmp = y - us[i - 1]
            ans = min(ans, tmp * 5)

for y in rp[0]:
    if y not in lp[0]:
        continue
    rs = rp[0][y]
    rs.sort()
    for x in lp[0][y]:
        i = bisect(rs, x)
        if i > 0:
            tmp = x - rs[i - 1]
            ans = min(ans, tmp * 5)

for xy in rp[1]:
    if xy not in up[1]:
        continue
    rs = rp[1][xy]
    rs.sort()
    for x in up[1][xy]:
        i = bisect(rs, x)
        if i > 0:
            tmp = x - rs[i - 1]
            ans = min(ans, tmp * 10)

for xy in dp[1]:
    if xy not in lp[1]:
        continue
    ds = dp[1][xy]
    ds.sort()
    for x in lp[1][xy]:
        i = bisect(ds, x)
        if i > 0:
            tmp = x - ds[i - 1]
            ans = min(ans, tmp * 10)

for xy in up[2]:
    if xy not in lp[2]:
        continue
    us = up[2][xy]
    us.sort()
    for x in lp[2][xy]:
        i = bisect(us, x)
        if i > 0:
            tmp = x - us[i - 1]
            ans = min(ans, tmp * 10)

for xy in rp[2]:
    if xy not in dp[2]:
        continue
    rs = rp[2][xy]
    rs.sort()
    for x in dp[2][xy]:
        i = bisect(rs, x)
        if i > 0:
            tmp = x - rs[i - 1]
            ans = min(ans, tmp * 10)

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