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 os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

N = int(input())
plane = []
for _ in range(N):
    xb,yb,ub = input().split()
    x = int(xb)
    y = int(yb)
    if ub == b'U':
        u = 'U'
    elif ub == b'R':
        u = 'R'
    elif ub == b'D':
        u = 'D'
    else:
        u = 'L'
    plane.append((x,y,u))


XR = []
XL = []
YU = []
YD = []
for i in range(200001):
    XR.append([])
    XL.append([])
    YU.append([])
    YD.append([])
for elem in plane:
    if elem[2] == 'U':
        YU[elem[0]].append(elem[1])
    if elem[2] == 'D':
        YD[elem[0]].append(elem[1])
    if elem[2] == 'L':
        XL[elem[1]].append(elem[0])
    if elem[2] == 'R':
        XR[elem[1]].append(elem[0])

        
for i in range(200001):
    XR[i].sort()
    XL[i].sort()
    YU[i].sort()
    YD[i].sort()

minTime = 4000000
for i in range(200001):
    indexR = 0
    indexL = 0
    while indexR < len(XR[i]) and indexL < len(XL[i]):
        if XR[i][indexR] > XL[i][indexL]:
            indexL += 1
        else:
            if (XL[i][indexL] - XR[i][indexR]) * 5 < minTime:
                minTime = (XL[i][indexL] - XR[i][indexR]) * 5
            indexR += 1
    
    indexU = 0
    indexD = 0
    while indexU < len(YU[i]) and indexD < len(YD[i]):
        if YU[i][indexU] > YD[i][indexD]:
            indexD += 1
        else:
            if (YD[i][indexD] - YU[i][indexU]) * 5 < minTime:
                minTime = (YD[i][indexD] - YU[i][indexU]) * 5
            indexU += 1



XYSumR = []
XYSumU = []
XYSumD = []
XYSumL = []

XYDiffR = []
XYDiffU = []
XYDiffD = []
XYDiffL = []

for i in range(400001):
    XYSumR.append([])
    XYSumU.append([])
    XYSumD.append([])
    XYSumL.append([])
    XYDiffR.append([])
    XYDiffU.append([])
    XYDiffD.append([])
    XYDiffL.append([])
for elem in plane:
    if elem[2] == 'U':
        XYSumU[elem[0] + elem[1]].append(elem[0])
        XYDiffU[elem[0] - elem[1] + 200000].append(elem[0])
    if elem[2] == 'D':
        XYSumD[elem[0] + elem[1]].append(elem[0])
        XYDiffD[elem[0] - elem[1] + 200000].append(elem[0])
    if elem[2] == 'L':
        XYSumL[elem[0] + elem[1]].append(elem[0])
        XYDiffL[elem[0] - elem[1] + 200000].append(elem[0])
    if elem[2] == 'R':
        XYSumR[elem[0] + elem[1]].append(elem[0])
        XYDiffR[elem[0] - elem[1] + 200000].append(elem[0])

for i in range(400001):
    XYSumU[i].sort()
    XYDiffU[i].sort()
    XYSumD[i].sort()
    XYDiffD[i].sort()
    XYSumL[i].sort()
    XYDiffL[i].sort()
    XYSumR[i].sort()
    XYDiffR[i].sort()

