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
n = int(input())
from collections import defaultdict
import bisect
xd0=defaultdict(list)
xd90=defaultdict(list)
xd180=defaultdict(list)
xd270=defaultdict(list)
xyd0=defaultdict(list)
xyd90=defaultdict(list)
xyd180=defaultdict(list)
xyd270=defaultdict(list)

def rotate(x,y,u):
    if u=='U': u0='R'
    elif u=='R': u0='D'
    elif u=='D': u0='L'
    else: u0='U'
    x0=y
    y0=200000-x
    return x0,y0,u0

for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=='U' or u=='D':
        xd0[x].append((y,u))
    x90,y90,u90=rotate(x,y,u)
    if u90=='U' or u90=='D':
        xd90[x90].append((y90,u90))
    x180,y180,u180=rotate(x90,y90,u90)
    if u180=='U' or u180=='D':
        xd180[x180].append((y180,u180))
    x270,y270,u270=rotate(x180,y180,u180)
    if u270=='U' or u270=='D':
        xd270[x270].append((y270,u270))
    if u=='U' or u=='R':
        xyd0[x+y].append((y,u))
    if u90=='U' or u90=='R':
        xyd90[x90+y90].append((y90,u90))
    if u180=='U' or u180=='R':
        xyd180[x180+y180].append((y180,u180))
    if u270=='U' or u270=='R':
        xyd270[x270+y270].append((y270,u270))

ans=float('inf')
for i in range(4):
    if i==0:
        xd=xd0
        xyd=xyd0
    elif i==1:
        xd=xd90
        xyd=xyd90        
    elif i==2:
        xd=xd180
        xyd=xyd180
    elif i==3:
        xd=xd270
        xyd=xyd270
    for j in range(200001):
        xl=xd[j]
        nxl=len(xl)
        if nxl<=1: continue
        elif nxl>1:
            xl=sorted(xl)
            for i in range(1,nxl):
                if xl[i][1]=='D' and xl[i-1][1]=='U':
                    ans=min(ans, (xl[i][0]-xl[i-1][0])*5)
    for j in range(400001):
        xyl=xyd[j]
        nxyl=len(xyl)
        if nxyl<=1: continue
        elif nxyl>1:
            xyl=sorted(xyl)
            for i in range(1,nxyl):
                if xyl[i][1]=='R' and xyl[i-1][1]=='U':
                    ans=min(ans, (xyl[i][0]-xyl[i-1][0])*10)            

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

Solution (Python):
n = int(input())
from collections import defaultdict
import bisect
xd0=defaultdict(list)
xd90=defaultdict(list)
xd180=defaultdict(list)
xd270=defaultdict(list)
xyd0=defaultdict(list)
xyd90=defaultdict(list)
xyd180=defaultdict(list)
xyd270=defaultdict(list)

def rotate(x,y,u):
    if u=='U': u0='R'
    elif u=='R': u0='D'
    elif u=='D': u0='L'
    else: u0='U'
    x0=y
    y0=200000-x
    return x0,y0,u0

for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=='U' or u=='D':
        xd0[x].append((y,u))
    x90,y90,u90=rotate(x,y,u)
    if u90=='U' or u90=='D':
        xd90[x90].append((y90,u90))
    x180,y180,u180=rotate(x90,y90,u90)
    if u180=='U' or u180=='D':
        xd180[x180].append((y180,u180))
    x270,y270,u270=rotate(x180,y180,u180)
    if u270=='U' or u270=='D':
        xd270[x270].append((y270,u270))
    if u=='U' or u=='R':
        xyd0[x+y].append((y,u))
    if u90=='U' or u90=='R':
        xyd90[x90+y90].append((y90,u90))
    if u180=='U' or u180=='R':
        xyd180[x180+y180].append((y180,u180))
    if u270=='U' or u270=='R':
        xyd270[x270+y270].append((y270,u270))

