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):
from bisect import bisect_left
from collections import defaultdict
N=int(input())
D=[[] for i in range(2*10**5+1)]
U=[[] for i in range(2*10**5+1)]
L=[[] for i in range(2*10**5+1)]
R=[[] for i in range(2*10**5+1)]
arr=[]


T=[[[] for i in range(2*10**5+1)] for i in range(4)]
li=['U','L','D','R']
for i in range(N):
    X,Y,v=input().split()
    X,Y=int(X),int(Y)
    arr.append((X,Y,v))
    if v=='U':
        U[X].append(Y)
    if v=='D':
        D[X].append(Y)
    if v=='L':
        L[Y].append(X)
    if v=='R':
        R[Y].append(X)
ans=float('inf')
for i in range(2*10**5+1):
    D[i].sort()
    for u in U[i]:
        b=bisect_left(D[i],u)
        if b==len(D[i]):
            continue
        ans=min(ans,5*(D[i][b]-u))
    L[i].sort()
    for r in R[i]:
        b=bisect_left(L[i],r)
        if b==len(L[i]):
            continue
        ans=min(ans,5*(L[i][b]-r))
        
def check(R,U):
    res=float('inf')
    for A,B in U.items():
        B.sort()
    for xr,yr in R:
        b=bisect_left(U[xr+yr],xr)
        if b==len(U[xr+yr]):
            continue
        res=min(res,10*(U[xr+yr][b]-xr))
    return res

def f1(x,y):return x,y
def f2(x,y):return -y,x
def f3(x,y):return -x,-y
def f4(x,y):return y,-x
fanc=[f1,f2,f3,f4]
for t in range(4):
    arr2=[]
    for x,y,v in arr:
        a,b=fanc[t](x,y)
        c=li[(li.index(v)+t)%4]
        arr2.append((a,b,c))
    r2,u2=[],defaultdict(list)
    for x,y,v in arr2:
        if v=='R':
            r2.append((x,y))
        if v=='U':
            u2[x+y].append(x)
    ans=min(ans,check(r2,u2))
print(ans if ans!=float('inf') else 'SAFE')

Solution (Python):
from bisect import bisect_left
from collections import defaultdict
N=int(input())
D=[[] for i in range(2*10**5+1)]
U=[[] for i in range(2*10**5+1)]
L=[[] for i in range(2*10**5+1)]
R=[[] for i in range(2*10**5+1)]
arr=[]

for i in range(N):
    X,Y,v=input().split()
    X,Y=int(X),int(Y)
    arr.append((X,Y,v))
    if v=='U':
        U[X].append(Y)
    if v=='D':
        D[X].append(Y)
    if v=='L':
        L[Y].append(X)
    if v=='R':
        R[Y].append(X)
ans=float('inf')
for i in range(2*10**5+1):
    D[i].sort()
    for u in U[i]:
        b=bisect_left(D[i],u)
        if b==len(D[i]):
            continue
        ans=min(ans,5*(D[i][b]-u))
        
    L[i].sort()
    for r in R[i]:
        b=bisect_left(L[i],r)
        if b==len(L[i]):
            continue
        ans=min(ans,5*(L[i][b]-r))
        
def check(R,U):
    res=float('inf')
    for A,B in U.items():
        B.sort()
    for xr,yr in R:
        b=bisect_left(U[xr+yr],xr)
        if b==len(U[xr+yr]):
            continue
        res=min(res,10*(U[xr+yr][b]-xr))
    return res

for t in range(4):
    r2,u2=[],defaultdict(list)
    for x,y,v in arr:
        if v=='U':
            if t==0:
                u2[x+y].append(x)
            if t==3:
                r2.append((y,-x))
        if v=='D':
            if t==2:
                u2[-y-x].append(-x)
            if t==1:
                r2.append((-y,x))
        if v=='R':
            if t==0:
                r2.append((x,y))
            if t==1:
                u2[x-y].append(-y)
        if v=='L':
            if t==2:
                r2.append((-x,-y))
            if t==3:
                u2[y-x].append(y)
    ans=min(ans,check(r2,u2))
print(ans if ans!=float('inf') else 'SAFE')

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

