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())
ans = 10 ** 10
upanddown = [[] for i in range(200001)]
leftandright = [[] for i in range(200001)]
lis = []
for i in range(n):
    x,y,r = map(str,input().split())
    x,y = int(x),int(y)
    lis.append([x+y,x-y,x,y,r])
    if r == "U":
        upanddown[x].append([y,0])
    elif r == "D":
        upanddown[x].append([y,1])
    elif r == "R":
        leftandright[y].append([x,0])
    else:
        leftandright[y].append([x,1])
  
for li in upanddown:
    if len(li) >= 2:
        li.sort(key=lambda z:z[1])
        li.sort(key=lambda z:z[0])
        key = 0
        keynum = -1
        for num,r in li:
            if r == 0:
                keynum = num
            else:
                if keynum != -1:
                    ans = min(ans,(num-keynum)*5)
for li in leftandright:
    if len(li) >= 2:
        li.sort(key=lambda z:z[1])
        li.sort(key=lambda z:z[0])
        key = 0
        keynum = -1
        for num,r in li:
            if r == 0:
                keynum = num
            else:
                if keynum != -1:
                    ans = min(ans,(num-keynum)*5)
  
lis.sort(key = lambda z:z[2])
lis.sort(key = lambda z:z[0])

for i in range(n-1):
    if lis[i][0] == lis[i+1][0]:
        if (lis[i][4] == "R" and lis[i+1][4] == "U") or (lis[i][4] == "D" and lis[i+1][4] == "L"):
            ans = min(ans,(lis[i+1][2]-lis[i][2])*10)
lis.sort(key = lambda z:z[2])
lis.sort(key = lambda z:z[1])

for i in range(n-1):
    if lis[i][1] == lis[i+1][1]:
        if (lis[i][4] == "U" and lis[i+1][4] == "L") or (lis[i][4] == "R" and lis[i+1][4] == "D"):
            ans = min(ans,(lis[i+1][2]-lis[i][2])*10)
if ans == 10 ** 10:
    print("SAFE")
else:
    print(ans)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





N = I()
data = SLL(N)

Udic = DD(list)
Ddic = DD(list)
Ldic = DD(list)
Rdic = DD(list)

URdic = DD(lambda:[[],[]])
DLdic = DD(lambda:[[],[]])

ULdic = DD(lambda:[[],[]])
DRdic = DD(lambda:[[],[]])

for i in range(N):
  x,y,s = data[i]
  x,y = int(x), int(y)
  if s == "U":
    Udic[x].append(y)
    URdic[x+y][0].append(x)
    ULdic[x-y][0].append(x)
  if s == "D":
    Ddic[x].append(y)
    DLdic[x+y][0].append(x)
    DRdic[x-y][0].append(x)
  if s == "L":
    Ldic[y].append(x)
    DLdic[x+y][1].append(x)
    ULdic[x-y][1].append(x)
  if s == "R":
    Rdic[y].append(x)
    URdic[x+y][1].append(x)
    DRdic[x-y][1].append(x)

col_t = INF

Uk = [k for k in Udic]
Dk = [k for k in Ddic]
Lk = [k for k in Ldic]
Rk = [k for k in Rdic]

UDk = set(Uk)&set(Dk)
LRk = set(Lk)&set(Rk)

for k in UDk:
  Udic[k].sort()
  for d in Ddic[k]:
    p = bisect.bisect(Udic[k],d)
    if p:
      col_t = min(col_t,(d-Udic[k][p-1])*5)
      
for k in LRk:
  Rdic[k].sort()
  for l in Ldic[k]:
    p = bisect.bisect(Rdic[k],l)
    if p:
      col_t = min(col_t,(l-Rdic[k][p-1])*5)
      
      
for k in URdic:
  if URdic[k][0] and URdic[k][1]:
    URdic[k][1].sort()
    for u in URdic[k][0]:
      p = bisect.bisect(URdic[k][1],u)
      if p:
        col_t = min(col_t,(u-URdic[k][1][p-1])*10)

for k in DLdic:
  if DLdic[k][0] and DLdic[k][1]:
    DLdic[k][0].sort()
    for l in DLdic[k][1]:
      p = bisect.bisect(DLdic[k][0],l)
      if p:
        col_t = min(col_t,(l-DLdic[k][0][p-1])*10)  

