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):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

INF = 10**10
M = 4*10**5 + 10

N = int(input())
PUs = [[] for _ in range(M)]
PRs = [[] for _ in range(M)]
PDs = [[] for _ in range(M)]
PLs = [[] for _ in range(M)]
nUs = [[] for _ in range(M)]
nRs = [[] for _ in range(M)]
nDs = [[] for _ in range(M)]
nLs = [[] for _ in range(M)]
xUs = [[] for _ in range(M)]
xDs = [[] for _ in range(M)]
yLs = [[] for _ in range(M)]
yRs = [[] for _ in range(M)]

for _ in range(N):
    X, Y, U = input().split()
    X, Y = int(X), int(Y)
    if U == 'L':
        PLs[X+Y].append((X, U))
        nLs[X-Y].append((X, U))
        yLs[Y].append((X, U))
    elif U == 'R':
        PRs[X+Y].append((X, U))
        nRs[X-Y].append((X, U))
        yRs[Y].append((X, U))
    elif U == 'U':
        PUs[X+Y].append((X, U))
        nUs[X-Y].append((X, U))
        xUs[X].append((Y, U))
    else:  
        PDs[X+Y].append((X, U))
        nDs[X-Y].append((X, U))
        xDs[X].append((Y, U))

def func(P1s, P2s, dir1, dir2):
    dist = INF
    for z in range(M):
        Ps = sorted(P1s[z] + P2s[z])
        for i in range(len(Ps)-1):
            if Ps[i][1] == dir1 and Ps[i+1][1] == dir2:
                d = Ps[i+1][0] - Ps[i][0]
                if d < dist:
                    dist = d
    return dist

ans = INF
dists = []
dists += [func(PRs, PUs, 'R', 'U') * 2]
dists += [func(PDs, PLs, 'D', 'L') * 2]
dists += [func(nRs, nDs, 'R', 'D') * 2]
dists += [func(nUs, nLs, 'U', 'L') * 2]
dists += [func(yRs, yLs, 'R', 'L')]
dists += [func(xUs, xDs, 'U', 'D')]

ans = min(dists)
if ans == INF:
    print('SAFE')
else:
    print(ans*5)

Solution (Python):
import sys
input = sys.stdin.readline
n = int(input())
x = [[] for _ in range(200001)]
y = [[] for _ in range(200001)]
z = [[] for _ in range(800002)]
w = [[] for _ in range(800002)]
t = float("inf")
for _ in range(n):
  xi,yi,ui = map(str,input().split())
  xi = int(xi)
  yi = int(yi)
  if ui == "U":
    x[xi].append((yi,1))
    z[xi+yi].append((xi,-1))
    w[xi-yi+200001].append((xi,1))
  elif ui == "D":
    x[xi].append((yi,-1))
    z[xi+yi+400001].append((xi,1))
    w[xi-yi+600001].append((xi,-1))                       
  elif ui == "R":
    y[yi].append((xi,1))
    z[xi+yi].append((xi,1))
    w[xi-yi+600001].append((xi,1))  
  else:
    y[yi].append((xi,-1))
    z[xi+yi+400001].append((xi,-1))
    w[xi-yi+200001].append((xi,-1)) 
for xx in x:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*5 < t:
            t = (xx[i][0] - n)*5
          n = -1 
for xx in y:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*5 < t:
            t = (xx[i][0] - n)*5
          n = -1 
for xx in z:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*10 < t:
            t = (xx[i][0] - n)*10
          n = -1 
for xx in w:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*10 < t:
            t = (xx[i][0] - n)*10
          n = -1 
if t == float("inf"):
  print("SAFE")
else:
  print(t)

Solution (Python):
import sys
input=sys.stdin.readline

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

ans=10**20
ud=[[]for _ in range(200001)]
lr=[[]for _ in range(200001)]
for x,y,u in xyu:
  if u in "UD":
    ud[x].append((y,u))
  else:
    lr[y].append((x,u))