ans=float('inf')
for i in range(4):
    if i==0:
        xd=xd0
        xyd=xyd0
    elif i==1:
        xd=xd90
        xyd=xyd90        
    elif i==2:
        xd=xd180
        xyd=xyd180
    elif i==3:
        xd=xd270
        xyd=xyd270
    for j in range(200001):
        xl=xd[j]
        nxl=len(xl)
        if nxl<=1: continue
        elif nxl>1:
            xl=sorted(xl)
            for i in range(1,nxl):
                if xl[i][1]=='D' and xl[i-1][1]=='U':
                    ans=min(ans, (xl[i][0]-xl[i-1][0])*5)
    for j in range(400001):
        xyl=xyd[j]
        nxyl=len(xyl)
        if nxyl<=1: continue
        elif nxyl>1:
            xyl=sorted(xyl)
            for i in range(1,nxyl):
                if xyl[i][1]=='R' and xyl[i-1][1]=='U':
                    ans=min(ans, (xyl[i][0]-xyl[i-1][0])*10)            

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

Solution (Python):
n = int(input())
x = []
y = []
d = []
for i in range(n):
  s = input().split()
  x.append(int(s[0]))
  y.append(int(s[1]))
  if s[2] == 'U':
    d.append(0)
  elif s[2] == 'L':
    d.append(1)
  elif s[2] == 'D':
    d.append(2)
  else:
    d.append(3)

INF = float('inf')

def calc(p):
  
  res = INF
  for k,v in p.items():
    v.sort()
    for i in range(1,len(v)):
      if v[i-1][1] == 0 and v[i][1] != 0:
        res = min(v[i][0]-v[i-1][0],res)
  return res

ans = INF
for r in range(4):
  
  p = {}
  for i in range(n):
    if d[i] != 0 and d[i] != 2:
      continue
    if x[i] in p:
      p[x[i]].append((y[i],d[i]))
    else:
      p[x[i]] = [(y[i],d[i])]
  ans = min(calc(p)*5,ans)
  
  p = {}
  for i in range(n):
    if d[i] != 0 and d[i] != 3:
      continue
    if x[i]+y[i] in p:
      p[x[i]+y[i]].append((y[i],d[i]))
    else:
      p[x[i]+y[i]] = [(y[i],d[i])]
  ans = min(calc(p)*10,ans)
  
  for i in range(n):
    x[i],y[i] = -y[i],x[i]
    d[i] = (d[i]+1)%4

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

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

planes = {
  'U': [],
  'R': [],
  'D': [],
  'L': []
}

for _ in range(N):
  x, y, t = input().split()
  x, y = int(x), int(y)
  planes[t].append((x, y))
  
BIG = 10**18
  
def time(ps):
  ps.sort()
  ans = BIG
  for i in range(len(ps)-1):
    y1, x1, t1 = ps[i]
    y2, x2, t2 = ps[i+1]
    
    if y1 != y2:
      continue
    
    if t1 == 1 and t2 == -1:
      ans = min(ans, x2 - x1)
  return 5*ans


ud = [(x, y, 1) for x, y in planes['U']] + [(x, y, -1) for x, y in planes['D']]
lr = [(y, x, 1) for x, y in planes['R']] + [(y, x, -1) for x, y in planes['L']]

ur = [(x+y, y-x, 1) for x, y in planes['U']] + [(x+y, y-x, -1) for x, y in planes['R']]
ul = [(x-y, y+x, 1) for x, y in planes['U']] + [(x-y, y+x, -1) for x, y in planes['L']]
rd = [(x-y, y+x, 1) for x, y in planes['R']] + [(x-y, y+x, -1) for x, y in planes['D']]
ld = [(x+y, y-x, 1) for x, y in planes['L']] + [(x+y, y-x, -1) for x, y in planes['D']]

ans = min(time(ud), time(lr), time(ur), time(ul), time(rd), time(ld))
if ans >= BIG:
  print("SAFE")
else:
  print(ans)

Solution (Python):
from collections import defaultdict
n = int(input())
x = [0] * n
y = [0] * n
dir = [0] * n
INF = 10**8


def g(v):
    v.sort(key=lambda x: x[0])
    ret = INF
    for i in range(1, len(v)):
        if v[i - 1][1] == 0 and v[i][1] != 0:
            ret = min(ret, v[i][0] - v[i - 1][0])
    return ret


def f(d):
    ret = INF
    for k, v in d.items():
        ret = min(ret, g(v))
    return ret


for i in range(n):
    
    sx, sy, c = input().split()
    x[i] = int(sx)
    y[i] = int(sy)
    if c == 'U':
        dir[i] = 0
    if c == 'R':
        dir[i] = 1
    if c == 'D':
        dir[i] = 2
    if c == 'L':
        dir[i] = 3