"""

上下 or 左右　それぞれの組はすぐ求まる．
同じライン上で上むきと下向きをまとめておいて，上向のaに対して，それよりも上にいて最も近い下向きのを探せば良い．
実際にはもっと早くできそうだけど二分探索で十分早いか

右+上　が当たる場合を考える．
u，rがそれぞれ約N個あるとして
uの中で一番左にあるやつ vs r全部
を考えて，uを左から順に見ていく？
微妙．

当たるとはdx=dyのこと
これ，右向きのやつを通る傾き-1の直線上（かつy座標が上の位置）に右向きのものがあれば当たれる．
45度回転させるか
X=x-y
Y=x+y
で反時計45度回転か．

uとrで，Y座標が同じで，rの方がX座標が小さい
dとlで，Y座標が同じで，dの方がX座標が小さい
dとrで，X座標が同じで，rの方がY座標が小さい
uとlで，X座標が同じで，uの方がY座標が小さい

だるすぎる，直線上の点をみよう，y=-x+kとすればx+y=kなので，kで場合わけ
各kでx座標が小さい順に並べておき，
u,rで，rの方がx座標が小さい
d,rで，rの方がx座標が小さい
u,lで，uの方がx座標が小さい
d,lで，dの方がx座標が小さい

"""
def main():
    import bisect
    
    mod=10**9+7
    N=I()
    M=200000 + 3
    inf = 10**10
    
    X=[0]*N
    Y=[0]*N
    U=[0]*N
    for i in range(N):
        xyu=input().split()
        X[i]=int(xyu[0])
        Y[i]=int(xyu[1])
        U[i]=xyu[2]
        
    
    
    
    xd=[[-inf, inf]for _ in range(M)]
    yl=[[-inf, inf]for _ in range(M)]
    
    
    for i in range(N):
        x=X[i]
        y=Y[i]
        if U[i] == "U":
            
            pass
        elif U[i] == "D":
            xd[x].append(y)
        elif U[i] == "L":
            yl[y].append(x)
        else:
            
            pass
    
    for i in range(M):
        
        xd[i].sort()
        yl[i].sort()
        
     
    ans_d=inf
    
    
    for i in range(N):
        x=X[i]
        y=Y[i]
        u=U[i]
        
        if u=="U":
            num=bisect.bisect_left(xd[x], y)
            ne=xd[x][num]
            diff=ne-y
            ans_d=min(ans_d,diff)
            
        if u=="R":
            num=bisect.bisect_left(yl[y], x)
            ne=yl[y][num]
            diff=ne-x
            ans_d=min(ans_d,diff)
            
        """
        if u=="D":
            num=bisect.bisect_left(xu[x], y)
            pre=xu[x][num-1]
            diff=y-pre
            ans_d=min(ans_d,diff)

        if u=="L":
            num=bisect.bisect_left(yr[y], x)
            pre=yr[y][num-1]
            diff=x-pre
            ans_d=min(ans_d,diff)
        """
            
        
    
    
    

    ku=[[-inf, inf]for _ in range(M*2)]
    kd=[[-inf, inf]for _ in range(M*2)]
    kl=[[-inf, inf]for _ in range(M*2)]
    kr=[[-inf, inf]for _ in range(M*2)]  
    
    
    
    k2u=[[-inf, inf]for _ in range(M*2)]
    k2d=[[-inf, inf]for _ in range(M*2)]
    k2l=[[-inf, inf]for _ in range(M*2)]
    k2r=[[-inf, inf]for _ in range(M*2)]     

    for i in range(N):
        x=X[i]
        y=Y[i]
        k=x+y
        k2=y-x+M
        if U[i] == "U":
            ku[k].append(x)
            k2u[k2].append(x)
        elif U[i] == "D":
            kd[k].append(x)
            k2d[k2].append(x)
        elif U[i] == "L":
            kl[k].append(x)
            k2l[k2].append(x)
        else:
            kr[k].append(x)
            k2r[k2].append(x)
            
    for i in range(M*2):
        ku[i].sort()
        kd[i].sort()
        kl[i].sort()
        kr[i].sort()
        k2u[i].sort()
        k2d[i].sort()
        k2l[i].sort()
        k2r[i].sort()
       
    """     
    各kでx座標が小さい順に並べておき，
    u,rで，rの方がx座標が小さい
    d,rで，rの方がx座標が小さい
    u,lで，uの方がx座標が小さい
    d,lで，dの方がx座標が小さい
    """
    
    
    
    ans_d2=inf
    
    for i in range(N):
        x=X[i]
        y=Y[i]
        k=x+y
        k2=y-x+M
        if U[i] == "U":
            num=bisect.bisect_left(kr[k],x)
            pre=kr[k][num-1]
            diff=x-pre
            ans_d2=min(ans_d2,diff)

            num=bisect.bisect_left(k2l[k2],x)
            ne=k2l[k2][num]
            diff=ne-x
            ans_d2=min(ans_d2,diff)
            
        elif U[i] == "D":
            num=bisect.bisect_left(k2r[k2],x)
            pre=k2r[k2][num-1]
            diff=x-pre
            ans_d2=min(ans_d2,diff)

            num=bisect.bisect_left(kl[k],x)
            ne=kl[k][num]
            diff=ne-x
            ans_d2=min(ans_d2,diff)
        
        
            
    
        
    ans = min(ans_d*5, ans_d2*10) 
    
    if ans>=10**8:
        print("SAFE")
    else:
        print(ans)
        


        
        



        
        
            
    
            
            
        

