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
from collections import defaultdict
import bisect

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

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


def main():

    N = in_n()

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

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

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

    INF = 10**18
    ans = INF

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

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

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

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

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

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

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

    for k in XYp.keys():

        
        
        
        

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

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

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

    for k in XYm.keys():

        
        
        
        

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

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

    
    
    
    

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


if __name__ == '__main__':
    main()

Solution (Python):
from 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 dic in (dicUD,dicRL,dicRUp,dicDLp,dicRDm,dicULm):
    for q in dic.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):
n = int(input())
xyu = []
for i in range(n):
    x, y, u = map(str, input().split())
    x = int(x)
    y = int(y)
    xyu.append( (x, y, u) )

axisx = [[] for _ in range(200001)]
axisy = [[] for _ in range(200001)]
axislb = [[] for _ in range(400001)]
axislt = [[] for _ in range(400001)]

for x, y, u in xyu:
    if u == 'U' or u == 'D':
        axisx[x].append( (y, u) )
    elif u == 'L' or u == 'R':
        axisy[y].append( (x, u) )
    axislb[x+y].append( (x, u) )
    axislt[x-y+200000].append( (x, u) )

m = 100000000

for i in range(200001):
    if axisx[i]:
        axisx[i] = sorted(axisx[i])
        
        d = None
        pos = None
        for y, u in axisx[i]:
            if d is None:
                if u == 'U':
                    d = 'U'
                    pos = y
            elif d == 'U':
                if u == 'U':
                    pos = y
                else:
                    m = min((y - pos)*5, m)
                    d = None
                    pos = None