for i in range(400001):
    indexR = 0
    indexU = 0
    while indexR < len(XYSumR[i]) and indexU < len(XYSumU[i]):
        if XYSumU[i][indexU] > XYSumR[i][indexR]:
            if (XYSumU[i][indexU] - XYSumR[i][indexR]) * 10 < minTime:
                minTime = (XYSumU[i][indexU] - XYSumR[i][indexR]) * 10
            indexR += 1
        else:
            indexU += 1
    indexD = 0
    indexL = 0
    while indexL < len(XYSumL[i]) and indexD < len(XYSumD[i]):
        if XYSumD[i][indexD] > XYSumL[i][indexL]:
            indexL += 1
        else:
            if (XYSumL[i][indexL] - XYSumD[i][indexD]) * 10 < minTime:
                minTime = (XYSumL[i][indexL] - XYSumD[i][indexD]) * 10
            indexD += 1    
    indexL = 0
    indexU = 0
    while indexL < len(XYDiffL[i]) and indexU < len(XYDiffU[i]):
        if XYDiffU[i][indexU] > XYDiffL[i][indexL]:
            indexL += 1
        else:
            if (XYDiffL[i][indexL] - XYDiffU[i][indexU]) * 10 < minTime:
                minTime = (XYDiffL[i][indexL] - XYDiffU[i][indexU]) * 10
            indexU += 1
    indexR = 0
    indexD = 0
    while indexR < len(XYDiffR[i]) and indexD < len(XYDiffD[i]):
        if XYDiffR[i][indexR] > XYDiffD[i][indexD]:
            indexD += 1
        else:
            if (XYDiffD[i][indexD] - XYDiffR[i][indexR]) * 10 < minTime:
                minTime = (XYDiffD[i][indexD] - XYDiffR[i][indexR]) * 10
            indexR += 1

if minTime == 4000000:
    print("SAFE")
else:
    print(minTime)

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


def solve():
    N = int(readline())
    X = [0] * N
    Y = [0] * N
    U = [0] * N

    for i in range(N):
        x, y, u = readline().split()
        X[i] = int(x)
        Y[i] = int(y)
        U[i] = u
    
    ans = 10 ** 10

    _U,D,L,R = 'U','D','L','R'

    rs = [(X[i], Y[i]) for i in range(N) if U[i] == R]
    ls = [(X[i], Y[i]) for i in range(N) if U[i] == L]
    ans = min(ans, horizon(rs, ls))

    rs = [(Y[i], X[i]) for i in range(N) if U[i] == _U]
    ls = [(Y[i], X[i]) for i in range(N) if U[i] == D]
    ans = min(ans, horizon(rs, ls))


    
    rs = [(X[i], Y[i]) for i in range(N) if U[i] == R]
    ds = [(X[i], Y[i]) for i in range(N) if U[i] == D]
    ans = min(ans, cross(rs, ds))

    rs = [(X[i], -Y[i]) for i in range(N) if U[i] == R]
    ds = [(X[i], -Y[i]) for i in range(N) if U[i] == _U]
    ans = min(ans, cross(rs, ds))

    rs = [(-X[i], Y[i]) for i in range(N) if U[i] == L]
    ds = [(-X[i], Y[i]) for i in range(N) if U[i] == D]
    ans = min(ans, cross(rs, ds))

    rs = [(-X[i], -Y[i]) for i in range(N) if U[i] == L]
    ds = [(-X[i], -Y[i]) for i in range(N) if U[i] == _U]
    ans = min(ans, cross(rs, ds))

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


def horizon(rights, lefts):
    Y = {}
    for rx, ry in rights:
        if ry not in Y:
            Y[ry] = []
        Y[ry].append(rx)
    for k in Y:
        Y[k].sort()

    res = 10 ** 10
    
    for lx, ly in lefts:
        if ly not in Y:
            continue
        xs = Y[ly]
        t = bisect_right(xs, lx)
        if t == -1:
            continue
        else:
            res = min(res, (lx - xs[t]) * 5)
    
    return res

def bisect_right(xs, x):
    l, r = -1, len(xs)
    while l + 1 < r:
        m = (l + r) // 2
        if xs[m] < x:
            l = m
        else:
            r = m
    return l

def cross(rights, downs):
    x_seps = {}
    
    for x, y in rights:
        xsep = x - y
        if xsep not in x_seps:
            x_seps[xsep] = []
        
        x_seps[xsep].append(x)
    
    for k in x_seps:
        x_seps[k].sort()
    
    res = 10 ** 10

    for x, y in downs:
        xsep = x - y
        if xsep not in x_seps:
            continue
        xs = x_seps[xsep]
        t = bisect_right(xs, x)
        if t != -1:
            res = min(res, (x - xs[t]) * 10)

    return res

solve()

Solution (Python):