ans = INF
for ri in range(4):
    
    d = defaultdict(list)
    for i in range(n):
        if dir[i] != 0 and dir[i] != 2:
            continue
        d[x[i]].append((y[i], dir[i]))
    ans = min(ans, f(d) * 5)
    
    d2 = defaultdict(list)
    for i in range(n):
        if dir[i] != 0 and dir[i] != 1:
            continue
        d2[x[i] + y[i]].append((y[i], dir[i]))
    ans = min(ans, f(d2) * 10)

    
    for i in range(n):
        px = x[i]
        py = y[i]
        x[i] = py
        y[i] = -px
        dir[i] = (dir[i] + 1) % 4
if ans >= INF:
    print('SAFE')
else:
    print(ans)

Solution (Python):
from collections import defaultdict

n = int(input())
line = defaultdict(list)  
row = defaultdict(list)  
A = defaultdict(list)  
B = defaultdict(list)  
C = defaultdict(list)  
D = defaultdict(list)  

for i in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U":
        row[x].append((y, u == "U"))
        A[y + x].append((y - x, u == "U"))
        C[y - x].append((y + x, u == "U"))
    elif u == "D":
        row[x].append((y, u == "U"))
        B[y + x].append((y - x, u == "L"))
        D[y - x].append((y + x, u == "R"))
    elif u == "L":
        line[y].append((x, u == "R"))
        B[y + x].append((y - x, u == "L"))
        C[y - x].append((y + x, u == "U"))
    else:
        line[y].append((x, u == "R"))
        A[y + x].append((y - x, u == "U"))
        D[y - x].append((y + x, u == "R"))

ans = 10**18
for Z in (line, row, A, B, C, D):
    for z_list in Z.values():
        z_list.sort()
        for (v1, flag1), (v2, flag2) in zip(z_list, z_list[1:]):
            if flag1 and not flag2:
                ans = min(ans, abs(v1 - v2) * 5)

if ans == 10**18:
    print("SAFE")
else:
    print(ans)

Solution (Python):
from collections import defaultdict

n = int(input())
line = defaultdict(list)
row = defaultdict(list)
A = defaultdict(list)  
B = defaultdict(list)  
C = defaultdict(list)  
D = defaultdict(list)  

for i in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U":
        row[x].append((y, True))
        A[y + x].append((y - x, True))
        C[y - x].append((y + x, True))
    elif u == "D":
        row[x].append((y, False))
        B[y + x].append((y - x, False))
        D[y - x].append((y + x, False))
    elif u == "L":
        line[y].append((x, False))
        B[y + x].append((y - x, True))
        C[y - x].append((y + x, False))
    else:
        line[y].append((x, True))
        A[y + x].append((y - x, False))
        D[y - x].append((y + x, True))

ans = 10**18
for Z in (line, row, A, B, C, D):
    for z_list in Z.values():
        z_list.sort()
        for i in range(len(z_list) - 1):
            if z_list[i][1] == True and z_list[i + 1][1] == False:
                ans = min(ans, abs(z_list[i][0] - z_list[i + 1][0]) * 5)

if ans >= 10**18:
    print("SAFE")
else:
    print(ans)

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


D_sum = defaultdict(list)
D_diff = defaultdict(list)
DX = defaultdict(list)
DY = defaultdict(list)
n = I()
L = []
ans = INF
for i in range(n):
    x, y, u = LS()
    x = int(x)
    y = int(y)
    D_sum[x + y] += [(x, u)]
    D_diff[x - y] += [(x, u)]
    if u in "UD":
        DX[x] += [(y, u)]
    else:
        DY[y] += [(x, u)]


for _, co_list in D_sum.items():
    co_list.sort()
    r = d = -INF
    for co, direction in co_list:
        if direction == "R":
            r = co
        elif direction == "D":
            d = co
        elif direction == "U":
            ans = min(co - r, ans)
        else:
            ans = min(co - d, ans)

for _, co_list in D_diff.items():
    co_list.sort()
    u = r = -INF
    for co, direction in co_list:
        if direction == "U":
            u = co
        elif direction == "R":
            r = co
        elif direction == "D":
            ans = min(co - r, ans)
        else:
            ans = min(co - u, ans)


for _, co_list in DX.items():
    co_list.sort()
    u = -INF
    for co, direction in co_list:
        coo = co
        if direction == "U":
            u = co
        else:
            ans = min((co - u) / 2, ans)