for i in range(200001):
  ud[i].sort()
  for j in range(1,len(ud[i])):
    if ud[i][j-1][1]+ud[i][j][1]=="UD":
      ans=min(ans,(ud[i][j][0]-ud[i][j-1][0])*5)
  lr[i].sort()
  for j in range(1,len(lr[i])):
    if lr[i][j-1][1]+lr[i][j][1]=="RL":
      ans=min(ans,(lr[i][j][0]-lr[i][j-1][0])*5)

rup_rd=[[]for _ in range(400001)]
rup_lu=[[]for _ in range(400001)]
lup_ld=[[]for _ in range(400001)]
lup_ru=[[]for _ in range(400001)]
for x,y,u in xyu:
  if u=="U":
    rup_lu[x-y+200000].append((x,y,u))
    lup_ru[x+y].append((x,y,u))
  if u=="D":
    rup_rd[x-y+200000].append((x,y,u))
    lup_ld[x+y].append((x,y,u))
  if u=="L":
    rup_lu[x-y+200000].append((x,y,u))
    lup_ld[x+y].append((x,y,u))
  if u=="R":
    rup_rd[x-y+200000].append((x,y,u))
    lup_ru[x+y].append((x,y,u))
for i in range(400001):
  rup_rd[i].sort()
  rup_lu[i].sort()
  lup_ld[i].sort()
  lup_ru[i].sort()
  for j in range(1,len(rup_rd[i])):
    sx,sy,su=rup_rd[i][j-1]
    tx,ty,tu=rup_rd[i][j]
    if su+tu=="RD":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
  for j in range(1,len(rup_lu[i])):
    sx,sy,su=rup_lu[i][j-1]
    tx,ty,tu=rup_lu[i][j]
    if su+tu=="UL":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
  for j in range(1,len(lup_ld[i])):
    sx,sy,su=lup_ld[i][j-1]
    tx,ty,tu=lup_ld[i][j]
    if su+tu=="DL":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
  for j in range(1,len(lup_ru[i])):
    sx,sy,su=lup_ru[i][j-1]
    tx,ty,tu=lup_ru[i][j]
    if su+tu=="RU":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
if ans==10**20:
  print("SAFE")
else:
  print(ans)

Solution (Python):
N = int(input())

A1 = []
A2=[]
A3=[]
B1 = []
B4 = []
B5 = []
C2 = []
C4 = []
C6 = []
D3 = []
D5 = []
D6 = []
for i in range(N):
  X, Y, U = input().split()
  X = int(X)
  Y = int(Y)
  U = str(U)
  if U == "R":
    A1.append((Y, X))
    A2.append((X-Y,X))
    A3.append((X+Y,X))
  elif U == "L":
    B1.append((Y,X))
    B4.append((X+Y,-X))
    B5.append((X-Y,-X))
  elif U == "D":
    C2.append((X-Y,X))
    C4.append((X+Y,-X))
    C6.append((X,Y))
  elif U == "U":
    D3.append((X+Y,X))
    D5.append((X-Y,-X))
    D6.append((X,Y))
    

ans = 10 ** 20
A1.sort()
B1.sort()
i = 0
for x1, y1 in A1:
  while i < len(B1):
    x2, y2 = B1[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*5)
      break
    else:
      i += 1
    