for i in range(200001):
    if axisy[i]:
        axisy[i] = sorted(axisy[i])
        
        d = None
        pos = None
        for x, u in axisy[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                else:
                    m = min((x - pos)*5, m)
                    d = None
                    pos = None

for i in range(400001):
    if axislb[i]:
        axislb[i] = sorted(axislb[i])
        
        d = None
        pos = None
        for x, u in axislb[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                elif u == 'U':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None
        d = None
        pos = None
        for x, u in axislb[i]:
            if d is None:
                if u == 'D':
                    d = 'D'
                    pos = x
            elif d == 'D':
                if u == 'D':
                    pos = x
                elif u == 'L':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None

for i in range(400001):
    if axislt[i]:
        axislt[i] = sorted(axislt[i])
        
        d = None
        pos = None
        for x, u in axislt[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                elif u == 'D':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None
        d = None
        pos = None
        for x, u in axislt[i]:
            if d is None:
                if u == 'U':
                    d = 'U'
                    pos = x
            elif d == 'U':
                if u == 'U':
                    pos = x
                elif u == 'L':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None

if m == 100000000:
    print('SAFE')
else:
    print(m)

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

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [list(map(str, input().split())) for _ in range(row)]
        return map(list, zip(*read_all))



N = I()
X,Y,U = LIR(N,3)
X = [int(x) for x in X]
Y = [int(y) for y in Y]

d1 = defaultdict(lambda:defaultdict(list))
d2 = defaultdict(lambda:defaultdict(list))

u = defaultdict(list)
r = defaultdict(list)
d = defaultdict(list)
l = defaultdict(list)

for i in range(N):
    if U[i] == 'U':
        u[X[i]].append(Y[i])
    elif U[i] == 'D':
        d[X[i]].append(Y[i])
    elif U[i] == 'R':
        r[Y[i]].append(X[i])
    else:
        l[Y[i]].append(X[i])

for k in u.keys():
    u[k].sort()

for k in d.keys():
    d[k].sort()

for k in r.keys():
    r[k].sort()

for k in l.keys():
    l[k].sort()

for i in range(N):
    d1[U[i]][Y[i]-X[i]].append(X[i])
    d2[U[i]][Y[i]+X[i]].append(X[i])

ans = float('inf')
for i in range(N):
    if U[i] == 'U':
        p = bisect_left(d[X[i]],Y[i])
        if p <= len(d[X[i]])-1 and len(d[X[i]]):
            ans = min(ans,(d[X[i]][p]-Y[i])*5)

        p = bisect_left(d1['L'][Y[i]-X[i]],X[i])
        if p <= len(d1['L'][Y[i]-X[i]])-1 and len(d1['L'][Y[i]-X[i]]):
            ans = min(ans,(d1['L'][Y[i]-X[i]][p]-X[i])*10)  

        p = bisect_left(d2['R'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d2['R'][Y[i]+X[i]])-1 and len(d2['R'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d2['R'][Y[i]+X[i]][p-1])*10)

    elif U[i] == 'D':
        p = bisect_left(u[X[i]],Y[i])
        if 0 <= p-1 <= len(u[X[i]])-1 and len(u[X[i]]):
            ans = min(ans,(Y[i]-u[X[i]][p-1])*5)

        p = bisect_left(d1['R'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d1['R'][Y[i]-X[i]])-1 and len(d1['R'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d1['R'][Y[i]-X[i]][p-1])*10)       

        p = bisect_left(d2['L'][Y[i]+X[i]],X[i])
        if p <= len(d2['L'][Y[i]+X[i]])-1 and len(d2['L'][Y[i]+X[i]]):
            ans = min(ans,(d2['L'][Y[i]+X[i]][p]-X[i])*10)

    elif U[i] == 'R':
        p = bisect_left(l[Y[i]],X[i])
        if p <= len(l[Y[i]])-1 and len(l[Y[i]]):
            ans = min(ans,(l[Y[i]][p]-X[i])*5)

        p = bisect_left(d1['D'][Y[i]-X[i]],X[i])
        if p <= len(d1['D'][Y[i]-X[i]])-1 and len(d1['D'][Y[i]-X[i]]):
            ans = min(ans,(d1['D'][Y[i]-X[i]][p]-X[i])*10)       

        p = bisect_left(d2['U'][Y[i]+X[i]],X[i])
        if p <= len(d2['U'][Y[i]+X[i]])-1 and len(d2['U'][Y[i]+X[i]]):
            ans = min(ans,(d2['U'][Y[i]+X[i]][p]-X[i])*10)

    else:
        p = bisect_left(r[Y[i]],X[i])
        if 0 <= p-1 <= len(r[Y[i]])-1 and len(r[Y[i]]):
            ans = min(ans,(X[i]-r[Y[i]][p-1])*5)

        p = bisect_left(d1['U'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d1['U'][Y[i]-X[i]])-1 and len(d1['U'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d1['U'][Y[i]-X[i]][p-1])*10)

        p = bisect_left(d2['D'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d2['D'][Y[i]+X[i]])-1 and len(d2['D'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d2['D'][Y[i]+X[i]][p-1])*10)


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

Solution (Python):
n = int(input())
A = [list(input().split()) for i in range(n)]
l = 2*10**5 + 5



D = [[[] for j in range(2*l)] for i in range(4)]





for i in range(n):
    x = int(A[i][0])
    y = int(A[i][1])
    nn = [x,y,A[i][2]]
    D[0][x].append(nn)
    D[1][y].append(nn)
    D[2][x+y].append(nn)
    D[3][x-y+l].append(nn)


import bisect
ans = float("inf")
for i in range(l):
    
    LR = [[], []]
    for j in range(len(D[1][i])):
        
        if D[1][i][j][2] == "L":
            LR[0].append(D[1][i][j][0])
        if D[1][i][j][2] == "R":
            LR[1].append(D[1][i][j][0])
    LR[0].sort()
    LR[1].sort()
        
    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, (LR[0][ind]-LR[1][k]) * 5)

for i in range(l):
    
    LR = [[], []]
    for j in range(len(D[0][i])):
        
        if D[0][i][j][2] == "U":
            LR[0].append(D[0][i][j][1])
        if D[0][i][j][2] == "D":
            LR[1].append(D[0][i][j][1])
    LR[0].sort()
    LR[1].sort()
        
    for k in range(len(LR[0])):
        ind = bisect.bisect(LR[1], LR[0][k])
        
        if ind != len(LR[1]):
            ans = min(ans, (LR[1][ind]-LR[0][k]) * 5)

for i in range(2*l):
    
    LR = [[], []]
    LR2 = [[], []]
    for j in range(len(D[2][i])):
        
        if D[2][i][j][2] == "L":
            LR[0].append(D[2][i][j][0])
        if D[2][i][j][2] == "D":
            LR[1].append(D[2][i][j][0])

        if D[2][i][j][2] == "U":
            LR2[0].append(D[2][i][j][0])
        if D[2][i][j][2] == "R":
            LR2[1].append(D[2][i][j][0])
        

    
    LR[0].sort()
    LR2[0].sort()
    LR[1].sort()
    LR2[1].sort()

    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, (LR[0][ind]-LR[1][k]) * 10)
    
    for k in range(len(LR2[1])):
        ind = bisect.bisect(LR2[0], LR2[1][k])
        if ind != len(LR2[0]):
            ans = min(ans, (LR2[0][ind]-LR2[1][k]) * 10)

for i in range(2*l):
    
    LR = [[], []]
    LR2 = [[], []]
    for j in range(len(D[3][i])):
        
        if D[3][i][j][2] == "D":
            LR[0].append(D[3][i][j][0])
        if D[3][i][j][2] == "R":
            LR[1].append(D[3][i][j][0])

        if D[3][i][j][2] == "L":
            LR2[0].append(D[3][i][j][0])
        if D[3][i][j][2] == "U":
            LR2[1].append(D[3][i][j][0])
    
    LR[0].sort()
    LR2[0].sort()
    LR[1].sort()
    LR2[1].sort()

        
    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, (LR[0][ind]-LR[1][k]) * 10)
    
    for k in range(len(LR2[1])):
        ind = bisect.bisect(LR2[0], LR2[1][k])
        if ind != len(LR2[0]):
            ans = min(ans, (LR2[0][ind]-LR2[1][k]) * 10)


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

Solution (Python):
from collections import deque, Counter, defaultdict
from itertools import chain, combinations
import json

import bisect
import sys
import math
import bisect
from functools import lru_cache
import itertools

sys.setrecursionlimit(10 ** 8)

M = 10 ** 9 + 7
INF = 10 ** 17


def main():
    N = int(input())
    XYU = [
        [a for a in input().split()]
        for _ in range(N)
    ]

    
    
    

    up = []
    down = []
    right = []
    left = []
    for xi, yi, ui in XYU:
        if ui == 'U':
            up.append((int(xi), int(yi)))
            continue
        if ui == 'D':
            down.append((int(xi), int(yi)))
            continue
        if ui == 'R':
            right.append((int(xi), int(yi)))
            continue
        if ui == 'L':
            left.append((int(xi), int(yi)))
            continue

    def a():
        conflict = 10 ** 50
        xtable = {}
        for xi, yi in down:
            if xi not in xtable:
                xtable[xi] = []
            ind = bisect.bisect_left(xtable[xi], yi)
            xtable[xi].insert(ind, yi)
        for xi, yi in up:
            if xi in xtable:
                ind = bisect.bisect_left(xtable[xi], yi)
                if ind != len(xtable[xi]):
                    conflict = min(conflict, (xtable[xi][ind] - yi) * 5)
        ytable = {}
        for xi, yi in left:
            if yi not in ytable:
                ytable[yi] = []
            ind = bisect.bisect_left(ytable[yi], xi)
            ytable[yi].insert(ind, xi)
        for xi, yi in right:
            if yi in ytable:
                ind = bisect.bisect_left(ytable[yi], xi)
                if ind != len(ytable[yi]):
                    conflict = min(conflict, (ytable[yi][ind] - xi) * 5)
        return conflict

    left_l1 = {}
    left_l2 = {}
    for xi, yi in left:
        v1 = yi - xi
        if v1 not in left_l1:
            left_l1[v1] = []
        ind = bisect.bisect_left(left_l1[v1], xi)
        left_l1[v1].insert(ind, xi)

        v2 = xi + yi
        if v2 not in left_l2:
            left_l2[v2] = []
        ind = bisect.bisect_left(left_l2[v2], xi)
        left_l2[v2].insert(ind, xi)

    right_l1 = {}
    right_l2 = {}
    for xi, yi in right:
        v1 = yi - xi
        if v1 not in right_l1:
            right_l1[v1] = []
        ind = bisect.bisect_left(right_l1[v1], xi)
        right_l1[v1].insert(ind, xi)

        v2 = xi + yi
        if v2 not in right_l2:
            right_l2[v2] = []
        ind = bisect.bisect_left(right_l2[v2], xi)
        right_l2[v2].insert(ind, xi)

    conflict = a()

    for xi, yi in up:
        v1 = yi - xi
        v2 = xi + yi
        if v1 in left_l1:
            l = left_l1[v1]
            ind = bisect.bisect_left(l, xi)
            if ind != len(l):
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
        if v2 in right_l2:
            l = right_l2[v2]
            ind = bisect.bisect_right(l, xi)
            if ind != 0:
                xx = l[ind - 1]
                conflict = min(conflict, abs(xx - xi) * 10)
    for xi, yi in down:
        v1 = yi - xi
        v2 = xi + yi
        if v1 in right_l1:
            l = right_l1[v1]
            ind = bisect.bisect_right(l, xi)
            if ind != 0:
                xx = l[ind - 1]
                conflict = min(conflict, abs(xx - xi) * 10)
        if v2 in left_l2:
            l = left_l2[v2]
            ind = bisect.bisect_left(l, xi)
            if ind != len(l):
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
    if conflict == 10 ** 50:
        print('SAFE')
        return
    print(conflict)


if __name__ == "__main__":
    main()

Solution (Python):
from collections import defaultdict as dd
from bisect import bisect_left, bisect

def stc(L, R, mp):
    m = 10**20
    for y, ll in L.items():
        if y not in R:
            continue
        ll.sort()
        for r in R[y]:
            i = bisect(ll, r)
            if i == len(ll):
                continue
            m = min(m, ll[i] - r)
    return m * mp


def main():
    N = int(input())
    UL, UR, DL, DR = dd(list), dd(list), dd(list), dd(list)
    ULa, URa, DLa, DRa = dd(list), dd(list), dd(list), dd(list)
    D, U, L, R = dd(list), dd(list), dd(list), dd(list)
    for _ in range(N):
        _x, _y, u = input().split()
        x, y = int(_x), int(_y)
        if u == 'U':
            UL[x - y].append(x)
            UR[x + y].append(x)
            U[x].append(y)
        elif u == 'D':
            DL[x + y].append(x)
            DR[x - y].append(x)
            D[x].append(y)
        elif u == 'L':
            ULa[x - y].append(x)
            DLa[x + y].append(x)
            L[y].append(x)
        else:
            URa[x + y].append(x)
            DRa[x - y].append(x)
            R[y].append(x)
    m = 10 ** 20
    m = min(m, stc(L, R, 5))
    m = min(m, stc(D, U, 5))
    m = min(m, stc(ULa, UL, 10))
    m = min(m, stc(UR, URa, 10))
    m = min(m, stc(DLa, DL, 10))
    m = min(m, stc(DR, DRa, 10))
    print('SAFE' if m >= 10 ** 20 else m)

main()

Solution (Python):
mod = 1000000007
eps = 10**-9


def main():
    import sys
    from collections import defaultdict
    input = sys.stdin.readline

    N = int(input())
    Uxy = [[] for _ in range(10**6)]
    Rxy = [[] for _ in range(10**6)]
    Dxy = [[] for _ in range(10**6)]
    Lxy = [[] for _ in range(10**6)]
    Ux_y = [[] for _ in range(10 ** 6)]
    Rx_y = [[] for _ in range(10 ** 6)]
    Dx_y = [[] for _ in range(10 ** 6)]
    Lx_y = [[] for _ in range(10 ** 6)]
    Ux = [[] for _ in range(10 ** 6)]
    Ry = [[] for _ in range(10 ** 6)]
    Dx = [[] for _ in range(10 ** 6)]
    Ly = [[] for _ in range(10 ** 6)]
    Xall = set()
    Yall = set()
    XYall = set()
    X_Yall = set()
    for _ in range(N):
        x, y, d = input().split()
        x = int(x)
        y = int(y)
        Xall.add(x)
        Yall.add(y)
        XYall.add(x+y)
        X_Yall.add(x-y)
        if d == "U":
            Uxy[x+y].append((x, y))
            Ux_y[x-y].append((x, y))
            Ux[x].append(y)
        elif d == "R":
            Rxy[x + y].append((x, y))
            Rx_y[x - y].append((x, y))
            Ry[y].append(x)
        elif d == "D":
            Dxy[x + y].append((x, y))
            Dx_y[x - y].append((x, y))
            Dx[x].append(y)
        else:
            Lxy[x + y].append((x, y))
            Lx_y[x - y].append((x, y))
            Ly[y].append(x)

    ans = 10**9
    
    for y in Yall:
        if len(Ry[y]) > 0 and len(Ly[y]) > 0:
            A = []
            for x in Ry[y]:
                A.append((x, 1))
            for x in Ly[y]:
                A.append((x, -1))
            A.sort(key=lambda p: p[0])
            for i in range(len(A) - 1):
                if A[i][1] == 1 and A[i+1][1] == -1:
                    ans = min(ans, (A[i+1][0] - A[i][0]) * 5)

    
    for x in Xall:
        if len(Ux[x]) > 0 and len(Dx[x]) > 0:
            A = []
            for y in Ux[x]:
                A.append((y, 1))
            for y in Dx[x]:
                A.append((y, -1))
            A.sort(key=lambda p: p[0])
            for i in range(len(A) - 1):
                if A[i][1] == 1 and A[i+1][1] == -1:
                    ans = min(ans, (A[i+1][0] - A[i][0]) * 5)

    
    for xy in XYall:
        A = []
        for x, y in Uxy[xy]:
            A.append((x, y, "U"))
        for x, y in Rxy[xy]:
            A.append((x, y, "R"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "R" and A[i+1][2] == "U":
                ans = min(ans, (A[i+1][0] - A[i][0]) * 10)

    
    for xy in XYall:
        A = []
        for x, y in Dxy[xy]:
            A.append((x, y, "D"))
        for x, y in Lxy[xy]:
            A.append((x, y, "L"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "D" and A[i + 1][2] == "L":
                ans = min(ans, (A[i + 1][0] - A[i][0]) * 10)

    
    for x_y in X_Yall:
        A = []
        for x, y in Ux_y[x_y]:
            A.append((x, y, "U"))
        for x, y in Lx_y[x_y]:
            A.append((x, y, "L"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "U" and A[i + 1][2] == "L":
                ans = min(ans, (A[i + 1][0] - A[i][0]) * 10)

    
    for x_y in X_Yall:
        A = []
        for x, y in Dx_y[x_y]:
            A.append((x, y, "D"))
        for x, y in Rx_y[x_y]:
            A.append((x, y, "R"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "R" and A[i + 1][2] == "D":
                ans = min(ans, (A[i + 1][0] - A[i][0]) * 10)

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


if __name__ == '__main__':
    main()

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

def main():
    n = int(input())
    yx_p_u = {}
    yx_p_r = {}
    yx_p_d = {}
    yx_p_l = {}

    yx_m_u = {}
    yx_m_r = {}
    yx_m_d = {}
    yx_m_l = {}

    y_d = {}
    y_u = {}
    x_r = {}
    x_l = {}

    for i in range(-200000,200000+1):
        yx_p_u[i] = []
        yx_p_r[i] = []
        yx_p_d[i] = []
        yx_p_l[i] = []

    for i in range(0,400000+1):
        yx_m_u[i] = []
        yx_m_r[i] = []
        yx_m_d[i] = []
        yx_m_l[i] = []

        if i <= 200000:
            y_d[i] = []
            y_u[i] = []
            x_r[i] = []
            x_l[i] = []


    for _ in range(n):
        x,y,u = map(str, input().split())
        x = int(x)
        y = int(y)
        yxp = y-x
        yxm = y+x
        if u == 'U':
            yx_p_u[yxp].append(x)
            yx_m_u[yxm].append(x)
            y_u[x].append(y)
        if u == 'R':
            yx_p_r[yxp].append(x)
            yx_m_r[yxm].append(x)
            x_r[y].append(x)
        if u == 'D':
            yx_p_d[yxp].append(x)
            yx_m_d[yxm].append(x)
            y_d[x].append(y)
        if u == 'L':
            yx_p_l[yxp].append(x)
            yx_m_l[yxm].append(x)
            x_l[y].append(x)


    
    for i in range(-200000,200000+1):
        yx_p_u[i].sort()
        yx_p_r[i].sort()
        yx_p_d[i].sort()
        yx_p_l[i].sort()
        
        
        
        


    for i in range(0,400000+1):
        yx_m_u[i].sort()
        yx_m_r[i].sort()
        yx_m_d[i].sort()
        yx_m_l[i].sort()
        if i <= 200000:
            y_d[i].sort()
            y_u[i].sort()
            x_r[i].sort()
            x_l[i].sort()
        
        
        
        


    ans = 10**9
    for i in range(-200000,200000+1):
        for v in yx_p_u[i]:
            ind = bisect_right(yx_p_l[i], v)
            ind = ind if 0 <= ind < len(yx_p_l[i]) else None
            val = yx_p_l[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)

        for v in yx_p_d[i]:
            ind = bisect_left(yx_p_r[i], v) - 1
            ind = ind if 0 <= ind < len(yx_p_r[i]) else None
            val = yx_p_r[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)


    for i in range(0,400000+1):
        for v in yx_m_d[i]:
            ind = bisect_right(yx_m_l[i], v)
            ind = ind if 0 <= ind < len(yx_m_l[i]) else None
            val = yx_m_l[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)

        for v in yx_m_u[i]:
            ind = bisect_left(yx_m_r[i], v) - 1
            ind = ind if 0 <= ind < len(yx_m_r[i]) else None
            val = yx_m_r[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)

        if i <= 200000:
            for v in y_u[i]:
                ind = bisect_right(y_d[i], v)
                ind = ind if 0 <= ind < len(y_d[i]) else None
                val = y_d[i][ind] if ind is not None else None
                if val is not None:
                    ans = min(ans, abs(val-v)*10//2)

            for v in x_r[i]:
                ind = bisect_right(x_l[i], v)
                ind = ind if 0 <= ind < len(x_l[i]) else None
                val = x_l[i][ind] if ind is not None else None
                if val is not None:
                    ans = min(ans, abs(val-v)*10//2)


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


if __name__ == "__main__":
    main()

Solution (Python):
from collections import defaultdict
from bisect import *
def solve():
  ans = float('inf')
  N = int(input())
  L_y = defaultdict(lambda: [-float('inf'),float('inf')])
  R_y = defaultdict(lambda: [-float('inf'),float('inf')])
  U_x = defaultdict(lambda: [-float('inf'),float('inf')])
  D_x = defaultdict(lambda: [-float('inf'),float('inf')])
  R_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  R_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  L_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  L_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  U_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  U_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  D_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  D_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  for i in range(N):
    x,y,u = input().split()
    x,y = int(x),int(y)
    if u=='D':
      insort(D_x[x],y)
      insort(D_xpy[x+y],x)
      insort(D_y_x[y-x],x)
    if u=='U':
      insort(U_x[x],y)
      insort(U_xpy[x+y],x)
      insort(U_y_x[y-x],x)
    if u=='L':
      insort(L_y[y],x)
      insort(L_xpy[x+y],x)
      insort(L_y_x[y-x],x)
    if u=='R':
      insort(R_y[y],x)
      insort(R_xpy[x+y],x)
      insort(R_y_x[y-x],x)
  for k,v in R_y.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(L_y[k],zahyou)
      dis = L_y[k][ind]-zahyou
      ans = min(ans,dis)
  for k,v in D_x.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(U_x[k],zahyou)
      dis = zahyou-U_x[k][ind-1]
      ans = min(ans,dis)
  for k,v in L_y_x.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(U_y_x[k],zahyou)
      dis = zahyou-U_y_x[k][ind-1]
      dis *= 2
      ans = min(ans,dis)
  for k,v in R_xpy.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(U_xpy[k],zahyou)
      dis = U_xpy[k][ind]-zahyou
      dis *= 2
      ans = min(ans,dis)
  for k,v in L_xpy.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(D_xpy[k],zahyou)
      dis = zahyou-D_xpy[k][ind-1]
      dis *= 2
      ans = min(ans,dis)
  for k,v in R_y_x.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(D_y_x[k],zahyou)
      dis = D_y_x[k][ind]-zahyou
      dis *= 2
      ans = min(ans,dis)
  ans *= 5
  return ans if ans<float('inf') else 'SAFE'
print(solve())