for _, co_list in DY.items():
    co_list.sort()
    r = -INF
    for co, direction in co_list:
        if direction == "R":
            r = co
        else:
            ans = min((co - r) / 2, ans)


if ans > 10 ** 8:
    print("SAFE")
else:
    print(int(ans * 10))







"""
L1 = []
L2 = []
L3 = []
L4 = []
for xk, yk ,u in L:
    L1 += [(xk - yk)]
    L2 += [(- xk - yk)]
    L3 += [(xk + yk)]
    L4 += [(- xk + yk)]

print(L1)
print(L2)
print(L3)
print(L4)

"""

Solution (Python):
INF = 2000000000


def calc_xx(A, B, mult, comp_field, diff_field):
    AA = list(sorted(A, key=lambda pp: (pp[comp_field], pp[diff_field])))
    BB = list(sorted(B, key=lambda pp: (pp[comp_field], pp[diff_field])))

    a = 0
    b = 0

    min_time = INF
    while a < len(A) and b < len(B):
        
        if AA[a][comp_field] == BB[b][comp_field]:
            astart = a
            asame = a + 1
            while asame < len(A) and AA[asame][comp_field] == AA[a][comp_field]:
                asame += 1
            aend = asame - 1

            bstart = b
            bsame = b + 1
            while bsame < len(B) and BB[bsame][comp_field] == BB[b][comp_field]:
                bsame += 1
            bend = bsame - 1

            
            aa = astart
            bb = bstart
            while aa <= aend and bb <= bend:
                diff = BB[bb][diff_field] - AA[aa][diff_field]
                if diff > 0:
                    hit_time = diff * mult
                    min_time = min(min_time, hit_time)

                if aa == aend:
                    bb += 1
                elif bb == bend:
                    aa += 1
                elif BB[bb][diff_field] > AA[aa][diff_field]:
                    aa += 1
                else:
                    bb += 1

            a = aend + 1
            b = bend + 1

        elif a == len(A) - 1:
            b += 1
        elif b == len(B) - 1:
            a += 1
        elif AA[a][comp_field] > BB[b][comp_field]:
            b += 1
        elif AA[a][comp_field] < BB[b][comp_field]:
            a += 1
        else:
            raise Exception

    return min_time


def main():
    N = int(input())
    PLANES = []

    U = []
    R = []
    D = []
    L = []
    for i in range(N):
        
        
        
        p = input().split()
        p[0] = int(p[0])
        p[1] = int(p[1])

        pp = [p[0], p[1], (p[0] + p[1]), (p[1] - p[0])]

        PLANES.append(p)
        if p[2] == "U":
            U.append(pp)
        elif p[2] == "R":
            R.append(pp)
        elif p[2] == "D":
            D.append(pp)
        else:
            L.append(pp)

    min_time = min(
        calc_xx(R, U, 10, 2, 0),
        calc_xx(U, D, 5, 0, 1),
        calc_xx(U, L, 10, 3, 0),
        calc_xx(R, D, 10, 3, 0),
        calc_xx(R, L, 5, 1, 0),
        calc_xx(D, L, 10, 2, 0),
    )

    if min_time == INF:
        print("SAFE")
    else:
        print(min_time)


main()

Solution (Python):

n=int(input())
ud=[[[],[]] for i in range(200001)]
rl=[[[],[]] for i in range(200001)]
from bisect import *
cross=[[dict(),dict()] for i in range(4)]
for i in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=="U":
        ud[x][0].append(y)
        if x+y in cross[0][1]:
            cross[0][1][x+y].append(x)
        else:
            cross[0][1][x+y]=[x]
        if x-y in cross[1][1]:
            cross[1][1][x-y].append(x)
        else:
            cross[1][1][x-y]=[x]
    elif u=="D":
        ud[x][1].append(y)
        if x+y in cross[3][1]:
            cross[3][1][x+y].append(x)
        else:
            cross[3][1][x+y]=[x]
        if x-y in cross[2][1]:
            cross[2][1][x-y].append(x)
        else:
            cross[2][1][x-y]=[x]
    elif u=="R":
        rl[y][0].append(x)
        if x+y in cross[0][0]:
            cross[0][0][x+y].append(x)
        else:
            cross[0][0][x+y]=[x]
        if x-y in cross[2][0]:
            cross[2][0][x-y].append(x)
        else:
            cross[2][0][x-y]=[x]
    else:
        rl[y][1].append(x)
        if x+y in cross[3][0]:
            cross[3][0][x+y].append(x)
        else:
            cross[3][0][x+y]=[x]
        if x-y in cross[1][0]:
            cross[1][0][x-y].append(x)
        else:
            cross[1][0][x-y]=[x]