A2.sort()
C2.sort()
i = 0
for x1, y1 in A2:
  while i < len(C2):
    x2, y2 = C2[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
A3.sort()
D3.sort()
i = 0
for x1, y1 in A3:
  while i < len(D3):
    x2, y2 = D3[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
C4.sort()
B4.sort()
i = 0
for x1, y1 in B4:
  while i < len(C4):
    x2, y2 = C4[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
D5.sort()
B5.sort()
i = 0
for x1, y1 in B5:
  while i < len(D5):
    x2, y2 = D5[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
C6.sort()
D6.sort()
i = 0
for x1, y1 in D6:
  while i < len(C6):
    x2, y2 = C6[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*5)
      break
    else:
      i += 1

print(ans if ans < 10**20 else "SAFE")

Solution (Python):

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

from collections import defaultdict

def solve(U,R,D,L):

    def helper(U,R):
        A = defaultdict(list)
        B = defaultdict(list)
        for x,y in U:
            A[x+y].append(x)
        for x,y in R:
            B[x+y].append(x)
        m = 1000000
        for d,r in A.items():
            l = B[d]
            j = 0
            for li in l:
                while j < len(r) and li > r[j]:
                    j += 1
                if j == len(r):
                    break
                m = min2(m, r[j]-li)
        return m

    def helper2(U,D):
        A = defaultdict(list)
        B = defaultdict(list)
        for x,y in U:
            A[x].append(y)
        for x,y in D:
            B[x].append(y)
        m = 100000000
        for d,l in A.items():
            l.sort()
            r = B[d]
            r.sort()
            j = 0
            for li in l:
                while j < len(r) and li > r[j]:
                    j += 1
                if j == len(r):
                    break
                m = min2(m, r[j]-li)
        return m



    U.sort()
    R.sort()
    D.sort()
    L.sort()
    m = helper(U,R)
    A,B = [(-x,y) for x,y in U], [(-x,y) for x,y in L]
    A.reverse()
    B.reverse()
    m = min2(helper(A,B), m)
    A,B = [(x,-y) for x,y in D], [(x,-y) for x,y in R]
    m = min2(helper(A,B), m)
    A,B = [(-x,-y) for x,y in D], [(-x,-y) for x,y in L]
    A.reverse()
    B.reverse()
    m = min2(helper(A,B), m)
    m *= 10
    m = min2(helper2(U,D)*5, m)
    A,B = [(y,x) for x,y in L], [(y,x) for x,y in R]
    m = min2(helper2(B,A)*5, m)

    return m if m < 10000000 else 'SAFE'



if __name__ == '__main__':
    N = int(readline())

    t = iter(read().split())

    U,R,D,L = [],[],[],[]
    for x,y,u in zip(t,t,t):
        p = (int(x),int(y))
        u = u.decode('utf8')
        if u == 'U':
            U.append(p)
        elif u == 'R':
            R.append(p)
        elif u == 'D':
            D.append(p)
        else:
            L.append(p)

    print(solve(U,R,D,L))

Solution (Python):
n=int(input())
xyu=[list(input().split()) for _ in range(n)]
xyu=[[int(x),int(y),u] for x,y,u in xyu]
ddr={'U':0,'R':1,'D':2,'L':3}
plus={'U':{},'R':{},'D':{},'L':{}}
minus={'U':{},'R':{},'D':{},'L':{}}
drdi={'U':{},'R':{},'D':{},'L':{}}

for i in range(n):
  x,y,u=xyu[i]
  if u=='U':
    if x in drdi[u]:
      drdi[u][x].add(i)
    else:
      drdi[u][x]={i}
  if u=='D':
    if x in drdi[u]:
      drdi[u][x].add(i)
    else:
      drdi[u][x]={i}
  if u=='R':
    if y in drdi[u]:
      drdi[u][y].add(i)
    else:
      drdi[u][y]={i}
  if u=='L':
    if y in drdi[u]:
      drdi[u][y].add(i)
    else:
      drdi[u][y]={i}
  if y-x in plus[u]:
    plus[u][y-x].add(i)
  else:
    plus[u][y-x]={i}
  if y+x in minus[u]:
    minus[u][y+x].add(i)
  else:
    minus[u][y+x]={i}
inf=float('inf')
ans=inf
ukeys=set(drdi['U'].keys())
dkeys=set(drdi['D'].keys())
from bisect import bisect_left
for x in ukeys.intersection(dkeys):
  U=[xyu[i][1] for i in drdi['U'][x]]
  D=[xyu[i][1] for i in drdi['D'][x]]
  if min(U)>=max(D):continue
  D=sorted(D)
  for ui in U:
    tmp=bisect_left(D,ui)
    if tmp==len(D):continue
    ans=min(ans,10*(D[tmp]-ui)//2)

rkeys=set(drdi['R'].keys())
lkeys=set(drdi['L'].keys())
for x in rkeys.intersection(lkeys):
  R=[xyu[i][0] for i in drdi['R'][x]]
  L=[xyu[i][0] for i in drdi['L'][x]]
  if min(R)>=max(L):continue
  L=sorted(L)
  for ri in R:
    tmp=bisect_left(L,ri)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ri)//2)

ukeys=set(plus['U'].keys())
lkeys=set(plus['L'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][1] for i in plus['U'][x]]
  L=[xyu[i][1] for i in plus['L'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))

ukeys=set(plus['R'].keys())
lkeys=set(plus['D'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][0] for i in plus['R'][x]]
  L=[xyu[i][0] for i in plus['D'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))

ukeys=set(minus['U'].keys())
lkeys=set(minus['R'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][1] for i in minus['U'][x]]
  L=[xyu[i][1] for i in minus['R'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))

ukeys=set(minus['D'].keys())
lkeys=set(minus['L'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][0] for i in minus['D'][x]]
  L=[xyu[i][0] for i in minus['L'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))
if ans==inf:
  print('SAFE')
else:
  print(ans)

Solution (Python):
from collections import defaultdict
from bisect import bisect_right
N = int(input())
XYU = [None]*N
for i in range(N):
    x, y, u = input().split()
    XYU[i] = (int(x), int(y), u)
U, D = defaultdict(list), defaultdict(list)
R, L = defaultdict(list), defaultdict(list) 
Ru, Rd, Lu, Ld = defaultdict(list), defaultdict(list), defaultdict(list), defaultdict(list)
for x, y, u in XYU:
    if u == 'R':
        Ru[x+y].append(x)
        Rd[y-x].append(x)
        R[y].append(x)
    elif u == 'L':
        Lu[y-x].append(x)
        Ld[x+y].append(x)
        L[y].append(x)
    elif u == 'U':
        U[x].append(y)
    else:
        D[x].append(y)
ans = float('inf')
for x in U:
    if len(D[x]) > 0:
        D[x].sort()
        le = len(D[x])
        for y in U[x]:
            idx = bisect_right(D[x], y)
            if idx < le and ans > (D[x][idx]-y)/2:
                ans = (D[x][idx]-y)/2
for y in R:
    if len(L[y]) > 0:
        L[y].sort()
        le = len(L[y])
        for x in R[y]:
            idx = bisect_right(L[y], x)
            if idx < le and ans > (L[y][idx]-x)/2:
                ans = (L[y][idx]-x)/2
for k in Ru:
    Ru[k].sort()
for k in Lu:
    Lu[k].sort()
for k in Rd:
    Rd[k].sort()
for k in Ld:
    Ld[k].sort()
for x, y, u in XYU:
    if u == 'U':
        if len(Ru[x+y]) > 0:
            idx = bisect_right(Ru[x+y], x)-1
            if 0 <= idx < len(Ru[x+y]):
                ans = min(ans, x-Ru[x+y][idx])
        if len(Lu[y-x]) > 0:
            idx = bisect_right(Lu[y-x], x)
            if idx < len(Lu[y-x]):
                ans = min(ans, Lu[y-x][idx]-x)
    elif u == 'D':
        if len(Rd[y-x]) > 0:
            idx = bisect_right(Rd[y-x], x)-1
            if 0 <= idx < len(Rd[y-x]):
                ans = min(ans, x-Rd[y-x][idx])
        if len(Ld[x+y]) > 0:
            idx = bisect_right(Ld[x+y], x)
            if idx < len(Ld[x+y]):
                ans = min(ans, Ld[x+y][idx]-x)
if ans == float('inf'):
    print('SAFE')
else:
    print(int(ans*10))

Solution (Python):
def solve():
    N = int(input())
    from collections import defaultdict
    X, Y = defaultdict(list), defaultdict(list)
    dx, dy = defaultdict(list), defaultdict(list)
    for i in range(N):
        x, y, U = list(input().split())
        x, y = int(x), int(y)
        X[x].append((y, U))
        Y[y].append((x, U))
        dy[x+y].append((x-y, U))
        dx[x-y].append((x+y, U))
    ans = float("inf")
    for key in X.keys():
        X[key].sort()
        for i in range(1, len(X[key])):
            y1, dir1 = X[key][i-1]
            y2, dir2 = X[key][i]
            if dir1 == "U" and dir2 == "D":
                ans = min(ans, 5*y2-5*y1)
    for key in Y.keys():
        Y[key].sort()
        for i in range(1, len(Y[key])):
            y1, dir1 = Y[key][i-1]
            y2, dir2 = Y[key][i]
            if dir1 == "R" and dir2 == "L":
                ans = min(ans, 5*y2-5*y1)
    for key in dx.keys():
        dx[key].sort()
        for i in range(1, len(dx[key])):
            y1, dir1 = dx[key][i-1]
            y2, dir2 = dx[key][i]
            if (dir1 == "U" and dir2 == "L") or (dir1 == "R" and dir2 == "D"):
                ans = min(ans, 5*y2-5*y1)
    for key in dy.keys():
        dy[key].sort()
        for i in range(1, len(dy[key])):
            y1, dir1 = dy[key][i-1]
            y2, dir2 = dy[key][i]
            if (dir1 == "R" and dir2 == "U") or(dir1 == "D" and dir2 == "L"):
                ans = min(ans, 5*y2-5*y1)
    if ans == float("inf"):
        print("SAFE")
    else:
        print(ans)


if __name__ == "__main__":
    solve()

Solution (Python):
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]


inf=10**16
n=II()
xyu=[SI().split() for _ in range(n)]
dir="LRDU"
xyu=[(int(x),int(y),dir.index(u)) for x,y,u in xyu]
xyu.sort()

ans=inf

ytox=defaultdict(int)
hu=defaultdict(list)
sei=defaultdict(list)
for x,y,u in xyu:
    if u==1:
        ytox[y]=x
    if u==2:hu[x+y]=[x,y]
    if u==3:sei[x-y]=[x,y]
    if u==0:
        if y in ytox:
            ans=min(ans,(x-ytox[y])*5)
        if x+y in hu:
            ans=min(ans,abs(x-hu[x+y][0])*10)
        if x-y in sei:
            ans=min(ans,abs(x-sei[x-y][0])*10)


hu=defaultdict(list)
sei=defaultdict(list)
for x,y,u in xyu[::-1]:
    if u==3:hu[x+y]=[x,y]
    if u==2:sei[x-y]=[x,y]
    if u==1:
        if x+y in hu:
            ans=min(ans,abs(x-hu[x+y][0])*10)
        if x-y in sei:
            ans=min(ans,abs(x-sei[x-y][0])*10)

xyu.sort(key=lambda x:x[1])
ytox=defaultdict(int)
hu=defaultdict(list)
sei=defaultdict(list)
for x,y,u in xyu:
    if u==3:
        ytox[x]=y
    if u==2:
        if x in ytox:
            ans=min(ans,(y-ytox[x])*5)

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

Solution (Python):
n = int(input())
n1, n2 = 200001, 400001
s1, s2 = [[] for _ in range(n1)], [[] for _ in range(n1)]
s3, s4 = [[] for _ in range(n2)], [[] for _ in range(n2)]
for _ in range(n):
    x, y, u = input().split()
    x, y = int(x), int(y)
    a, b = x + y, x - y + 200000
    s1[x].append([y, u])
    s2[y].append([x, u])
    s3[a].append([b, u])
    s4[b].append([a, u])
ans = 100000000
for t in s1:
    if not t:
        continue
    a, b = -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "U":
            a = tt[0]
        elif tt[1] == "D":
            b = tt[0]
        if not min(a, b) == -1 and a < b:
            ans = min(ans, 5 * (b - a))
for t in s2:
    if not t:
        continue
    a, b = -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "R":
            a = tt[0]
        elif tt[1] == "L":
            b = tt[0]
        if not min(a, b) == -1 and a < b:
            ans = min(ans, 5 * (b - a))
for t in s3:
    if not t:
        continue
    a, b, c, d = -1, -1, -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "U":
            a = tt[0]
        elif tt[1] == "D":
            b = tt[0]
        elif tt[1] == "R":
            c = tt[0]
        elif tt[1] == "L":
            d = tt[0]
        if not min(a, c) == -1 and a > c:
            ans = min(ans, 5 * (a - c))
        if not min(b, d) == -1 and d > b:
            ans = min(ans, 5 * (d - b))
for t in s4:
    if not t:
        continue
    a, b, c, d = -1, -1, -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "U":
            a = tt[0]
        elif tt[1] == "D":
            b = tt[0]
        elif tt[1] == "R":
            c = tt[0]
        elif tt[1] == "L":
            d = tt[0]
        if not min(b, c) == -1 and c < b:
            ans = min(ans, 5 * (b - c))
        if not min(a, d) == -1 and a < d:
            ans = min(ans, 5 * (d - a))
print(ans if not ans == 100000000 else "SAFE")

Solution (Python):
import sys
input = sys.stdin.readline

from collections import defaultdict
M = 200001
N = int(input())
F = []
X = [[] for _ in range(M)] 
Y = [[] for _ in range(M)]

S1 = defaultdict(list) 
S2 = defaultdict(list)
T1 = defaultdict(list)
T2 = defaultdict(list)

for _ in range(N):
    x, y, c = input().split()
    x = int(x)
    y = int(y)
    if c == 'U':
        c = 0
        S1[x + y].append((x - y, c))
        T1[x - y].append((x + y, c))
    elif c == 'R':
        c = 1
        S1[x + y].append((x - y, c))
        T2[x - y].append((x + y, c))
    elif c == 'D':
        c = 2
        S2[x + y].append((x - y, c))
        T2[x - y].append((x + y, c))
    else:
        c = 3
        S2[x + y].append((x - y, c))
        T1[x - y].append((x + y, c))
    if c % 2 == 0:
        X[x].append((y, c))
    else:
        Y[y].append((x, c))

res = 10**18

for i in range(M):
    X[i].sort()
    tmp = None
    for j in range(len(X[i])):
        y, c = X[i][j]
        if c == 0:
            tmp = y
        if c == 2:
            if tmp is not None:
                res = min(res, (y - tmp) * 5)

for i in range(M):
    Y[i].sort()
    tmp = None
    for j in range(len(Y[i])):
        x, c = Y[i][j]
        if c == 1:
            tmp = x
        if c == 3:
            if tmp is not None:
                res = min(res, (x - tmp) * 5)

for k, v in S1.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 1:
            tmp = z
        if c == 0:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

for k, v in S2.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 2:
            tmp = z
        if c == 3:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

for k, v in T1.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 0:
            tmp = z
        if c == 3:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

for k, v in T2.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 1:
            tmp = z
        if c == 2:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

print(res if res != 10**18 else 'SAFE')

Solution (Python):
n = int(input())
xyu = [list(input().split()) for _ in range(n)]

r = []
l = []
u = []
d = []
ans = 10**15

for x,y,U in xyu:
    x = int(x)
    y = int(y)
    if U == 'U':
        u.append((x,y,x+y,x-y))
    elif U == 'R':
        r.append((x,y,x+y,x-y))
    elif U == 'D':
        d.append((x,y,x+y,x-y))
    else:
        l.append((x,y,x+y,x-y))

xr = [[] for _ in range(200010)]
xl = [[] for _ in range(200010)]

for x,y,z,w in r:
    xr[y].append(x)

for x,y,z,w in l:
    xl[y].append(x)

for i in range(len(xr)):
    if xr[i] and xl[i]:
        a = sorted(xr[i])
        b = sorted(xl[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*5)

yd = [[] for _ in range(200010)]
yu = [[] for _ in range(200010)]

for x,y,z,w in d:
    yd[x].append(y)

for x,y,z,w in u:
    yu[x].append(y)

for i in range(len(yd)):
    if yd[i] and yu[i]:
        b = sorted(yd[i])
        a = sorted(yu[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*5)

zr = [[] for _ in range(400010)]
zu = [[] for _ in range(400010)]

for x,y,z,w in r:
    zr[z].append(x)

for x,y,z,w in u:
    zu[z].append(x)

for i in range(len(zr)):
    if zr[i] and zu[i]:
        b = sorted(zu[i])
        a = sorted(zr[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

zd = [[] for _ in range(400010)]
zl = [[] for _ in range(400010)]

for x,y,z,w in d:
    zd[z].append(x)

for x,y,z,w in l:
    zl[z].append(x)

for i in range(len(zd)):
    if zd[i] and zl[i]:
        b = sorted(zl[i])
        a = sorted(zd[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

wd = [[] for _ in range(400010)]
wr = [[] for _ in range(400010)]

for x,y,z,w in d:
    wd[w+200005].append(x)

for x,y,z,w in r:
    wr[w+200005].append(x)

for i in range(len(wr)):
    if wd[i] and wr[i]:
        b = sorted(wd[i])
        a = sorted(wr[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

wl = [[] for _ in range(400010)]
wu = [[] for _ in range(400010)]

for x,y,z,w in l:
    wl[w+200005].append(x)

for x,y,z,w in u:
    wu[w+200005].append(x)

for i in range(len(wl)):
    if wl[i] and wu[i]:
        b = sorted(wl[i])
        a = sorted(wu[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

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

Solution (Python):
import bisect

n = int(input())
xyu_180_1 = {}
xyu_180_2 = {}
xyu_90_1 = {}
xyu_90_2 = {}
xyu_90_3 = {}
xyu_90_4 = {}
for i in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U":
        xyu_180_2.setdefault(x, {"U":[], "D":[]})
        xyu_180_2[x][u].append(y)
        xyu_90_1.setdefault(x + y, {"R":[], "U":[]})
        xyu_90_1[x + y][u].append(x - y)
        xyu_90_2.setdefault(x - y, {"U":[], "L":[]})
        xyu_90_2[x - y][u].append(x + y)
    elif u == "R":
        xyu_180_1.setdefault(y, {"R":[], "L":[]})
        xyu_180_1[y][u].append(x)
        xyu_90_1.setdefault(x + y, {"R":[], "U":[]})
        xyu_90_1[x + y][u].append(x - y)
        xyu_90_4.setdefault(x - y, {"D":[], "R":[]})
        xyu_90_4[x - y][u].append(x + y)
    elif u == "D":
        xyu_180_2.setdefault(x, {"U":[], "D":[]})
        xyu_180_2[x][u].append(y)
        xyu_90_3.setdefault(x + y, {"L":[], "D":[]})
        xyu_90_3[x + y][u].append(x - y)
        xyu_90_4.setdefault(x - y, {"D":[], "R":[]})
        xyu_90_4[x - y][u].append(x + y)
    elif u == "L":
        xyu_180_1.setdefault(y, {"R":[], "L":[]})
        xyu_180_1[y][u].append(x)
        xyu_90_2.setdefault(x - y, {"U":[], "L":[]})
        xyu_90_2[x - y][u].append(x + y)
        xyu_90_3.setdefault(x + y, {"D":[], "L":[]})
        xyu_90_3[x + y][u].append(x - y)
time = float("inf")
for i in xyu_180_1.values():
    if i["R"] and i["L"]:
        num = i["L"]
        num.sort()
        for j in i["R"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_180_2.values():
    if i["U"] and i["D"]:
        num = i["D"]
        num.sort()
        for j in i["U"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_1.values():
    if i["R"] and i["U"]:
        num = i["U"]
        num.sort()
        for j in i["R"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_2.values():
    if i["U"] and i["L"]:
        num = i["L"]
        num.sort()
        for j in i["U"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_3.values():
    if i["D"] and i["L"]:
        num = i["L"]
        num.sort()
        for j in i["D"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_4.values():
    if i["R"] and i["D"]:
        num = i["D"]
        num.sort()
        for j in i["R"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
if time == float("inf"):
    print("SAFE")
else:
    print(time)