for k in ULdic:
  if ULdic[k][0] and ULdic[k][1]:
    ULdic[k][1].sort()
    for u in ULdic[k][0]:
      p = bisect.bisect(ULdic[k][1],u)
      if p<len(ULdic[k][1]):
        col_t = min(col_t,(ULdic[k][1][p]-u)*10)
for k in DRdic:
  if DRdic[k][0] and DRdic[k][1]:
    DRdic[k][0].sort()
    for r in DRdic[k][1]:
      p = bisect.bisect(DRdic[k][0],r)
      if p<len(DRdic[k][0]):
        col_t = min(col_t,(DRdic[k][0][p]-r)*10)
        
        
if col_t != INF:
  print(col_t)
else:
  print("SAFE")

Solution (Python):
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

n = int(readline())
xyu = read().split()


num = 200_000
x,y,p,m = dict(),dict(),dict(),dict()
for i in [x,y]:
    for s in 'URDL':
        i[s] = [[] for _ in range(num+1)]

for i in [p,m]:
    for s in 'URDL':
        i[s] = [[] for _ in range(num*2+1)]

it = iter(xyu)
for a,b,c in zip(it,it,it):
    a = int(a)
    b = int(b)
    if(c in 'UD'):
        y[c][a].append(b)
    if(c in 'RL'):
        x[c][b].append(a)

    p[c][num + a-b].append(b)
    m[c][a+b].append(b)

inf = 10**10
ans = inf
for i in [x]:
    for j in range(num+1):
        
        if(len(i['R'][j])>0)&(len(i['L'][j])>0):
            a = i['R'][j]
            a.sort()
            b = i['L'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*5)

for i in [y]:
    for j in range(num+1):
        
        if(len(i['U'][j])>0)&(len(i['D'][j])>0):
            a = i['U'][j]
            a.sort()
            b = i['D'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*5)