main()

Solution (Python):
def main():
    def calc(v, w, i, j, ans):
        if v > 0:
            i[0] += 1
        elif v < 0:
            j[0] += 1
        else:
            if w > 0:
                ans[0] = min(ans[0], w)
                i[0] += 1
            else:
                j[0] += 1

    n = int(input())
    inf = 10**10
    ans = [inf]
    u_list, d_list, l_list, r_list = [], [], [], []
    for _ in range(n):
        x, y, d = input().split()
        x, y = int(x), int(y)
        if d == "D":
            d_list.append((x, y))
        elif d == "R":
            r_list.append((x, y))
        elif d == "L":
            l_list.append((x, y))
        else:
            u_list.append((x, y))
    ld, lr, ll, lu = len(d_list), len(r_list), len(l_list), len(u_list)
    
    u_list.sort(key=lambda x: (x[0], x[1]))
    d_list.sort(key=lambda x: (x[0], x[1]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < ld):
        x, y = u_list[i[0]]
        p, q = d_list[j[0]]
        v = p-x
        w = (q-y)*5
        calc(v, w, i, j, ans)
    
    r_list.sort(key=lambda x: (x[1], x[0]))
    l_list.sort(key=lambda x: (x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < lr and j[0] < ll):
        x, y = r_list[i[0]]
        p, q = l_list[j[0]]
        v = q-y
        w = (p-x)*5
        calc(v, w, i, j, ans)
    
    u_list.sort(key=lambda x: (x[0]-x[1], x[0]))
    l_list.sort(key=lambda x: (x[0]-x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < ll):
        x, y = u_list[i[0]]
        p, q = l_list[j[0]]
        v = (p-q)-(x-y)
        w = (p-x)*10
        calc(v, w, i, j, ans)
    
    d_list.sort(key=lambda x: (x[0]+x[1], x[0]))
    l_list.sort(key=lambda x: (x[0]+x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < ld and j[0] < ll):
        x, y = d_list[i[0]]
        p, q = l_list[j[0]]
        v = (p+q)-(x+y)
        w = (p-x)*10
        calc(v, w, i, j, ans)
    
    u_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < lr):
        x, y = u_list[i[0]]
        p, q = r_list[j[0]]
        v = (p+q)-(x+y)
        w = (x-p)*10
        calc(v, w, i, j, ans)
    
    d_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    i, j = [0], [0]
    while(i[0] < ld and j[0] < lr):
        x, y = d_list[i[0]]
        p, q = r_list[j[0]]
        v = (p-q)-(x-y)
        w = (x-p)*10
        calc(v, w, i, j, ans)
    if ans == [inf]:
        print("SAFE")
    else:
        print(ans[0])


main()

Solution (Python):

import sys
import io


def main():
    N = int( sys.stdin.readline() )

    XYU_list = []

    for _ in range(N):
        x,y,u = sys.stdin.readline().rstrip().split()
        XYU_list.append( [int(x),int(y),u] )


    diff = float("inf")

    for i in range(4):
        if i <= 1:  
            ret = checkSafety_UD(XYU_list)
            diff = min(diff, ret)
        
        
        ret = checkSafety_UR(XYU_list)
        diff = min(diff, ret)

        rotate(XYU_list)


    if diff != float("inf"):
        print( int(diff * 10) )
    else:
        print("SAFE")


def rotate(XYU_list :list):
    for i in range(len(XYU_list)):
        x,y,u = XYU_list[i][0], XYU_list[i][1], XYU_list[i][2]
        
        x2 = -y
        y2 = x
        
        if u == "U":  u2 = "L"
        if u == "D":  u2 = "R"
        if u == "L":  u2 = "D"
        if u == "R":  u2 = "U"
        
        XYU_list[i] = [x2,y2,u2]


def checkSafety_UD(XYU_list :list) -> int:
    check_UD = {}

    for x,y,u in XYU_list:
        if (u == "U") or (u == "D"):
            check_UD.setdefault( x , [] )
            check_UD[x].append( (y,u) )

    for key in check_UD:
        check_UD[key].sort()


    diff_min = float("inf")
    
    for arr in check_UD.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "U") and (arr[i+1][1] == "D"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) / 2 )

    return diff_min


def checkSafety_UR(XYU_list) -> int:
    check_UR = {}

    for x,y,u in XYU_list:
        if (u == "U") or (u == "R"):
            check_UR.setdefault( (x+y) , [] )
            check_UR[ (x+y) ].append( (x,u) )

    for key in check_UR:
        check_UR[key].sort()


    diff_min = float("inf")
    
    for arr in check_UR.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "R") and (arr[i+1][1] == "U"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) )

    return diff_min