for i in range(200001):
    ud[i][0].sort()
    ud[i][1].sort()
    rl[i][0].sort()
    rl[i][1].sort()

ans=[]
for i in range(200001):
    l1,l2=len(ud[i][0]),len(ud[i][1])
    if l1 and l2:
        for j in ud[i][0]:
            b=bisect_left(ud[i][1],j)
            if b!=l2:
                ans.append(ud[i][1][b]-j)
    l1,l2=len(rl[i][0]),len(rl[i][1])
    if l1 and l2:
        for j in rl[i][0]:
            b=bisect_left(rl[i][1],j)
            if b!=l2:
                ans.append(rl[i][1][b]-j)

for i in range(4):
    for j in range(2):
        for k in cross[i][j]:
            cross[i][j][k].sort()

for i in range(4):
    for j in cross[i][1]:
        if j in cross[i][0]:
            l=len(cross[i][0][j])
            if i%2==1:
                for k in cross[i][1][j]:
                    b=bisect_left(cross[i][0][j],k)
                    if b!=l:
                        ans.append(2*cross[i][0][j][b]-2*k)
            else:
                for k in cross[i][1][j]:
                    b=bisect_right(cross[i][0][j],k)-1
                    if b!=-1:
                        ans.append(2*k-2*cross[i][0][j][b])

if len(ans):
    print(min(ans)*5)
else:
    print("SAFE")

Solution (Python):
import sys
import math
from collections import deque
import heapq as hq

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    N = NI()
    planes = [list(SI().split()) for _ in range(N)]

    XS = [[] for _ in range(200001)]
    YS = [[] for _ in range(200001)]
    ZS = [[] for _ in range(400001)]
    WS = [[] for _ in range(400001)]
    for plane in planes:
        x, y, u = int(plane[0]), int(plane[1]), plane[2]
        XS[x].append((y, u))
        YS[y].append((x, u))
        ZS[x+y].append((x, u))
        WS[x-y+200000].append((x, u))
    for X in XS:
        hq.heapify(X)
    for Y in YS:
        hq.heapify(Y)
    for Z in ZS:
        hq.heapify(Z)
    for W in WS:
        hq.heapify(W)

    ans = float("inf")

    for X in XS:
        if len(X) <= 1:
            continue
        c = -1
        for _ in range(len(X)):
            k, u = hq.heappop(X)
            if u == "U":
                c = k
            if u == "D" and c >= 0:
                ans = min(ans, (k - c)*5)
                c = -1

    for Y in YS:
        if len(Y) <= 1:
            continue
        c = -1
        for _ in range(len(Y)):
            k, u = hq.heappop(Y)
            if u == "R":
                c = k
            if u == "L" and c >= 0:
                ans = min(ans, (k - c)*5)
                c = -1

    for Z in ZS:
        if len(Z) <= 1:
            continue
        c = -1
        d = -1
        for _ in range(len(Z)):
            k, u = hq.heappop(Z)
            if u == "R":
                c = k
            if u == "D":
                d = k
            if u == "U" and c >= 0:
                ans = min(ans, (k - c)*10)
                c = -1
            if u == "L" and d >= 0:
                ans = min(ans, (k - d)*10)
                d = -1

    for W in WS:
        if len(W) <= 1:
            continue
        c = -1
        d = -1
        for _ in range(len(W)):
            k, u = hq.heappop(W)
            if u == "R":
                c = k
            if u == "U":
                d = k
            if u == "D" and c >= 0:
                ans = min(ans, (k - c)*10)
                c = -1
            if u == "L" and d >= 0:
                ans = min(ans, (k - d)*10)
                d = -1

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


if __name__ == "__main__":
    main()

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

N=int(input())

X1={}
X2={}

X={}
Y={}

