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 heapq
import copy
n = int(input())

size = 2*10**5
def f(ary):
    t_ans = 10**100
    for i in range(len(ary)):
        t_ud = ary[i]
        if len(t_ud) != 0:
            
            t_ud.sort()
            t_u = -10**100
            for j in range(len(t_ud)):
                if t_ud[j][1] == 'U':
                    t_u = t_ud[j][0]
                elif t_u == -10**100:
                    continue
                else:
                    t_ans = min(t_ans, (t_ud[j][0] - t_u))
    return t_ans

xyu = []

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

ud = [[] for i in range(size+1)]
rl = [[] for i in range(size+1)]
ul = [[] for i in range(size*2+2)]
ur = [[] for i in range(size*2+2)]
dl = [[] for i in range(size*2+2)]
dr = [[] for i in range(size*2+2)]

for i in range(n):
    if xyu[i][2] == 'U':
        ud[xyu[i][0]].append([xyu[i][1],'U'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'U'])
    if xyu[i][2] == 'D':
        ud[xyu[i][0]].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
    if xyu[i][2] == 'R':
        rl[xyu[i][1]].append([xyu[i][0],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
    if xyu[i][2] == 'L':
        rl[xyu[i][1]].append([xyu[i][0],'D'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'U'])
                  
ans = 10**100
ans = min(ans,f(ud)*5)
ans = min(ans,f(rl)*5)
ans = min(ans,f(ul)*10)
ans = min(ans,f(ur)*10)
ans = min(ans,f(dl)*10)
ans = min(ans,f(dr)*10)
if ans == 10**100:
    print('SAFE')
else:
    print(ans)

Solution (Python):
N = int(input())
XYUs = [list(map(str,input().split())) for _ in range(N)]

for i in range(len(XYUs)):
    XYUs[i][0] = int(XYUs[i][0])
    XYUs[i][1] = int(XYUs[i][1])


def check_the_conflict(XYUs):
    slopes = [[] for _ in range(400001)]
    for XYU in XYUs:
        if XYU[2] == "R" or XYU[2] == "D":       
            slopes[int(XYU[1])-int(XYU[0])+200000].append([int(XYU[0]),XYU[2]])    
    return slopes

def rotate_matrix(XYUs):
    converted = []
    for XYU in XYUs:
        if XYU[2] == "R":
            direction = "D"
        elif XYU[2] == "D":
            direction = "L"
        elif XYU[2] == "L":
            direction = "U"
        elif XYU[2] == "U":
            direction = "R"
        converted.append([XYU[1], 200000-XYU[0], direction])
    return converted
    
min_val = int(1e+10)

for i in range(4):
    if i > 0:
        XYUs = rotate_matrix(XYUs)
    slopes = check_the_conflict(XYUs)
    for slope in slopes:
        now_R = -int(1e+10)
        slope = sorted(slope)
        for airplane in slope:
            if airplane[1] == "R":
                now_R = airplane[0]
            elif airplane[1] == "D":
                candidate = (airplane[0] - now_R)*10
                if candidate < min_val:
                    min_val = candidate
    if i in [0,1]:
        rows = [[] for _ in range(200001)]
        for XYU in XYUs:
            rows[XYU[0]].append([XYU[1],XYU[2]])
        for row in rows:
            now_U = -int(1e+10)
            row = sorted(row)
            for airplane in row:
                if airplane[1] == "U":
                    now_U = airplane[0]
                elif airplane[1] == "D":
                    candidate = (airplane[0] - now_U)*5
                    if candidate < min_val:
                        min_val = candidate
if min_val < 3000000:
    print(min_val)
else:
    print("SAFE")

Solution (Python):
def x_ijo_min(lst, x):
    if lst[0] >= x: return lst[0]
    left = 0 
    right = len(lst) 
    while left+1 < right:
        mid = (left+right) // 2
        if lst[mid] < x:
            left = mid
        else:
            right = mid
    if right == len(lst): return False
    else: return lst[right]

n = int(input())

dic_up = {}
dic_down = {}
dic_hor = {}
dic_ver = {}
lst = []
for i in range(n):
    xi, yi, ui = input().split()
    xi, yi = int(xi), int(yi)
    up = xi - yi
    down = xi + yi
    if (ui, up) in dic_up:
        dic_up[(ui, up)].append(xi)
    else:
        dic_up[(ui, up)] = [xi]
    if (ui, down) in dic_down:
        dic_down[(ui, down)].append(xi)
    else:
        dic_down[(ui, down)] = [xi]
    if (ui, xi) in dic_ver:
        dic_ver[(ui, xi)].append(yi)
    else:
        dic_ver[(ui, xi)] = [yi]
    if (ui, yi) in dic_hor:
        dic_hor[(ui, yi)].append(xi)
    else:
        dic_hor[(ui, yi)] = [xi]
    lst.append([xi, yi, ui, up, down])

for key in dic_up.keys():
    dic_up[key].sort()
for key in dic_down.keys():
    dic_down[key].sort()
for key in dic_hor.keys():
    dic_hor[key].sort()
for key in dic_ver.keys():
    dic_ver[key].sort()

ans = 10**9
for i in range(n):
    xi, yi, ui, up, down = lst[i]
    if ui == 'U':
        if ('D', xi) in dic_ver:
            dy = x_ijo_min(dic_ver[('D', xi)], yi)
            if dy: ans = min(ans, (dy-yi)*5)
        if ('L', up) in dic_up:
            lx = x_ijo_min(dic_up[('L', up)], xi)
            if lx: ans = min(ans, (lx-xi)*10)
    if ui == 'R':
        if ('U', down) in dic_down:
            ux = x_ijo_min(dic_down[('U', down)], xi)
            if ux: ans = min(ans, (ux-xi)*10)
        if ('D', up) in dic_up:
            dx = x_ijo_min(dic_up[('D', up)], xi)
            if dx: ans = min(ans, (dx-xi)*10)
        if ('L', yi) in dic_hor:
            lx = x_ijo_min(dic_hor[('L', yi)], xi)
            if lx: ans = min(ans, (lx-xi)*5)
    if ui == 'D':
        if ('L', down) in dic_down:
            lx = x_ijo_min(dic_down[('L', down)], xi)
            if lx: ans = min(ans, (lx-xi)*10)

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

Solution (Python):
import sys
from collections import defaultdict
def input(): return sys.stdin.readline().rstrip()


def culc(li):
    li.sort(key=lambda x: x[0])
    ans = 10**9
    for i in range(len(li)-1):
        if li[i][1] == '+' and li[i+1][1] == '-':
            ans = min(ans, li[i+1][0]-li[i][0])
    return ans


def main():
    N = int(input())
    axisX = defaultdict(list)
    axisY = defaultdict(list)
    XplusYplus = defaultdict(list)
    XminusYminus = defaultdict(list)
    XminusYplus = defaultdict(list)
    XplusYminus = defaultdict(list)
    ans = 10**9
    for _ in range(N):
        x, y, u = input().split()
        x, y = int(x), int(y)
        if u == 'U':
            axisY[x].append([y, '+'])
            XplusYplus[x+y].append([y-x, '+'])
            XminusYplus[x-y].append([x+y, '+'])
        elif u == 'R':
            axisX[y].append([x, '+'])
            XplusYplus[x+y].append([y-x, '-'])
            XplusYminus[x-y].append([x+y, '+'])
        elif u == 'D':
            axisY[x].append([y, '-'])
            XminusYminus[x+y].append([y-x, '-'])
            XplusYminus[x-y].append([x+y, '-'])
        elif u == 'L':
            axisX[y].append([x, '-'])
            XminusYminus[x+y].append([y-x, '+'])
            XminusYplus[x-y].append([x+y, '-'])

    for v in axisX.values():
        if len(v) > 1:
            ans = min(culc(v), ans)
    for v in axisY.values():
        if len(v) > 1:
            ans = min(culc(v), ans)
    for v in XplusYplus.values():
        if len(v) > 1:
            ans = min(culc(v), ans)
    for v in XplusYminus.values():
        if len(v) > 1:
            ans = min(culc(v), ans)
    for v in XminusYplus.values():
        if len(v) > 1:
            ans = min(culc(v), ans)
    for v in XminusYminus.values():
        if len(v) > 1:
            ans = min(culc(v), ans)
    print('SAFE' if ans > 10**8 else 5 * ans)


if __name__ == '__main__':
    main()

Solution (Python):
INF = float("inf")

sc = iter(open(0).read().split())
ni = lambda: int(next(sc))
ns = lambda: next(sc)

LR, UD, RU, LD, LU, RD = [[[] for _ in range(400_100)] for _ in range(6)]

U = []

N = ni()
for i in range(N):
    x, y, u = ni(), ni(), ns()
    U.append(u)

    if u in "LR":
        LR[y].append((x, i))
    if u in "UD":
        UD[x].append((y, i))
    if u in "LD":
        LD[x + y].append((y, i))
    if u in "RU":
        RU[x + y].append((y, i))
    if u in "LU":
        LU[y - x + 200_000].append((x, i))
    if u in "RD":
        RD[y - x + 200_000].append((x, i))

ans = INF
for i in range(400_001):
    LR[i].sort()
    UD[i].sort()
    LD[i].sort()
    RU[i].sort()
    LU[i].sort()
    RD[i].sort()

    ans = min(
        ans,
        5 * min(
            ((LR[i][j + 1][0] - LR[i][j][0])
            for j in range(len(LR[i]) - 1)
            if U[LR[i][j][1]] == "R" and U[LR[i][j + 1][1]] == "L"),
            default=INF
        ),
        5 * min(
            ((UD[i][j + 1][0] - UD[i][j][0])
            for j in range(len(UD[i]) - 1)
            if U[UD[i][j][1]] == "U" and U[UD[i][j + 1][1]] == "D"),
            default=INF
        ),
        10 * min(
            ((LD[i][j + 1][0] - LD[i][j][0])
            for j in range(len(LD[i]) - 1)
            if U[LD[i][j][1]] == "L" and U[LD[i][j + 1][1]] == "D"),
            default=INF
        ),
        10 * min(
            ((RU[i][j + 1][0] - RU[i][j][0])
            for j in range(len(RU[i]) - 1)
            if U[RU[i][j][1]] == "U" and U[RU[i][j + 1][1]] == "R"),
            default=INF
        ),
        10 * min(
            ((LU[i][j + 1][0] - LU[i][j][0])
            for j in range(len(LU[i]) - 1)
            if U[LU[i][j][1]] == "U" and U[LU[i][j + 1][1]] == "L"),
            default=INF
        ),
        10 * min(
            ((RD[i][j + 1][0] - RD[i][j][0])
            for j in range(len(RD[i]) - 1)
            if U[RD[i][j][1]] == "R" and U[RD[i][j + 1][1]] == "D"),
            default=INF
        )
    )

print("SAFE" if ans == INF else ans)

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

n = int(input())

xysame, upright, downright = {},{},{}
u_list = ("U","R","D","L")
for u in u_list:
    xysame[u] = defaultdict(list)
    upright[u] = defaultdict(list)
    downright[u] = defaultdict(list)

for _ in range(n):
    x,y,u = input().split()
    x,y = int(x),int(y)
    if u == "U" or u == "D":
        xysame[u][x].append(y)
    else:
        xysame[u][y].append(x)
    upright[u][y-x].append(x)
    downright[u][y+x].append(x)
    
for u in u_list:
    for key in xysame[u].keys():
        xysame[u][key].sort()
    for key in upright[u].keys():
        upright[u][key].sort()
    for key in downright[u].keys():
        downright[u][key].sort()

INF = 10**6
ans = INF


def line(low,high,type_ = 1):
    ret = INF
    for k,v in low.items():
        if high[k] == []: continue

        for vi in v:
            index = bisect_left(high[k], vi)
            if index == len(high[k]): continue
            ret = min(ret,(high[k][index]-vi)/type_)
    return ret

ans = min(ans, line(xysame["U"],xysame["D"],2))
ans = min(ans, line(xysame["R"],xysame["L"],2))
ans = min(ans, line(upright["R"],upright["D"],1))
ans = min(ans, line(upright["U"],upright["L"],1))
ans = min(ans, line(downright["R"],downright["U"],1))
ans = min(ans, line(downright["D"],downright["L"],1))

ans = int(ans*10)
if ans ==INF*10: ans = "SAFE"
    
print(ans)

Solution (Python):
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N = II()
    
    
    
    U = 0
    R = 1
    D = 2
    L = 3
    direction = {'U':U,'R':R,'D':D,'L':L}
    
    x_axis = defaultdict(list)
    y_axis = defaultdict(list)
    ru = defaultdict(list)
    dr = defaultdict(list)
    ld = defaultdict(list)
    ul = defaultdict(list)
    

    for i in range(N):
        line = input().split()
        x = int(line[0])
        y = int(line[1])
        d = direction[line[2]]

        

        
        
        
        sum_cordinate = x+y
        dif_cordinate = x-y
        if d == U:
            y_axis[x].append((y,d))
            ul[dif_cordinate].append((x,y,d))
            ru[sum_cordinate].append((x,y,d))
        elif d == R:
            x_axis[y].append((x,d))
            ru[sum_cordinate].append((x,y,d))
            dr[dif_cordinate].append((x,y,d))
        elif d == D:
            y_axis[x].append((y,d))
            dr[dif_cordinate].append((x,y,d))
            ld[sum_cordinate].append((x,y,d))
        else:
            x_axis[y].append((x,d))
            ld[sum_cordinate].append((x,y,d))
            ul[dif_cordinate].append((x,y,d))

    

    min_time = 10**20
    for v in x_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  R:
                j = i+1
                while j < len(v):
                    if v[j][1] == L:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1

    for v in y_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  U:
                j = i+1
                while j < len(v):
                    if v[j][1] == D:
                        min_time = min(min_time, (v[j][0]-v[i][0])*5)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ru.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == U:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in dr.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == D:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ld.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == D:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ul.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == U:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1


    print(min_time if min_time < 10**20 else 'SAFE')
    

    

    



    
main()

Solution (Python):
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N = II()
    
    
    
    U = 0
    R = 1
    D = 2
    L = 3
    direction = {'U':U,'R':R,'D':D,'L':L}
    
    x_axis = defaultdict(list)
    y_axis = defaultdict(list)
    ru = defaultdict(list)
    dr = defaultdict(list)
    ld = defaultdict(list)
    ul = defaultdict(list)
    

    for i in range(N):
        line = input().split()
        x = int(line[0])
        y = int(line[1])
        d = direction[line[2]]

        

        
        
        
        sum_cordinate = x+y
        dif_cordinate = x-y
        if d == U:
            y_axis[x].append((y,d))
            ul[dif_cordinate].append((x,y,d))
            ru[sum_cordinate].append((x,y,d))
        elif d == R:
            x_axis[y].append((x,d))
            ru[sum_cordinate].append((x,y,d))
            dr[dif_cordinate].append((x,y,d))
        elif d == D:
            y_axis[x].append((y,d))
            dr[dif_cordinate].append((x,y,d))
            ld[sum_cordinate].append((x,y,d))
        else:
            x_axis[y].append((x,d))
            ld[sum_cordinate].append((x,y,d))
            ul[dif_cordinate].append((x,y,d))

    

    min_time = 10**20
    for v in x_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  R:
                j = i+1
                while j < len(v):
                    if v[j][1] == L:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1

    for v in y_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  U:
                j = i+1
                while j < len(v):
                    if v[j][1] == D:
                        min_time = min(min_time, (v[j][0]-v[i][0])*5)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ru.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == U:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in dr.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == D:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ld.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == D:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ul.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == U:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1


    print(min_time if min_time < 10**20 else 'SAFE')
    

    

    



    
main()

Solution (Python):
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N = II()
    
    
    
    U = 0
    R = 1
    D = 2
    L = 3
    direction = {'U':U,'R':R,'D':D,'L':L}
    
    x_axis = defaultdict(list)
    y_axis = defaultdict(list)
    ru = defaultdict(list)
    dr = defaultdict(list)
    ld = defaultdict(list)
    ul = defaultdict(list)
    

    for i in range(N):
        line = input().split()
        x = int(line[0])
        y = int(line[1])
        d = direction[line[2]]

        

        
        
        
        sum_cordinate = x+y
        dif_cordinate = x-y
        if d == U:
            y_axis[x].append((y,d))
            ul[dif_cordinate].append((x,y,d))
            ru[sum_cordinate].append((x,y,d))
        elif d == R:
            x_axis[y].append((x,d))
            ru[sum_cordinate].append((x,y,d))
            dr[dif_cordinate].append((x,y,d))
        elif d == D:
            y_axis[x].append((y,d))
            dr[dif_cordinate].append((x,y,d))
            ld[sum_cordinate].append((x,y,d))
        else:
            x_axis[y].append((x,d))
            ld[sum_cordinate].append((x,y,d))
            ul[dif_cordinate].append((x,y,d))

    

    min_time = 10**20
    for v in x_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  R:
                j = i+1
                while j < len(v):
                    if v[j][1] == L:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1

    for v in y_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  U:
                j = i+1
                while j < len(v):
                    if v[j][1] == D:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ru.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == U:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in dr.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == D:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ld.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == D:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ul.values():
        
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == U:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1


    print(min_time if min_time < 10**20 else 'SAFE')
    

    

    



    
main()

Solution (Python):
import sys



def main():
    N = int(sys.stdin.readline().rstrip())
    X = [[] for _ in range(200005)]
    Y = [[] for _ in range(200005)]
    A = [[] for _ in range(200005 * 2 + 1)]
    B = [[] for _ in range(200005 * 2 + 1)]

    for i in range(N):
        x, y, u = sys.stdin.readline().rstrip().split()
        x = int(x)
        y = int(y)
        X[x].append((y, u))  
        Y[y].append((x, u))
        A[x + y].append((x, u))
        B[x - y + 200005].append((x, u))

    
    length = 10000000
    for xs in X:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "D":
                    length = min(abs(y - tmp_y) * 5, length)
                    is_count = False
                if u == "U":
                    tmp_y = y
                    is_count = True

    
    for xs in Y:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "L":
                    length = min(abs(y - tmp_y) * 5, length)
                    is_count = False
                if u == "R":
                    tmp_y = y
                    is_count = True

    
    for xs in A:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "U":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "R":
                    tmp_y = y
                    is_count = True

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "L":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "D":
                    tmp_y = y
                    is_count = True

    
    for xs in B:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "L":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "U":
                    tmp_y = y
                    is_count = True

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "D":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "R":
                    tmp_y = y
                    is_count = True

    if length == 10000000:
        print("SAFE")
    else:
        print(length)


main()

Solution (Python):
def f_calc1(u1, d1, ans):
  u1.sort()
  d1.sort()

  i=0
  for x1, y1 in u1:
    while i < len(d1):
      x2, y2 = d1[i]
      if x1 < x2:
        break
      if x1 == x2:
        if y1 < y2:
          ans = min(ans, (y2-y1)*5)
          break
        i += 1
      else:
        i += 1
  return ans

def f_calc2(u1, d1, ans):
  u1.sort()
  d1.sort()

  i=0
  for x1, y1 in u1:
    while i < len(d1):
      x2, y2 = d1[i]
      if x1 < x2:
        break
      if x1 == x2:
        if y1 < y2:
          ans = min(ans, (y2-y1)*10)
          break
        i += 1
      else:
        i += 1
  return ans

n = int(input())

u1 = []
u2 = []
u3 = []
d1 = []
d2 = []
d3 = []
r1 = []
r2 = []
r3 = []
l1 = []
l2 = []
l3 = []

for _ in range(n):
  x,y,u = input().split()
  x = int(x)
  y = int(y)
  if u == 'U':
    u1.append([x, y])
    u2.append([x+y, y])
    u3.append([x-y, y])
  elif u == 'D':
    d1.append([x, y])
    d2.append([x+y, x])
    d3.append([x-y, x])
  elif u == 'R':
    r1.append([y, x])
    r2.append([x+y, y])
    r3.append([x-y, x])
  else:
    l1.append([y, x])
    l2.append([x+y, x])
    l3.append([x-y, y])
  
ans = 10**8
ans = f_calc1(u1, d1, ans)
ans = f_calc1(r1, l1, ans)
ans = f_calc2(u2, r2, ans)
ans = f_calc2(d2, l2, ans)
ans = f_calc2(u3, l3, ans)
ans = f_calc2(r3, d3, ans)

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

Solution (Python):
N = int(input())
L = {'U':[], 'R':[], 'D':[], 'L':[]}

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

ans = 10 ** 7

def solve(A):
    global ans
    A.sort()
    s = - 10 ** 6
    t = - 10 ** 6
    for p, q, r in A:
        if p != s:
            if r == 1:
                s = p
                t = q
        elif r == 1:
            t = q
        else:
            ans = min(ans, (q - t) * 5)

solve([(x, y, 1) for x, y in L['U']] + [(x, y, -1) for x, y in L['D']])
solve([(y, x, 1) for x, y in L['R']] + [(y, x, -1) for x, y in L['L']])
solve([(x + y, y - x, 1) for x, y in L['U']] + [(x + y, y - x, -1) for x, y in L['R']])
solve([(y - x, x + y, 1) for x, y in L['R']] + [(y - x, x + y, -1) for x, y in L['D']])
solve([(x + y, x - y, 1) for x, y in L['D']] + [(x + y, x - y, -1) for x, y in L['L']])
solve([(y - x, - x - y, 1) for x, y in L['L']] + [(y - x, - x - y, -1) for x, y in L['U']])

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