if __name__ == "__main__":
    main()

Solution (Python):

import sys
import io


def main():
    N = int( sys.stdin.readline() )

    XYU_list = []

    for _ in range(N):
        x,y,u = sys.stdin.readline().rstrip().split()
        XYU_list.append( [int(x),int(y),u] )


    diff = float("inf")

    
    ret = checkSafety_UD(XYU_list)
    diff = min(diff, ret)
    
    ret = checkSafety_UR(XYU_list)
    diff = min(diff, ret)
    
    
    rotate(XYU_list)

    ret = checkSafety_UD(XYU_list)
    diff = min(diff, ret)
    
    ret = checkSafety_UR(XYU_list)
    diff = min(diff, ret)

    
    rotate(XYU_list)

    ret = checkSafety_UR(XYU_list)
    diff = min(diff, ret)

    
    rotate(XYU_list)

    ret = checkSafety_UR(XYU_list)
    diff = min(diff, ret)


    if diff != float("inf"):
        print( int(diff * 10) )
    else:
        print("SAFE")


def rotate(XYU_list :list):
    for i in range(len(XYU_list)):
        x,y,u = XYU_list[i][0], XYU_list[i][1], XYU_list[i][2]
        
        x2 = -y
        y2 = x
        
        if u == "U":  u2 = "L"
        if u == "D":  u2 = "R"
        if u == "L":  u2 = "D"
        if u == "R":  u2 = "U"
        
        XYU_list[i] = [x2,y2,u2]


def checkSafety_UD(XYU_list :list) -> int:
    check_UD = {}

    for x,y,u in XYU_list:
        if (u == "U") or (u == "D"):
            check_UD.setdefault( x , [] )
            check_UD[x].append( (y,u) )

    for key in check_UD:
        check_UD[key].sort()


    diff_min = float("inf")
    
    for arr in check_UD.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "U") and (arr[i+1][1] == "D"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) / 2 )

    return diff_min


def checkSafety_UR(XYU_list) -> int:
    check_UR = {}

    for x,y,u in XYU_list:
        if (u == "U") or (u == "R"):
            check_UR.setdefault( (x+y) , [] )
            check_UR[ (x+y) ].append( (x,u) )

    for key in check_UR:
        check_UR[key].sort()


    diff_min = float("inf")
    
    for arr in check_UR.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "R") and (arr[i+1][1] == "U"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) )

    return diff_min