import sys

N, *XYU = map(str, sys.stdin.read().split())

UD = {}
UR = {}
UL = {}
DU = {}
DR = {}
DL = {}
RU = {}
RD = {}
RL = {}
LU = {}
LD = {}
LR = {}

for i in range(int(N)):
  X = int(XYU[3*i])
  Y = int(XYU[3*i+1])
  U = XYU[3*i+2]
  if U == 'U':
    if X in UD.keys():
      UD[X].append(Y)
    else:
      UD[X] = [Y]
    if X+Y in UR.keys():
      UR[X+Y].append(X)
    else:
      UR[X+Y] = [X]
    if X-Y in UL.keys():
      UL[X-Y].append(X)
    else:
      UL[X-Y] = [X]
  elif U == 'D':
    if X in DU.keys():
      DU[X].append(Y)
    else:
      DU[X] = [Y]
    if X+Y in DL.keys():
      DL[X+Y].append(X)
    else:
      DL[X+Y] = [X]
    if X-Y in DR.keys():
      DR[X-Y].append(X)
    else:
      DR[X-Y] = [X]
  elif U == 'R':
    if Y in RL.keys():
      RL[Y].append(X)
    else:
      RL[Y] = [X]
    if X+Y in RU.keys():
      RU[X+Y].append(X)
    else:
      RU[X+Y] = [X]
    if X-Y in RD.keys():
      RD[X-Y].append(X)
    else:
      RD[X-Y] = [X]
  else:
    if Y in LR.keys():
      LR[Y].append(X)
    else:
      LR[Y] = [X]
    if X+Y in LD.keys():
      LD[X+Y].append(X)
    else:
      LD[X+Y] = [X]
    if X-Y in LU.keys():
      LU[X-Y].append(X)
    else:
      LU[X-Y] = [X]

def dist(X,Y):
  minimum = -1
  X_len = len(X)
  X_index = 0
  Y_len = len(Y)
  Y_index = 0
  while X_index<X_len and Y_index<Y_len:
    x = X[X_index]
    y = Y[Y_index]
    if x<y:
      if minimum == -1:
        minimum = y-x
      else:
        minimum = min(minimum, y-x)
      X_index += 1
    else:
      Y_index += 1
  return minimum

second = -1

for x in UD.keys():
  if x in DU.keys():
    distance = dist(sorted(UD[x]),sorted(DU[x]))
    if distance>0:
      if second == -1:
        second = 5*distance
      else:
        second = min(second,5*distance)

for x in RL.keys():
  if x in LR.keys():
    distance = dist(sorted(RL[x]),sorted(LR[x]))
    if distance>0:
      if second == -1:
        second = 5*distance
      else:
        second = min(second,5*distance)