for i in [p]:
    for j in range(num*2+1):
        
        if(len(i['U'][j])>0)&(len(i['L'][j])>0):
            a = i['U'][j]
            a.sort()
            b = i['L'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

        
        if(len(i['R'][j])>0)&(len(i['D'][j])>0):
            a = i['R'][j]
            a.sort()
            b = i['D'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

for i in [m]:
    for j in range(num*2+1):
        
        if(len(i['U'][j])>0)&(len(i['R'][j])>0):
            a = i['U'][j]
            a.sort()
            b = i['R'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

        
        if(len(i['L'][j])>0)&(len(i['D'][j])>0):
            a = i['L'][j]
            a.sort()
            b = i['D'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

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

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

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def core(dic1, dic2):
    ans = INF
    for j in dic1.keys():
        if j not in dic2:
            continue
        dic1[j].sort()
        dic2[j].sort()
        v1 = dic1[j]
        v2 = dic2[j]
        for x in v1:
            i = bisect_left(v2, x)
            if i == len(v2):
                continue
            if ans > (v2[i] - x) * 10:
                ans = (v2[i] - x) * 10

    return ans


def main():
    N = int(readline())
    M = 200000
    U, R, D, L = [], [], [], []
    for _ in range(N):
        x, y, u = readline().split()
        x, y = int(x), int(y)
        if u == 'U':
            U.append((x, y))
        elif u == 'R':
            R.append((x, y))
        elif u == 'D':
            D.append((x, y))
        else:
            L.append((x, y))

    ans = INF

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in U:
        dic1[x].append(y)
    for x, y in D:
        dic2[x].append(y)

    for j in dic1.keys():
        if j not in dic2:
            continue
        dic1[j].sort()
        dic2[j].sort()
        v1 = dic1[j]
        v2 = dic2[j]
        for yu in v1:
            i = bisect_left(v2, yu)
            if i == len(v2):
                continue
            if ans > (v2[i] - yu) * 10 // 2:
                ans = (v2[i] - yu) * 10 // 2

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in R:
        dic1[y].append(x)
    for x, y in L:
        dic2[y].append(x)

    for j in dic1.keys():
        if j not in dic2:
            continue
        dic1[j].sort()
        dic2[j].sort()
        v1 = dic1[j]
        v2 = dic2[j]
        for xr in v1:
            i = bisect_left(v2, xr)
            if i == len(v2):
                continue
            if ans > (v2[i] - xr) * 10 // 2:
                ans = (v2[i] - xr) * 10 // 2

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in R:
        dic1[y - x].append(x)
    for x, y in D:
        dic2[y - x].append(x)

    ans = min(ans, core(dic1, dic2))

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in U:
        dic1[y - x].append(x)
    for x, y in L:
        dic2[y - x].append(x)

    ans = min(ans, core(dic1, dic2))

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in R:
        dic1[y + x].append(x)
    for x, y in U:
        dic2[y + x].append(x)

    ans = min(ans, core(dic1, dic2))

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in D:
        dic1[y + x].append(x)
    for x, y in L:
        dic2[y + x].append(x)

    ans = min(ans, core(dic1, dic2))

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

    return


if __name__ == '__main__':
    main()

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

n = int(input())
m = 200000
y_r = [[] for _ in range(m+1)]
y_l = [[] for _ in range(m+1)]
x_u = [[] for _ in range(m+1)]
x_d = [[] for _ in range(m+1)]
xy_r = [[] for _ in range(2*m+1)]
xy_l = [[] for _ in range(2*m+1)]
xy_u = [[] for _ in range(2*m+1)]
xy_d = [[] for _ in range(2*m+1)]
yx_r = [[] for _ in range(2*m+1)]
yx_l = [[] for _ in range(2*m+1)]
yx_u = [[] for _ in range(2*m+1)]
yx_d = [[] for _ in range(2*m+1)]

for _ in range(n):
    x, y, u = input().split()
    x, y = int(x), int(y)
    if u == 'U':
        x_u[x].append(y)
        xy_u[x+y].append(x)
        yx_u[y-x+m].append(x)
    if u == 'D':
        x_d[x].append(y)
        xy_d[x+y].append(x)
        yx_d[y-x+m].append(x)
    if u == 'R':
        y_r[y].append(x)
        xy_r[x+y].append(x)
        yx_r[y-x+m].append(x)
    if u == 'L':
        y_l[y].append(x)
        xy_l[x+y].append(x)
        yx_l[y-x+m].append(x)

    

ans = 10 ** 9
for i in range(m+1):
    x_u[i].sort()
    x_d[i].sort()
    y_l[i].sort()
    y_r[i].sort()

    for yu in x_u[i]:
        idx = bisect.bisect_left(x_d[i], yu)
        if idx < len(x_d[i]):
            ans = min(ans, (x_d[i][idx] - yu) * 5)

    for xr in y_r[i]:
        idx = bisect.bisect_left(y_l[i], xr)
        if idx < len(y_l[i]):
            ans = min(ans, (y_l[i][idx] - xr) * 5)

for i in range(2*m+1):
    xy_u[i].sort()
    xy_d[i].sort()
    xy_l[i].sort()
    xy_r[i].sort()

    for xr in xy_r[i]:
        idx = bisect.bisect_left(xy_u[i], xr)
        if idx < len(xy_u[i]):
            ans = min(ans, (xy_u[i][idx] - xr) * 10)
    
    for xd in xy_d[i]:
        idx = bisect.bisect_left(xy_l[i], xd)
        if idx < len(xy_l[i]):
            ans = min(ans, (xy_l[i][idx] - xd) * 10)

    yx_u[i].sort()
    yx_d[i].sort()
    yx_l[i].sort()
    yx_r[i].sort()

    for xr in yx_r[i]:
        idx = bisect.bisect_left(yx_d[i], xr)
        if idx < len(yx_d[i]):
            ans = min(ans, (yx_d[i][idx] - xr) * 10)
    
    for xu in yx_u[i]:
        idx = bisect.bisect_left(yx_l[i], xu)
        if idx < len(yx_l[i]):
            ans = min(ans, (yx_l[i][idx] - xu) * 10)


print(ans if ans < 10 ** 9 else 'SAFE')

Solution (Python):
from collections import defaultdict as dd
from bisect import bisect_left
N = int(input())

Ps = []
for _ in range(N):
    X, Y, U = input().split()
    Ps.append((int(X), int(Y), U))
Ps.sort()

case1 = dd(list)
case2 = dd(list)
case3 = dd(list)
case4 = dd(list)
case5 = dd(list)
case6 = dd(list)

INF = float('inf')
ans = INF
for x, y, u in Ps:
    if u == 'U':
        case2[y-x].append(y)
        case5[x].append(y)
        if y+x in case1:
            idx = bisect_left(case1[y+x], -y)
            if idx > 0:
                t = (-y - case1[y+x][idx-1]) * 10
                ans = ans if ans < t else t

    elif u == 'R':
        case1[y+x].append(-y)
        case3[y-x].append(y)
        case6[y].append(x)
    elif u == 'D':
        case4[y+x].append(-y)
        if y-x in case3:
            idx = bisect_left(case3[y-x], y)
            if idx > 0:
                t = (y - case3[y-x][idx-1]) * 10
                ans = ans if ans < t else t
        if x in case5:
            idx = bisect_left(case5[x], y)
            if idx > 0:
                t = (y - case5[x][idx-1]) * 5
                ans = ans if ans < t else t
    elif u == 'L':
        if y-x in case2:
            idx = bisect_left(case2[y-x], y)
            if idx > 0:
                t = (y - case2[y-x][idx-1]) * 10
                ans = ans if ans < t else t
        if y+x in case4:
            idx = bisect_left(case4[y+x], -y)
            if idx > 0:
                t = (-y - case4[y+x][idx-1]) * 10
                ans = ans if ans < t else t
        if y in case6:
            idx = bisect_left(case6[y], x)
            if idx > 0:
                t = (x - case6[y][idx-1]) * 5
                ans = ans if ans < t else t
if ans == INF:
    print('SAFE')
else:
    print(ans)

Solution (Python):

N = int(input())

UD = {}
LR = {}

RU = {}
DL = {}

UL = {}
RD = {}


for i in range(N):

    X,Y,S = input().split()
    X = int(X)
    Y = int(Y)

    if S == 'U' or S == 'D':
        if X not in UD:
            UD[X] = []
        UD[X].append((Y,S))

    if S == 'L' or S == 'R':
        if Y not in LR:
            LR[Y] = []
        LR[Y].append((X,S))

    if S == 'R' or S == 'U':
        if X+Y not in RU:
            RU[X+Y] = []
        RU[X+Y].append((X,S))

    if S == 'D' or S == 'L':
        if X+Y not in DL:
            DL[X+Y] = []
        DL[X+Y].append((X,S))

    if S == 'U' or S == 'L':
        if X-Y not in UL:
            UL[X-Y] = []
        UL[X-Y].append((Y,S))

    if S == 'R' or S == 'D':
        if X-Y not in RD:
            RD[X-Y] = []
        RD[X-Y].append((Y,S))

ans = float("inf")
for i in UD:
    lasu = float("-inf")
    lis = UD[i]
    lis.sort()
    for t,d in lis:
        if d == "U":
            lasu = t
        else:
            ans = min(ans , (t-lasu))

for i in LR:
    lasu = float("-inf")
    lis = LR[i]
    lis.sort()
    for t,d in lis:
        if d == "R":
            lasu = t
        else:
            ans = min(ans , (t-lasu))

for i in RU:
    lasu = float("-inf")
    lis = RU[i]
    lis.sort()
    for t,d in lis:
        if d == "R":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

for i in DL:
    lasu = float("-inf")
    lis = DL[i]
    lis.sort()
    for t,d in lis:
        if d == "D":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

for i in UL:
    lasu = float("-inf")
    lis = UL[i]
    lis.sort()
    for t,d in lis:
        if d == "U":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

for i in RD:
    lasu = float("-inf")
    lis = RD[i]
    lis.sort()
    for t,d in lis:
        if d == "R":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

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

Solution (Python):
import sys
from collections import defaultdict
from bisect import bisect_left, bisect_right
def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    airplane = {'U':[], 'R':[], 'D':[], 'L':[]}
    for _ in range(N):
        x, y, u = input().split()
        airplane[u].append((int(x), int(y)))
    out = float('inf')

    X = defaultdict(list)
    for x, y in airplane['U']: X[x].append((y, 1))
    for x, y in airplane['D']: X[x].append((y, -1))
    for x in X:
        X[x].sort()
        pre_y, pre_u = None, -2
        for y, u in X[x]:
            if pre_u > u: out = min(out, (y - pre_y) * 5)
            pre_y, pre_u = y, u

    Y = defaultdict(list)
    for x, y in airplane['R']: Y[y].append((x, 1))
    for x, y in airplane['L']: Y[y].append((x, -1))
    for y in Y:
        Y[y].sort()
        pre_x, pre_u = None, -2
        for x, u in Y[y]:
            if pre_u > u: out = min(out, (x - pre_x) * 5)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['U']: D[x + y].append((x, -1))
    for x, y in airplane['R']: D[x + y].append((x, 1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['D']: D[x + y].append((x, 1))
    for x, y in airplane['L']: D[x + y].append((x, -1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['D']: D[x - y].append((x, -1))
    for x, y in airplane['R']: D[x - y].append((x, 1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['U']: D[x - y].append((x, 1))
    for x, y in airplane['L']: D[x - y].append((x, -1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u
    if out == float('inf'):
        print("SAFE")
    else:
        print(out)


if __name__ == "__main__":
    main()

Solution (Python):
from collections import defaultdict
import heapq as hq
N = int(input())
dicUD = defaultdict(list)
dicRL = defaultdict(list)
dicRUp = defaultdict(list)
dicDLp = defaultdict(list)
dicRDm = defaultdict(list)
dicULm = defaultdict(list)
for i in range(N):
    X,Y,U = input().split()
    X,Y = map(int,(X,Y))
    if U == "L":
        hq.heappush(dicRL[Y],(X,"L"))
        hq.heappush(dicDLp[X+Y],(X-Y,"L"))
        hq.heappush(dicULm[X-Y],(X+Y,"L"))
    if U == "R":
        hq.heappush(dicRL[Y],(X,"R"))
        hq.heappush(dicRUp[X+Y],(X-Y,"R"))
        hq.heappush(dicRDm[X-Y],(X+Y,"R"))
    if U == "U":
        hq.heappush(dicUD[X],(Y,"R"))
        hq.heappush(dicRUp[X+Y],(X-Y,"L"))
        hq.heappush(dicULm[X-Y],(X+Y,"R"))
    if U == "D":
        hq.heappush(dicUD[X],(Y,"L"))
        hq.heappush(dicDLp[X+Y],(X-Y,"R"))
        hq.heappush(dicRDm[X-Y],(X+Y,"L"))
time = 10000000
for q in dicUD.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicRL.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicRUp.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicDLp.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicRDm.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicULm.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
if time == 10000000:
    print("SAFE")
else:
    print(time)

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
M = 200000
UD = [[] for _ in range(2 * M + 10)]
RL = [[] for _ in range(2 * M + 10)]

RU = [[] for _ in range(2 * M + 10)]
RD = [[] for _ in range(2 * M + 10)]
LU = [[] for _ in range(2 * M + 10)]
LD = [[] for _ in range(2 * M + 10)]

for _ in range(N):
    x, y, di = input().split()
    x, y = int(x), int(y)
    if di == "R":
        RL[y].append(x * 2)
        RU[x+y].append(x * 2)
        RD[x-y+M].append(x * 2)
    elif di == "L":
        RL[y].append(x * 2 + 1)
        LU[x-y+M].append(x * 2 + 1)
        LD[x+y].append(x * 2 + 1)
    elif di == "U":
        UD[x].append(y * 2)
        RU[x+y].append(x * 2 + 1)
        LU[x-y+M].append(x * 2)
    elif di == "D":
        UD[x].append(y * 2 + 1)
        RD[x-y+M].append(x * 2 + 1)
        LD[x+y].append(x * 2)

def chk(XX):
    def subchk(X):
        t = - (1 << 100)
        re = 1 << 100
        for x in sorted(X):
            a = x >> 1
            b = x & 1
            if b == 0:
                t = a
            else:
                re = min(re, a - t)
        return re * 10
    
    RE = 1 << 100
    for xx in XX:
        RE = min(RE, subchk(xx))
    return RE

ans = 1 << 100
ans = min(ans, chk(UD) // 2)
ans = min(ans, chk(RL) // 2)
ans = min(ans, chk(RU))
ans = min(ans, chk(RD))
ans = min(ans, chk(LU))
ans = min(ans, chk(LD))

print("SAFE" if ans > 1 << 80 else ans)