if __name__ == "__main__":
    main()

Solution (Python):

import sys
import io


def main():
    N = int( sys.stdin.readline() )

    XYU_list = []

    for _ in range(N):
        x,y,u = sys.stdin.readline().rstrip().split()
        XYU_list.append( [int(x),int(y),u] )

    
    check_UD = {}
    check_LR = {}

    check_UR = {}
    check_DL = {}
    check_UL = {}
    check_DR = {}


    for x,y,u in XYU_list:
        if (u == "U") or (u == "D"):
            check_UD.setdefault( x , [] )
            check_UD[x].append( (y,u) )
        
        if (u == "L") or (u == "R"):
            check_LR.setdefault( y , [] )
            check_LR[y].append( (x,u) )
        
        if (u == "U") or (u == "R"):
            check_UR.setdefault( (x+y) , [] )
            check_UR[ (x+y) ].append( (x,u) )

        if (u == "D") or (u == "L"):
            check_DL.setdefault( (x+y) , [] )
            check_DL[ (x+y) ].append( (x,u) )

        if (u == "U") or (u == "L"):
            check_UL.setdefault( (x-y) , [] )
            check_UL[ (x-y) ].append( (x,u) )

        if (u == "D") or (u == "R"):
            check_DR.setdefault( (x-y) , [] )
            check_DR[ (x-y) ].append( (x,u) )


    for check_dic in [check_UD, check_LR, check_UR, check_DL, check_UL, check_DR]:
        for key in check_dic:
            check_dic[key].sort()
    

    diff_min = float("inf")
    
    for arr in check_UD.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "U") and (arr[i+1][1] == "D"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) / 2 )
    
    for arr in check_LR.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "R") and (arr[i+1][1] == "L"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) / 2 )



    for arr in check_UR.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "R") and (arr[i+1][1] == "U"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) )
    
    for arr in check_DL.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "D") and (arr[i+1][1] == "L"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) )

    for arr in check_UL.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "U") and (arr[i+1][1] == "L"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) )

    for arr in check_DR.values():
        for i in range(len(arr) - 1):
            if (arr[i][1] == "R") and (arr[i+1][1] == "D"):
                diff_min = min( diff_min, (arr[i+1][0] - arr[i][0]) )



    if diff_min != float("inf"):
        print( int(diff_min * 10) )
    else:
        print("SAFE")


if __name__ == "__main__":
    main()

Solution (Python):
def generate_test_case():
    import random
    random.seed(0)
    ret = list()
    n = 10
    for _ in range(5):
        plane_list = list()
        for _ in range(n):
            x, y = random.choices(range(200001), k=2)
            u = random.choice(['U', 'R', 'D', 'L'])
            plane_list.append((x, y, u))
        ret.append({
            'n': n,
            'plane_list': plane_list
        })
    return ret


def solve_simply(N, plane_list):
    
    from collections import defaultdict
    occur_collision = False
    LIMIT_T = 200000 * 2
    t = 1
    while t <= LIMIT_T:
        location = defaultdict(int)
        same_location = False
        for plane in plane_list:
            x, y, u = plane
            x *= 2  
            y *= 2
            if u == 'U':
                y += t  
            elif u == 'R':
                x += t
            elif u == 'D':
                y -= t
            else:
                x -= t
            if location[(x, y)] > 0:
                same_location = True
                break
            location[(x, y)] += 1
        if same_location:
            occur_collision = True
            break
        t += 1
    if occur_collision:
        return t * 5
    else:
        return 'SAFE'


def get_min_t_on_same_line(N, plane_list, t_inf=2*(10**6)):
    import bisect
    from collections import defaultdict
    uy, dy = defaultdict(list), defaultdict(list)
    plane_list.sort(key=lambda p: (p[0], p[1]))  
    for plane in plane_list:
        x, y, u = plane
        if u == 'U':
            uy[x].append(y)
        elif u == 'D':
            dy[x].append(y)
    lx, rx = defaultdict(list), defaultdict(list)
    plane_list.sort(key=lambda p: (p[1], p[0]))  
    for plane in plane_list:
        x, y, u = plane
        if u == 'R':
            rx[y].append(x)
        elif u == 'L':
            lx[y].append(x)
    min_t = t_inf
    for y in rx.keys():  
        for x in rx[y]:
            index = bisect.bisect_right(lx[y], x)
            if index >= len(lx[y]):
                continue
            dist = lx[y][index] - x
            min_t = min(min_t, 5 * dist)
    for x in uy.keys():  
        for y in uy[x]:
            index = bisect.bisect_right(dy[x], y)
            if index >= len(dy[x]):
                continue
            dist = dy[x][index] - y
            min_t = min(min_t, 5 * dist)
    return min_t