for x in UR.keys():
  if x in RU.keys():
    distance = dist(sorted(RU[x]),sorted(UR[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

for x in UL.keys():
  if x in LU.keys():
    distance = dist(sorted(UL[x]),sorted(LU[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

for x in RD.keys():
  if x in DR.keys():
    distance = dist(sorted(RD[x]),sorted(DR[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

for x in LD.keys():
  if x in DL.keys():
    distance = dist(sorted(DL[x]),sorted(LD[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

if second == -1:
  print('SAFE')
else:
  print(second)

Solution (Python):
import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict






def solve(grid):  
    console("----- solving ------")
    

    n_planes = []
    s_planes = []
    w_planes = []
    e_planes = []

    for a,b,c in grid:
        a, b = int(a), int(b)
        if c == "U":
            n_planes.append((a,b))
        if c == "D":
            s_planes.append((a,b))
        if c == "L":
            w_planes.append((a,b))
        if c == "R":
            e_planes.append((a,b))
        
    console(n_planes)
    console(s_planes)
    console(w_planes)
    console(e_planes)

    
    ns = collections.defaultdict(list)
    for a,b in n_planes:
        ns[a].append((b/2,1))
    for a,b in s_planes:
        ns[a].append((b/2,-1))
    
    ns = [(k,sorted(v)) for k,v in ns.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("ns", ns)

    
    ew = collections.defaultdict(list)
    for a,b in w_planes:
        ew[b].append((a/2,-1))
    for a,b in e_planes:
        ew[b].append((a/2,1))

    ew = [(k,sorted(v)) for k,v in ew.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("ew", ew)

    
    ne = collections.defaultdict(list)
    for a,b in n_planes:
        val = a+b
        ne[val].append((a,-1))
    for a,b in e_planes:
        val = a+b
        ne[val].append((a,1))

    ne = [(k,sorted(v)) for k,v in ne.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("ne", ne)

    
    sw = collections.defaultdict(list)
    for a,b in s_planes:
        val = -a-b
        sw[val].append((a,1))
    for a,b in w_planes:
        val = -a-b
        sw[val].append((a,-1))

    sw = [(k,sorted(v)) for k,v in sw.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("sw", sw)

    
    nw = collections.defaultdict(list)
    for a,b in n_planes:
        val = a-b
        nw[val].append((a,1))
    for a,b in w_planes:
        val = a-b
        nw[val].append((a,-1))

    nw = [(k,sorted(v)) for k,v in nw.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("nw", nw)

    
    se = collections.defaultdict(list)
    for a,b in s_planes:
        val = -a+b
        se[val].append((a,-1))
    for a,b in e_planes:
        val = -a+b
        se[val].append((a,1))

    se = [(k,sorted(v)) for k,v in se.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("se", se)

    minres = math.inf

    for c in [ns, ew, ne, sw, nw, se]:
        for _,v in c:
            
            
            for a,b in zip(v, v[1:]):
                
                
                if a[1] > b[1]:
                    
                    minres = min(minres, b[0] - a[0])
    
    if minres == math.inf:
        return "SAFE"
    return int(minres*10)


def console(*args):  
    
    return




for case_num in [1]:
    
    

    
    nrows = int(input())
    
    
    

    
    

    
    
    
    grid = []
    for _ in range(nrows):
        grid.append(input().split())

    res = solve(grid)  
    
    
    

    
    print(res)

Solution (Python):
import sys

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
    n = ni()
    s = 'UDLR'
    g = [list() for _ in range(4)]
    for _ in range(n):
        x, y, u = input().split()
        g[s.index(u)].append((int(x), int(y)))


    def calc(a, b):
        a.sort()
        b.sort()
        idx = 0
        m = len(b)
        res = 10 ** 9
        for x, y in a:
            while idx < m and (b[idx][0] < x or b[idx][0] == x and b[idx][1] < y):
                idx += 1
            if idx >= m:
                break
            if b[idx][0] == x and b[idx][1] >= y:
                res = min(res, b[idx][1] - y)
        return res * 5

    res1 = calc(g[0], g[1])
    res2 = calc([(y, x) for x, y in g[3]], [(y, x) for x, y in g[2]])
    res3 = calc([(x+y, x-y) for x, y in g[3]], [(x+y, x-y) for x, y in g[0]])
    res4 = calc([(x+y, x-y) for x, y in g[1]], [(x+y, x-y) for x, y in g[2]])
    res5 = calc([(x-y, x+y) for x, y in g[0]], [(x-y, x+y) for x, y in g[2]])
    res6 = calc([(x-y, x+y) for x, y in g[3]], [(x-y, x+y) for x, y in g[1]])
    ans = min(res1, res2, res3, res4, res5, res6)
    if ans > 10**9:
        print('SAFE')
    else:
        print(ans)
    return

solve()

Solution (Python):
import sys
from collections import defaultdict
def smin(x,y):
    if x>y:
        return y
    else:
        return x

sys.setrecursionlimit(500000)
def input():
    return sys.stdin.readline()[:-1]

def main():
    N = int(input())

    dd = defaultdict(list)
    ans = 10**27

    for i in range(N):
        x,y,u = input().split()
        x,y = int(x),int(y)
        dd[u].append((x,y))

    dd_u = defaultdict(list)

    for x,y in dd["U"]:
        dd_u[x].append((y,"U"))

    for x,y in dd["D"]:
        if x in dd_u:
            dd_u[x].append((y,"D"))

    for x in dd_u:
        dd_u[x].sort()
        for i in range(len(dd_u[x])-1):
            if dd_u[x][i][1]=="U" and dd_u[x][i+1][1]=="D":
                ans = smin((dd_u[x][i+1][0]-dd_u[x][i][0])/2,ans)

    dd_l = defaultdict(list)

    for x,y in dd["L"]:
        dd_l[y].append((x,"L"))

    for x,y in dd["R"]:
        if y in dd_l:
            dd_l[y].append((x,"R"))

    for y in dd_l:
        dd_l[y].sort()
        for i in range(len(dd_l[y])-1):
            if dd_l[y][i][1]=="R" and dd_l[y][i+1][1]=="L":
                ans = smin((dd_l[y][i+1][0]-dd_l[y][i][0])/2,ans)

    dd_v = defaultdict(list)

    for x,y in dd["U"]:
        v = y-x
        dd_v[v].append((x+y,"U"))

    for x,y in dd["L"]:
        v = y-x
        if v in dd_v:
            dd_v[v].append((x+y,"L"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="U" and dd_v[v][i+1][1]=="L":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)

    dd_v = defaultdict(list)

    for x,y in dd["U"]:
        v = y+x
        dd_v[v].append((x-y,"U"))

    for x,y in dd["R"]:
        v = y+x
        if v in dd_v:
            dd_v[v].append((x-y,"R"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="R" and dd_v[v][i+1][1]=="U":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)


    dd_v = defaultdict(list)

    for x,y in dd["D"]:
        v = y-x
        dd_v[v].append((x+y,"D"))

    for x,y in dd["R"]:
        v = y-x
        if v in dd_v:
            dd_v[v].append((x+y,"R"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="R" and dd_v[v][i+1][1]=="D":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)

    dd_v = defaultdict(list)

    for x,y in dd["D"]:
        v = y+x
        dd_v[v].append((x-y,"D"))

    for x,y in dd["L"]:
        v = y+x
        if v in dd_v:
            dd_v[v].append((x-y,"L"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="D" and dd_v[v][i+1][1]=="L":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)

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


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
PU = []
PR = []
PD = []
PL = []
P = {'U':PU, 'R':PR, 'D':PD, 'L':PL}
for _ in range(N):
    X, Y, U = input().split()
    P[U].append((int(X), int(Y)))

ans = 100000000
    

DU = {}
for x, y in PU:
    if x not in DU: DU[x] = []
    DU[x].append(y)

DD = {}
for x, y in PD:
    if x not in DD: DD[x] = []
    DD[x].append(y)

for x, p1 in DU.items():
    if x not in DD: continue
    p2 = DD[x]
    
    p1.sort()
    p2.sort()
    n = len(p2)
    i = 0
    for z in p1:
        while i<n and p2[i]<=z: i+=1
        if i==n: break
        ans = min(ans, (p2[i]-z)*5)


DR = {}
for x, y in PR:
    if y not in DR: DR[y] = []
    DR[y].append(x)

DL = {}
for x, y in PL:
    if y not in DL: DL[y] = []
    DL[y].append(x)

for y, p1 in DR.items():
    if y not in DL: continue
    p2 = DL[y]

    p1.sort()
    p2.sort()
    n = len(p2)
    i = 0
    for z in p1:
        while i<n and p2[i]<=z: i+=1
        if i==n: break
        ans = min(ans, (p2[i]-z)*5)


DR = {}
for x, y in PR:
    if x+y not in DR: DR[x+y] = []
    DR[x+y].append(x)

DU = {}
for x, y in PU:
    if x+y not in DU: DU[x+y] = []
    DU[x+y].append(x)

for key, p1 in DR.items():
    if key not in DU: continue
    p2 = DU[key]

    p1.sort()
    p2.sort()
    n = len(p2)
    i = 0
    for z in p1:
        while i<n and p2[i]<=z: i+=1
        if i==n: break
        ans = min(ans, (p2[i]-z)*10)


DD = {}
for x, y in PD:
    if x+y not in DD: DD[x+y] = []
    DD[x+y].append(x)

DL = {}
for x, y in PL:
    if x+y not in DL: DL[x+y] = []
    DL[x+y].append(x)

for key, p1 in DD.items():
    if key not in DL: continue
    p2 = DL[key]

    p1.sort()
    p2.sort()
    n = len(p2)
    i = 0
    for z in p1:
        while i<n and p2[i]<=z: i+=1
        if i==n: break
        ans = min(ans, (p2[i]-z)*10)


DR = {}
for x, y in PR:
    if x-y not in DR: DR[x-y] = []
    DR[x-y].append(x)

DD = {}
for x, y in PD:
    if x-y not in DD: DD[x-y] = []
    DD[x-y].append(x)

for key, p1 in DR.items():
    if key not in DD: continue
    p2 = DD[key]

    p1.sort()
    p2.sort()
    n = len(p2)
    i = 0
    for z in p1:
        while i<n and p2[i]<=z: i+=1
        if i==n: break
        ans = min(ans, (p2[i]-z)*10)


DU = {}
for x, y in PU:
    if x-y not in DU: DU[x-y] = []
    DU[x-y].append(x)

DL = {}
for x, y in PL:
    if x-y not in DL: DL[x-y] = []
    DL[x-y].append(x)

for key, p1 in DU.items():
    if key not in DL: continue
    p2 = DL[key]

    p1.sort()
    p2.sort()
    n = len(p2)
    i = 0
    for z in p1:
        while i<n and p2[i]<=z: i+=1
        if i==n: break
        ans = min(ans, (p2[i]-z)*10)
        

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

Solution (Python):
N, = map(int, input().split())
from collections import defaultdict
D = defaultdict(lambda : defaultdict(list))
D2 = defaultdict(lambda : defaultdict(list))

def Fm(d1, d2):
    alist = D[d1]
    blist = D[d2]
    R = 10**18
    for key in alist:
        if key not in blist:
            continue
        A, B = alist[key], blist[key]
        X=sorted(A+B, key=lambda x:x[0])
        for a, b in zip(X, X[1:]):
            if a[2] != b[2] and (a[2] == "R" or a[2] == "D"):
                R = min(R, 10*(b[0]-a[0]))
    return R

def Fm2(d1, d2):
    alist = D2[d1]
    blist = D2[d2]
    R = 10**18
    for key in alist:
        if key not in blist:
            continue
        A, B = alist[key], blist[key]
        X=sorted(A+B, key=lambda x:x[0])
        for a, b in zip(X, X[1:]):
            if a[2] != b[2] and (a[2] == "R" or a[2] == "U"):
                R = min(R, 10*(b[0]-a[0]))
    return R


Dx = defaultdict(list)
Dy = defaultdict(list)
for _ in range(N):
    x, y, d = input().split()
    x, y = int(x), int(y)
    D[d][x+y].append((x, y, d))
    D2[d][x-y].append((x, y, d))
    if d in {"R", "L"}:
        Dx[y].append((x, d))
    else:
        Dy[x].append((y, d))

R = 10**18
for key in Dx:
    X = sorted(Dx[key])
    for (x, d), (xx, d2) in zip(X, X[1:]):
        if d == "R" and d2 == "L":
            R = min(R, (xx-x)*5)
for key in Dy:
    X = sorted(Dy[key])
    for (x, d), (xx, d2) in zip(X, X[1:]):
        if d == "U" and d2 == "D":
            R = min(R, (xx-x)*5)

R = min(R, Fm("D", "L"))
R = min(R, Fm("U", "R"))
R = min(R, Fm2("D", "R"))
R = min(R, Fm2("U", "L"))
if R != 10**18:
    print(R)
else:
    print("SAFE")

Solution (Python):
import sys
from collections import defaultdict
range = xrange
input = raw_input

inp = sys.stdin.read().split(); ii = 0

mapper = {'U':0, 'D':1, 'R':2, 'L':3}

n = int(inp[ii]); ii += 1
X = []
Y = []
D = []
for _ in range(n):
    x = int(inp[ii]); ii += 1
    y = int(inp[ii]); ii += 1
    d = mapper[inp[ii]]; ii += 1
    
    X.append(x)
    Y.append(y)
    D.append(d)

listdict = lambda: defaultdict(list)

Y0 = listdict()
Y1 = listdict() 
X2 = listdict() 
X3 = listdict() 

pos0 = listdict() 
pos1 = listdict() 
pos2 = listdict() 
pos3 = listdict() 

neg0 = listdict()
neg1 = listdict() 
neg2 = listdict()
neg3 = listdict()

Xset = set()
Yset = set()
posset = set()
negset = set()

for i in range(n):
    d = D[i]
    x = X[i]
    y = Y[i]

    pos = x+y
    neg = x-y

    Xset.add(x)
    Yset.add(y)
    posset.add(pos)
    negset.add(neg)

    if d == 0:
        Y0[x].append(y)
        pos0[pos].append(2 * x)
        neg0[neg].append(2 * x)
    elif d == 1:
        Y1[x].append(y)
        pos1[pos].append(2 * x)
        neg1[neg].append(2 * x)
    elif d == 2:
        X2[y].append(x)
        pos2[pos].append(2 * x)
        neg2[neg].append(2 * x)
    elif d == 3:
        X3[y].append(x)
        pos3[pos].append(2 * x)
        neg3[neg].append(2 * x)
    else:
        assert False

def sorter(A):
    for a in A.values():
        a.sort()

sorter(Y0)
sorter(Y1)
sorter(X2)
sorter(X3)

sorter(pos0)
sorter(pos1)
sorter(pos2)
sorter(pos3)

sorter(neg0)
sorter(neg1)
sorter(neg2)
sorter(neg3)

best = -1
def check(A0, A1):
    
    global best
    i = 0
    n = len(A1)
    for a in A0:
        while i < n and a >= A1[i]:
            i += 1
        if i == n:
            break
        score = (A1[i] - a) * 5
        if best == -1 or best > score:
            best = score

















for x in Xset:
    check(Y0[x], Y1[x])
for y in Yset:
    check(X2[y], X3[y])

for neg in negset:
    check(neg2[neg], neg1[neg])
    check(neg0[neg], neg3[neg])

for pos in posset:
    check(pos2[pos], pos0[pos])
    check(pos1[pos], pos3[pos])

print 'SAFE' if best == -1 else best

Solution (Python):
check=200000

import sys

input=sys.stdin.readline

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

ans=10**18


DR=D+R
DR.sort()
data=[[] for i in range(2*check+1)]
for x,y,u in DR:
    t=y-x+check
    if u=="R":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*x-2*X)


DL=D+L
DL.sort(reverse=True)
data=[[] for i in range(2*check+1)]
for x,y,u in DL:
    t=x+y
    if u=="L":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*X-2*x)


UR=U+R
UR.sort()
data=[[] for i in range(2*check+1)]
for x,y,u in UR:
    t=x+y
    if u=="R":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*x-2*X)


UL=U+L
UL.sort(reverse=True)
data=[[] for i in range(2*check+1)]
for x,y,u in UL:
    t=y-x+check
    if u=="L":
        data[t].append(x)
    else:
        if data[t]:
            X=data[t][-1]
            ans=min(ans,2*X-2*x)


UD=U+D
UD.sort(key=lambda x:x[1])
data=[[] for i in range(check+1)]
for x,y,u in UD:
    if u=="U":
        data[x].append(y)
    else:
        if data[x]:
            Y=data[x][-1]
            ans=min(ans,(y-Y))


LR=L+R
LR.sort()
data=[[] for i in range(check+1)]
for x,y,u in LR:
    if u=="R":
        data[y].append(x)
    else:
        if data[y]:
            X=data[y][-1]
            ans=min(ans,(x-X))

if ans==10**18:
    print("SAFE")
    exit()
print(int(ans*5))

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-1]
N=int(input())
t=[[] for i in range(200001)]
y=[[] for i in range(200001)]
pl=[[] for i in range(400001)]
ml=[[] for i in range(400001)]
pr=[[] for i in range(400001)]
mr=[[] for i in range(400001)]
for i in range(N):
    X,Y,U=input().split()
    X=int(X)
    Y=int(Y)
    if U=="U":
        t[X].append((Y,1))
        pl[X-Y].append((X,1))
        mr[X+Y].append((X,0))
    elif U=="D":
        t[X].append((Y,0))
        pr[X-Y].append((X,0))
        ml[X+Y].append((X,1))
    elif U=="L":
        y[Y].append((X,0))
        pl[X-Y].append((X,0))
        ml[X+Y].append((X,0))
    else:
        y[Y].append((X,1))
        pr[X-Y].append((X,1))
        mr[X+Y].append((X,1))
a=3000000
for i in t:
    if not i:
        continue
    i.sort()
    c=-1000001
    for j in i:
        if j[1]:
            c=j[0]
        else:
            p=(j[0]-c)*5
            if p<a:
                a=p
for i in y:
    if not i:
        continue
    i.sort()
    c=-1000001
    for j in i:
        if j[1]:
            c=j[0]
        else:
            p=(j[0]-c)*5
            if p<a:
                a=p
for i in pl:
    if not i:
        continue
    i.sort()
    c=-2000001
    for j in i:
        if j[1]:
            c=j[0]
        else:
            p=(j[0]-c)*10
            if p<a:
                a=p
for i in pr:
    if not i:
        continue
    i.sort()
    c=-2000001
    for j in i:
        if j[1]:
            c=j[0]
        else:
            p=(j[0]-c)*10
            if p<a:
                a=p
for i in mr:
    if not i:
        continue
    i.sort()
    c=-2000001
    for j in i:
        if j[1]:
            c=j[0]
        else:
            p=(j[0]-c)*10
            if p<a:
                a=p
for i in ml:
    if not i:
        continue
    i.sort()
    c=-2000001
    for j in i:
        if j[1]:
            c=j[0]
        else:
            p=(j[0]-c)*10
            if p<a:
                a=p
if a==3000000:
    print("SAFE")
else:
    print(a)

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
xyu = [None]*n
from collections import defaultdict
dx = defaultdict(list)
dy = defaultdict(list)
dxpy = defaultdict(list)
dxmy = defaultdict(list)
for i in range(n):
    x,y,u = input().split()
    x,y = (int(x), int(y))
    dx[x].append((y, u))
    dy[y].append((x, u))
    dxpy[x+y].append((x,u))
    dxmy[x-y].append((x,u))

def sub(maru, batu):
    ans = float("inf")
    if not maru or not batu:
        return ans
    maru.sort()
    batu.sort()
    j = -1
    for i in range(len(batu)):
        while j+1<len(maru) and maru[j+1]<=batu[i]:
            j += 1
        if j<len(maru) and -maru[j]+batu[i]>=0:
            ans = min(ans, -maru[j]+batu[i])








    return ans
ans = float("inf")
for v in dy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*5)
for v in dx.values():
    maru = [item[0] for item in v if item[1]=="U"]
    batu = [item[0] for item in v if item[1]=="D"]
    ans = min(ans, sub(maru, batu)*5)
for v in dxpy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="U"]
    ans = min(ans, sub(maru, batu)*10)
    maru = [item[0] for item in v if item[1]=="D"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*10)
for v in dxmy.values():
    maru = [item[0] for item in v if item[1]=="R"]
    batu = [item[0] for item in v if item[1]=="D"]
    ans = min(ans, sub(maru, batu)*10)
    maru = [item[0] for item in v if item[1]=="U"]
    batu = [item[0] for item in v if item[1]=="L"]
    ans = min(ans, sub(maru, batu)*10)
if ans==float("inf"):
    ans = "SAFE"
print(ans)