for i in range(N):
    x,y,u=input().split()
    x=int(x)
    y=int(y)
    if x+y not in X1:
        X1[x+y]=[[x,u]]
    else:
        X1[x+y].append([x,u])
    if y-x not in X2:
        X2[y-x]=[[x,u]]
    else:
        X2[y-x].append([x,u])
    if x not in X:
        X[x]=[[y,u]]
    else:
        X[x].append([y,u])
    if y not in Y:
        Y[y]=[[x,u]]
    else:
        Y[y].append([x,u])


Dead=10**9


for k,v in X1.items():
    D=-1
    R=-1
    v.sort()
    
    for a,u in v:
        if u=="D":
            D=a
        elif u=="R":
            R=a
        elif u=="L":
            if D>=0:
                Dead=min(Dead,(a-D)*10)
        elif u=="U":
            if R>=0:
                Dead=min(Dead,(a-R)*10)
for k,v in X2.items():
    U=-1
    R=-1
    v.sort()
    
    for a,u in v:
        if u=="U":
            U=a
        elif u=="R":
            R=a
        elif u=="L":
            if U>=0:
                Dead=min(Dead,(a-U)*10)
        elif u=="D":
            if R>=0:
                Dead=min(Dead,(a-R)*10)
for k,v in X.items():
    U=-1
    v.sort()
    
    for a,u in v:
        if u=="U":
            U=a
        elif u=="D":
            if U>=0:
                Dead=min(Dead,(a-U)*5)
for k,v in Y.items():
    R=-1
    v.sort()
    
    for a,u in v:
        if u=="R":
            R=a
        elif u=="L":
            if R>=0:
                Dead=min(Dead,(a-R)*5)
if Dead==10**9:
    print("SAFE")
else:
    print(Dead)

Solution (Python):
n = int((input()))
U, R, D, L = [], [], [], []
for _ in range(n):
    x, y, d = input().split()
    x = int(x)
    y = int(y)
    (U if d == 'U' else R if d == 'R' else D if d == 'D' else L).append((x, y))
INF = 1001001001
ans = INF
def front_crash(u, d):
    global ans
    u.sort()
    d.sort()
    i = 0
    j = 0
    while i < len(u) and j < len(d):
        ut = [u[i][1]]
        while i + 1 < len(u) and u[i][0] == u[i+1][0]:
            i += 1
            ut.append(u[i][1])
        dt = []
        while j < len(d) and d[j][0] < u[i][0]:
            j += 1
        while j < len(d) and d[j][0] == u[i][0]:
            dt.append(d[j][1])
            j += 1
        q = 0
        for y1 in ut:
            while q < len(dt) and dt[q] < y1:
                q += 1
            if q == len(dt):
                break
            y2 = dt[q]
            ans = min(ans, (y2 - y1) * 5)
        i += 1
front_crash(U, D)
front_crash(*(list(map(lambda p: (p[1], p[0]), t)) for t in [R, L]))
from collections import defaultdict
from bisect import bisect_left
def side_crash(u, r):
    global ans
    d = defaultdict(list)
    u.sort()
    for x, y in u:
        d[x+y].append(x)
    for x, y in r:
        dxy = d[x+y]
        i = bisect_left(dxy, x)
        if i < len(dxy):
            ans = min(ans, (dxy[i] - x) * 10)
side_crash(U, R)
side_crash(*([(y, 200000 - x) for x, y in t] for t in [L, U]))
side_crash(*([(200000 - x, 200000 - y) for x, y in t] for t in [D, L]))
side_crash(*([(200000 - y, x) for x, y in t] for t in [R, D]))

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

Solution (Python):
n = int(input())
b = 2000001
u = []; r = []; d = []; l = []
for i in range(n):
    A = list(input().split())
    a = [int(A[0]), int(A[1])]
    if A[2] == "U":
        u.append(a)
    elif A[2] == "R":
        r.append(a)
    elif A[2] == "D":
        d.append(a)
    else:
        l.append(a)
u1 = {}; d1 = {}
for i in range(len(u)):
    if u[i][0] not in u1:
        u1[u[i][0]] = []
    u1[u[i][0]].append(u[i][1])
for i in range(len(d)):
    if d[i][0] not in d1:
        d1[d[i][0]] = []
    d1[d[i][0]].append(d[i][1])
for i in range(200001):
    if i in u1 and i in d1:
        u1[i].sort(reverse=True)
        d1[i].sort(reverse=True)
        for j in range(len(u1[i])):
            for k in range(len(d1[i])):
                if u1[i][-1] < d1[i][-1]:
                    b = min(b, (d1[i][-1]-u1[i][-1])*5)
                    break
                else:
                    d1[i].pop()
            u1[i].pop()