def get_min_t_at_crossing(N, plane_list, t_inf=2*(10**6)):
    from collections import defaultdict
    import bisect
    plane_list.sort(key=lambda p: p[0])  
    min_t = t_inf
    
    rx, ux = defaultdict(list), defaultdict(list)
    lx, dx = defaultdict(list), defaultdict(list)
    for plane in plane_list:
        x, y, u = plane
        k = y + x
        if u == 'U':
            ux[k].append(x)
        elif u == 'R':
            rx[k].append(x)
        elif u == 'D':
            dx[k].append(x)
        else:
            lx[k].append(x)
    for k in rx.keys():  
        for x in rx[k]:
            index = bisect.bisect_right(ux[k], x)
            if index >= len(ux[k]):
                continue
            x_diff = ux[k][index] - x
            min_t = min(min_t, 10 * x_diff)
    for k in dx.keys():  
        for x in dx[k]:
            index = bisect.bisect_right(lx[k], x)
            if index >= len(lx[k]):
                continue
            x_diff = lx[k][index] - x
            min_t = min(min_t, 10 * x_diff)
    
    rx, ux = defaultdict(list), defaultdict(list)
    lx, dx = defaultdict(list), defaultdict(list)
    for plane in plane_list:
        x, y, u = plane
        k = y - x
        if u == 'U':
            ux[k].append(x)
        elif u == 'R':
            rx[k].append(x)
        elif u == 'D':
            dx[k].append(x)
        else:
            lx[k].append(x)
    for k in rx.keys():  
        for x in rx[k]:
            index = bisect.bisect_right(dx[k], x)
            if index >= len(dx[k]):
                continue
            x_diff = dx[k][index] - x
            min_t = min(min_t, 10 * x_diff)
    for k in ux.keys():  
        for x in ux[k]:
            index = bisect.bisect_right(lx[k], x)
            if index >= len(lx[k]):
                continue
            x_diff = lx[k][index] - x
            min_t = min(min_t, 10 * x_diff)
    return min_t


def solve(N, plane_list):
    T_INF = 2 * (10 ** 6) + 1
    
    min_t = get_min_t_on_same_line(N, plane_list, T_INF)
    
    min_t = min(min_t, get_min_t_at_crossing(N, plane_list, T_INF))
    if min_t == T_INF:
        return 'SAFE'
    return min_t


def main():
    N = int(input())
    plane_list = list()
    for _ in range(N):
        X, Y, U = input().split()
        X, Y = int(X), int(Y)
        plane_list.append((X, Y, U))
    print(solve(N, plane_list))


def check():
    for i, test_case in enumerate(generate_test_case()):
        print('Check {}-th test case'.format(i))
        N, plane_list = test_case['n'], test_case['plane_list']
        assert solve_simply(N, plane_list) == solve(N, plane_list)
    print('OK')


if __name__ == '__main__':
    main()

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

n = int(input())
C = [list(input().split()) for i in range(n)]

l = 2*10**5 + 5



    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

A = []
D = {"U": 0, "R": 1, "D": 2, "L": 3}
for i in range(n):
    A.append([int(C[i][0]), int(C[i][1]), D[C[i][2]]])

from bisect import bisect

ans = float("inf")
for ii in range(4):
    
    
    if ii <= 1:
        L = [[] for i in range(l)]
        R = [[] for i in range(l)]
        for i in range(n):
            if A[i][2] == 3:
                L[A[i][1]].append(A[i][0])
            if A[i][2] == 1:
                
                R[A[i][1]].append(A[i][0])

        for i in range(l):
            R[i].sort()
            
            for j in range(len(L[i])):
                ind = bisect(R[i], L[i][j])
                if ind > 0:
                    ans = min(ans, (L[i][j]-R[i][ind-1]) * 5)

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

    for i in range(n):
        if A[i][2] == 3:
            L[A[i][0] + A[i][1]].append(A[i][0])
        if A[i][2] == 2:
            D[A[i][0] + A[i][1]].append(A[i][0])
    for i in range(2*l):
        D[i].sort()
        for j in range(len(L[i])):
            ind = bisect(D[i], L[i][j])
            if ind > 0:
                ans = min(ans, (L[i][j]-D[i][ind-1]) * 10)
                

    for i in range(n):
        l2 = l // 2 - 1
        A[i][0], A[i][1] = (A[i][1]-l2) + l2, -(A[i][0]-l2) + l2
        A[i][2] = (A[i][2] + 1) % 4

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

Solution (Python):
from operator import itemgetter
import bisect


n = int(input())
info = []
for i in range(n):
    x, y, u = input().split()
    info.append((int(x), int(y), u))
INF = 10 ** 18
ans = INF


info = sorted(info, key=itemgetter(0))
u = {}
d = {}
l = {}
r = {}
for x, y, dire in info:
    xy = x + y
    if dire == "U":
        if xy not in u:
            u[xy] = []
        u[xy].append(x)
    if dire == "D":
        if xy not in d:
            d[xy] = []
        d[xy].append(x)
    if dire == "L":
        if xy not in l:
            l[xy] = []
        l[xy].append(x)
    if dire == "R":
        if xy not in r:
            r[xy] = []
        r[xy].append(x)

for xy in u:
    if xy not in r:
        continue
    for x in u[xy]:
        ind = bisect.bisect_left(r[xy], x) - 1
        if ind < 0:
            continue
        ans = min((x - r[xy][ind]) * 10, ans)

for xy in l:
    if xy not in d:
        continue
    for x in l[xy]:
        ind = bisect.bisect_left(d[xy], x) - 1
        if ind < 0:
            continue
        ans = min((x - d[xy][ind]) * 10, ans)

info = sorted(info, key=itemgetter(0))
u = {}
d = {}
l = {}
r = {}
for x, y, dire in info:
    xy = x - y
    if dire == "U":
        if xy not in u:
            u[xy] = []
        u[xy].append(x)
    if dire == "D":
        if xy not in d:
            d[xy] = []
        d[xy].append(x)
    if dire == "L":
        if xy not in l:
            l[xy] = []
        l[xy].append(x)
    if dire == "R":
        if xy not in r:
            r[xy] = []
        r[xy].append(x)

for xy in d:
    if xy not in r:
        continue
    for x in d[xy]:
        ind = bisect.bisect_left(r[xy], x) - 1
        if ind < 0:
            continue
        ans = min((x - r[xy][ind]) * 10, ans)

for xy in l:
    if xy not in u:
        continue
    for x in l[xy]:
        ind = bisect.bisect_left(u[xy], x) - 1
        if ind < 0:
            continue
        ans = min((x - u[xy][ind]) * 10, ans)

l = {}
r = {}
for x, y, dire in info:
    if dire == "L":
        if y not in l:
            l[y] = []
        l[y].append(x)
    if dire == "R":
        if y not in r:
            r[y] = []
        r[y].append(x)

for y in l:
    if y not in r:
        continue
    for x in l[y]:
        ind = bisect.bisect_left(r[y], x) - 1
        if ind < 0:
            continue
        ans = min((x - r[y][ind]) * 5, ans)

info = sorted(info, key=itemgetter(1))
u = {}
d = {}
for x, y, dire in info:
    if dire == "U":
        if x not in u:
            u[x] = []
        u[x].append(y)
    if dire == "D":
        if x not in d:
            d[x] = []
        d[x].append(y)

for x in d:
    if x not in u:
        continue
    for y in d[x]:
        ind = bisect.bisect_left(u[x], y) - 1
        if ind < 0:
            continue
        ans = min((y - u[x][ind]) * 5, ans)

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

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+1)]
ur = [[] for i in range(size*2+1)]
dl = [[] for i in range(size*2+1)]
dr = [[] for i in range(size*2+1)]

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)