r1 = {}; l1 = {}
for i in range(len(r)):
    if r[i][1] not in r1:
        r1[r[i][1]] = []
    r1[r[i][1]].append(r[i][0])
for i in range(len(l)):
    if l[i][1] not in l1:
        l1[l[i][1]] = []
    l1[l[i][1]].append(l[i][0])
for i in range(200001):
    if i in r1 and i in l1:
        r1[i].sort(reverse=True)
        l1[i].sort(reverse=True)
        for j in range(len(r1[i])):
            for k in range(len(l1[i])):
                if r1[i][-1] < l1[i][-1]:
                    b = min(b, (l1[i][-1]-r1[i][-1])*5)
                    break
                else:
                    l1[i].pop()
            r1[i].pop()
u2 = {}; r2 = {}
for i in range(len(u)):
    if u[i][0]+u[i][1] not in u2:
        u2[u[i][0]+u[i][1]] = []
    u2[u[i][0]+u[i][1]].append(u[i][0])
for i in range(len(r)):
    if r[i][0]+r[i][1] not in r2:
        r2[r[i][0]+r[i][1]] = []
    r2[r[i][0]+r[i][1]].append(r[i][0])
for i in range(400001):
    if i in u2 and i in r2:
        u2[i].sort(reverse=True)
        r2[i].sort(reverse=True)
        for j in range(len(r2[i])):
            for k in range(len(u2[i])):
                if r2[i][-1] < u2[i][-1]:
                    b = min(b, (u2[i][-1]-r2[i][-1])*10)
                    break
                else:
                    u2[i].pop()
            r2[i].pop()
l2 = {}; d2 = {}
for i in range(len(l)):
    if l[i][0]+l[i][1] not in l2:
        l2[l[i][0]+l[i][1]] = []
    l2[l[i][0]+l[i][1]].append(l[i][0])
for i in range(len(d)):
    if d[i][0]+d[i][1] not in d2:
        d2[d[i][0]+d[i][1]] = []
    d2[d[i][0]+d[i][1]].append(d[i][0])
for i in range(400001):
    if i in l2 and i in d2:
        l2[i].sort(reverse=True)
        d2[i].sort(reverse=True)
        for j in range(len(d2[i])):
            for k in range(len(l2[i])):
                if d2[i][-1] < l2[i][-1]:
                    b = min(b, (l2[i][-1]-d2[i][-1])*10)
                    break
                else:
                    l2[i].pop()
            d2[i].pop()
l3 = {}; u3 = {}
for i in range(len(l)):
    if l[i][0]-l[i][1] not in l3:
        l3[l[i][0]-l[i][1]] = []
    l3[l[i][0]-l[i][1]].append(l[i][0])
for i in range(len(u)):
    if u[i][0]-u[i][1] not in u3:
        u3[u[i][0]-u[i][1]] = []
    u3[u[i][0]-u[i][1]].append(u[i][0])
for i in range(-200000, 200001):
    if i in l3 and i in u3:
        l3[i].sort(reverse=True)
        u3[i].sort(reverse=True)
        for j in range(len(u3[i])):
            for k in range(len(l3[i])):
                if u3[i][-1] < l3[i][-1]:
                    b = min(b, (l3[i][-1]-u3[i][-1])*10)
                    break
                else:
                    l3[i].pop()
            u3[i].pop()
d3 = {}; r3 = {}
for i in range(len(d)):
    if d[i][0]-d[i][1] not in d3:
        d3[d[i][0]-d[i][1]] = []
    d3[d[i][0]-d[i][1]].append(d[i][0])
for i in range(len(r)):
    if r[i][0]-r[i][1] not in r3:
        r3[r[i][0]-r[i][1]] = []
    r3[r[i][0]-r[i][1]].append(r[i][0])
for i in range(-200000, 200001):
    if i in d3 and i in r3:
        d3[i].sort(reverse=True)
        r3[i].sort(reverse=True)
        for j in range(len(r3[i])):
            for k in range(len(d3[i])):
                if r3[i][-1] < d3[i][-1]:
                    b = min(b, (d3[i][-1]-r3[i][-1])*10)
                    break
                else:
                    d3[i].pop()
            r3[i].pop()
print("SAFE") if b == 2000001 else print(b)