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



Sample input:
2
11 1 U
11 47 D


Sample output:
230

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

n = int(input())
Rp = []
Rm = []
Lp = []
Lm = []
Up = []
Um = []
Dp = []
Dm = []
U = []
D = []
R = []
L = []

for i in range(n):
    x,y,u = input().split()
    x,y = int(x), int(y)
    if u == "U":
        U.append([x,y])
        Up.append((x+y,x,y))
        Um.append((x-y,x,y))
    elif u == "D":
        D.append([x,y])
        Dp.append((x+y,x,y))
        Dm.append((x-y,x,y))
    elif u == "R":
        R.append([y,x])    
        Rp.append((x+y,x,y))
        Rm.append((x-y,x,y))
    else:
        L.append([y,x])
        Lp.append((x+y,x,y))
        Lm.append((x-y,x,y))

Rp.sort()
Rm.sort()
Up.sort()
Um.sort()
Lp.sort()
Lm.sort()
Dp.sort()
Dm.sort()
U.sort()
D.sort()
R.sort()
L.sort()
ans = float("INF")

def syaku(A,B):
    if A == [] or B == []:
        return float("INF")
    la = len(A)
    lb = len(B)
    count = float("INF")
    b = 0
    for i in range(la):
        xy,x,y = A[i]
        if i > 0 and xy == A[i-1][0]:
            if len(l) > 0:
                for nxy,nx,ny in l:
                    if ny >= y:
                        count = min(count, abs(x-nx)*10)
        else:
            l = []
            while b < lb and B[b][0] <= xy:
                if B[b][0] == xy:
                    if B[b][2] >= y:
                        count = min(count,abs(x-B[b][1])*10)
                    l.append(B[b])
                b += 1
    return count

def syaku2(A,B):
    if A == [] or B == []:
        return float("INF")
    la = len(A)
    lb = len(B)
    count = float("INF")
    b = 0
    for i in range(la):
        xy,x,y = A[i]
        if i > 0 and xy == A[i-1][0]:
            if len(l) > 0:
                for nxy,nx,ny in l:
                    if y >= ny:
                        count = min(count, abs(x-nx)*10)
        else:
            l = []
            while b < lb and B[b][0] <= xy:
                if B[b][0] == xy:
                    if y >= B[b][2]:
                        count = min(count,abs(x-B[b][1])*10)
                    l.append(B[b])
                b += 1
    return count

def syaku3(A,B):
    if A == [] or B == []:
        return float("INF")
    la = len(A)
    lb = len(B)
    count = float("INF")
    b = 0
    for i in range(la):
        x,y = A[i]
        if i > 0 and x == A[i-1][0]:
            if len(l) > 0:
                for nx,ny in l:
                    if y >= ny:
                        count = min(count, abs(y-ny)*5)
        else:
            l = []
            while b < lb and B[b][0] <= x:
                if B[b][0] == x:
                    if y >= B[b][1]:
                        count = min(count,abs(y-B[b][1])*5)
                    l.append(B[b])
                b += 1
    return count
ans = min(ans,syaku(Up,Rp))

ans = min(ans,syaku(Um,Lm))

ans = min(ans,syaku2(Dp,Lp))

ans = min(ans,syaku2(Dm,Rm))

ans = min(ans,syaku3(D,U))
ans = min(ans,syaku3(L,R))

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
from collections import defaultdict
import bisect
xd0=defaultdict(list)
xd90=defaultdict(list)
xd180=defaultdict(list)
xd270=defaultdict(list)
xyd0=defaultdict(list)
xyd90=defaultdict(list)
xyd180=defaultdict(list)
xyd270=defaultdict(list)

def rotate(x,y,u):
    if u=='U': u0='R'
    elif u=='R': u0='D'
    elif u=='D': u0='L'
    else: u0='U'
    x0=y
    y0=200000-x
    return x0,y0,u0

for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=='U' or u=='D':
        bisect.insort(xd0[x],(y,u))
    x90,y90,u90=rotate(x,y,u)
    if u90=='U' or u90=='D':
        bisect.insort(xd90[x90],(y90,u90))
    x180,y180,u180=rotate(x90,y90,u90)
    if u180=='U' or u180=='D':
        bisect.insort(xd180[x180],(y180,u180))
    x270,y270,u270=rotate(x180,y180,u180)
    if u270=='U' or u270=='D':
        bisect.insort(xd270[x270],(y270,u270))
    if u=='U' or u=='R':
        bisect.insort(xyd0[x+y],(y,u))
    if u90=='U' or u90=='R':
        bisect.insort(xyd90[x90+y90],(y90,u90))
    if u180=='U' or u180=='R':
        bisect.insort(xyd180[x180+y180],(y180,u180))
    if u270=='U' or u270=='R':
        bisect.insort(xyd270[x270+y270],(y270,u270))

ans=float('inf')
for i in range(4):
    if i==0:
        xd=xd0
        xyd=xyd0
    elif i==1:
        xd=xd90
        xyd=xyd90        
    elif i==2:
        xd=xd180
        xyd=xyd180
    elif i==3:
        xd=xd270
        xyd=xyd270
    for j in range(200001):
        xl=xd[j]
        nxl=len(xl)
        if nxl<=1: continue
        elif nxl>1:
            for i in range(1,nxl):
                if xl[i][1]=='D' and xl[i-1][1]=='U':
                    ans=min(ans, (xl[i][0]-xl[i-1][0])*5)
    for j in range(400001):
        xyl=xyd[j]
        nxyl=len(xyl)
        if nxyl<=1: continue
        if nxyl>1:
            for i in range(1,nxyl):
                if xyl[i][1]=='R' and xyl[i-1][1]=='U':
                    ans=min(ans, (xyl[i][0]-xyl[i-1][0])*10)            

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
from collections import defaultdict
import bisect
xd0=defaultdict(list)
xd90=defaultdict(list)
xd180=defaultdict(list)
xd270=defaultdict(list)
xyd0=defaultdict(list)
xyd90=defaultdict(list)
xyd180=defaultdict(list)
xyd270=defaultdict(list)

def rotate(x,y,u):
    if u=='U': u0='R'
    elif u=='R': u0='D'
    elif u=='D': u0='L'
    else: u0='U'
    x0=y
    y0=200000-x
    return x0,y0,u0

for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=='U' or u=='D':
        bisect.insort(xd0[x],(y,u))
    x90,y90,u90=rotate(x,y,u)
    if u90=='U' or u90=='D':
        bisect.insort(xd90[x90],(y90,u90))
    x180,y180,u180=rotate(x90,y90,u90)
    if u180=='U' or u180=='D':
        bisect.insort(xd180[x180],(y180,u180))
    x270,y270,u270=rotate(x180,y180,u180)
    if u270=='U' or u270=='D':
        bisect.insort(xd270[x270],(y270,u270))
    if u=='U' or u=='R':
        bisect.insort(xyd0[x+y],(y,u))
    if u90=='U' or u90=='R':
        bisect.insort(xyd90[x90+y90],(y90,u90))
    if u180=='U' or u180=='R':
        bisect.insort(xyd180[x180+y180],(y180,u180))
    if u270=='U' or u270=='R':
        bisect.insort(xyd270[x270+y270],(y270,u270))

ans=float('inf')
for i in range(4):
    if i==0:
        xd=xd0
        xyd=xyd0
    elif i==1:
        xd=xd90
        xyd=xyd90        
    elif i==2:
        xd=xd180
        xyd=xyd180
    elif i==3:
        xd=xd270
        xyd=xyd270
    for j in range(400001):
        xl=xd[j]
        nxl=len(xl)
        if nxl>1:
            for i in range(1,nxl):
                if xl[i][1]=='D' and xl[i-1][1]=='U':
                    ans=min(ans, (xl[i][0]-xl[i-1][0])*5)
        xyl=xyd[j]
        nxyl=len(xyl)
        if nxyl>1:
            for i in range(1,nxyl):
                if xyl[i][1]=='R' and xyl[i-1][1]=='U':
                    ans=min(ans, (xyl[i][0]-xyl[i-1][0])*10)            

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
from collections import defaultdict
import bisect
xd0=defaultdict(list)
xd90=defaultdict(list)
xd180=defaultdict(list)
xd270=defaultdict(list)
xyd0=defaultdict(list)
xyd90=defaultdict(list)
xyd180=defaultdict(list)
xyd270=defaultdict(list)

def rotate(x,y,u):
    if u=='U': u0='R'
    elif u=='R': u0='D'
    elif u=='D': u0='L'
    else: u0='U'
    x0=y
    y0=200000-x
    return x0,y0,u0


for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=='U' or u=='D':
        bisect.insort(xd0[x],(y,u))
    x90,y90,u90=rotate(x,y,u)
    if u90=='U' or u90=='D':
        bisect.insort(xd90[x90],(y90,u90))
    x180,y180,u180=rotate(x90,y90,u90)
    if u180=='U' or u180=='D':
        bisect.insort(xd180[x180],(y180,u180))
    x270,y270,u270=rotate(x180,y180,u180)
    if u270=='U' or u270=='D':
        bisect.insort(xd270[x270],(y270,u270))
    if u=='U' or u=='R':
        bisect.insort(xyd0[x+y],(y,u))
    if u90=='U' or u90=='R':
        bisect.insort(xyd90[x90+y90],(y90,u90))
    if u180=='U' or u180=='R':
        bisect.insort(xyd180[x180+y180],(y180,u180))
    if u270=='U' or u270=='R':
        bisect.insort(xyd270[x270+y270],(y270,u270))

ans=float('inf')
for i in range(4):
    if i==0:
        xd=xd0
        xyd=xyd0
    elif i==1:
        xd=xd90
        xyd=xyd90        
    elif i==2:
        xd=xd180
        xyd=xyd180
    elif i==3:
        xd=xd270
        xyd=xyd270
    for j in range(400001):
        xl=xd[j]
        nxl=len(xl)
        if nxl>1:
            for i in range(1,nxl):
                if xl[i][1]=='D' and xl[i-1][1]=='U':
                    ans=min(ans, (xl[i][0]-xl[i-1][0])*5)
        xyl=xyd[j]
        nxyl=len(xyl)
        if nxyl>1:
            for i in range(1,nxyl):
                if xyl[i][1]=='R' and xyl[i-1][1]=='U':
                    ans=min(ans, (xyl[i][0]-xyl[i-1][0])*10)            

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


D_sum = defaultdict(list)
D_diff = defaultdict(list)
DX = defaultdict(list)
DY = defaultdict(list)
n = I()
L = []
ans = INF
for i in range(n):
    x, y, u = LS()
    x = int(x)
    y = int(y)
    D_sum[(x + y, u)] += [x]
    D_diff[(x - y, u)] += [x]
    DX[x, u] += [y]
    DY[y, u] += [x]
    L += [(x, y, u)]

for xi, yi, u in L:
    if u == "R" and D_diff[(xi - yi, "D")]:
        ll = sorted(D_diff[(xi - yi, "D")])
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "R" and D_sum[(xi + yi, "U")]:
        ll = sorted(D_sum[(xi + yi, "U")])
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "L" and D_diff[(xi - yi , "U")]:
        ll = sorted(D_diff[(xi - yi, "U")])
        if xi > ll[0]:
            ii = bisect_right(ll, xi)
            ans = min(ans, xi - ll[ii - 1])
    if u == "L" and D_sum[(xi + yi, "D")]:
        ll = sorted(D_sum[(xi + yi, "D")])
        if xi > ll[0]:
            ii = bisect_right(ll, xi)
            ans = min(ans, xi - ll[ii - 1])
    if u == "R" and DY[yi, "L"]:
        ll = sorted(DY[(yi, "L")])
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, (ll[ii] - xi) / 2)
    if u == "U" and DX[xi, "D"]:
        ll = sorted(DX[(xi, "D")])
        ii = bisect_right(ll, yi)
        if ii < len(ll):
            ans = min(ans, abs(ll[ii] - yi) / 2)


"""
L1 = []
L2 = []
L3 = []
L4 = []
for xk, yk ,u in L:
    L1 += [(xk - yk)]
    L2 += [(- xk - yk)]
    L3 += [(xk + yk)]
    L4 += [(- xk + yk)]

print(L1)
print(L2)
print(L3)
print(L4)

"""

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

Submission status: Time Limit Exceeded

Solution code:
INF = 2000000000


def calc_xx(A, B, mult, k, diff_func):
    AA = list(sorted(A, key=lambda pp: pp[k]))
    BB = list(sorted(B, key=lambda pp: pp[k]))

    a = 0
    b = 0

    min_time = INF
    while a < len(A) and b < len(B):
        # 衝突判定 (ソートの重複値の全組み合わせで検証)
        if AA[a][k] == BB[b][k]:
            astart = a
            asame = a + 1
            while asame < len(A) and AA[asame][k] == AA[a][k]:
                asame += 1
            aend = asame - 1

            bstart = b
            bsame = b + 1
            while bsame < len(B) and BB[bsame][k] == BB[b][k]:
                bsame += 1
            bend = bsame - 1

            for aa in range(astart, aend + 1):
                for bb in range(bstart, bend + 1):
                    diff = diff_func(AA[aa], BB[bb])
                    if diff > 0:
                        hit_time = diff * mult
                        min_time = min(min_time, hit_time)

            a = aend + 1
            b = bend + 1
        elif a == len(A) - 1:
            b += 1
        elif b == len(B) - 1:
            a += 1
        elif AA[a][k] > BB[b][k]:
            b += 1
        elif AA[a][k] < BB[b][k]:
            a += 1
        else:
            raise Exception

    return min_time


def main():
    N = int(input())
    PLANES = []

    U = []
    R = []
    D = []
    L = []
    for i in range(N):
        # x=c[0]
        # y=c[1]
        # u=c[2]
        p = input().split()
        p[0] = int(p[0])
        p[1] = int(p[1])

        pp = [p[0], p[1], (p[0] + p[1]), (p[1] - p[0])]

        PLANES.append(p)
        if p[2] == "U":
            U.append(pp)
        elif p[2] == "R":
            R.append(pp)
        elif p[2] == "D":
            D.append(pp)
        else:
            L.append(pp)

    min_time = min(
        calc_xx(U, R, 10, 2, lambda a, b: a[0] - b[0]),
        calc_xx(U, D, 5, 0, lambda a, b: b[1] - a[1]),
        calc_xx(U, L, 10, 3, lambda a, b: b[0] - a[0]),
        calc_xx(R, D, 10, 3, lambda a, b: b[0] - a[0]),
        calc_xx(R, L, 5, 1, lambda a, b: b[0] - a[0]),
        calc_xx(D, L, 10, 2, lambda a, b: b[0] - a[0])
    )

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


main()

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
input = stdin.read

n, *arr = input().split()

U = []
D = []
R = []
L = []

for i in range(int(n)):
    x, y, di = arr[i*3], arr[i*3 + 1], arr[i*3 + 2]
    t = int(x), int(y)
    if di=='U':
        U.append(t)
    elif di=='D':
        D.append(t)
    elif di=='R':
        R.append(t)
    elif di=='L':
        L.append(t)

ans = None

for x1, y1 in L:
    for x2, y2 in R:
        if y2!=y1 or x2>x1:
            continue

        t = (x1-x2)*5
        if not ans:
            ans = t
        elif ans>t:
            ans = t
        

for x1, y1 in D:
    for x2, y2 in U:
        if x2!=x1 or y2>y1:
            continue

        t = (y1-y2)*5
        if not ans:
            ans = t
        elif ans>t:
            ans = t
        
for x1, y1 in L:
    for x2, y2 in U:
        if x2>=x1 or y2>=y1 or y1-y2!=x1-x2:
            continue

        t = (y1-y2)*10
        if not ans:
            ans = t
        elif ans>t:
            ans = t
        
for x1, y1 in R:
    for x2, y2 in U:
        if x1>=x2 or y2>=y1 or y1-y2!=x2-x1:
            continue
        
        t = (y1-y2)*10
        if not ans:
            ans = t
        elif ans>t:
            ans = t

for x1, y1 in D:
    for x2, y2 in L:
        if y2>=y1 or x1>=x2 or y1-y2!=x2-x1:
            continue
        
        t = (y1-y2)*10
        if not ans:
            ans = t
        if ans>t:
            ans = t
        
for x1, y1 in D:
    for x2, y2 in R:
        if y2>=y1 or x2>=x1 or y1-y2!=x1-x2:
            continue
        
        t = (y1-y2)*10
        if not ans:
            ans = t
        if ans>t:
            ans = t

print(ans if ans else 'SAFE')

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
input = stdin.read

n = input().split()

U = []
D = []
R = []
L = []

for i in range(int(n[0])):
    x, y, di = n[1 + i*3], n[i*3 + 2], n[i*3 + 3]
    x = int(x)
    y = int(y)
    if di=='U':
        U.append((x, y, di))
    if di=='D':
        D.append((x, y, di))
    if di=='R':
        R.append((x, y, di))
    if di=='L':
        L.append((x, y, di))

ans = None

for x1, y1, d1 in L:
    for x2, y2, d2 in R:
        if y2!=y1 or x2>x1:
            continue
        if not ans:
            ans = (x1-x2)*5
        elif ans>(x1-x2)*5:
            ans = (x1-x2)*5
        

for x1, y1, d1 in D:
    for x2, y2, d2 in U:
        if x2!=x1 or y2>y1:
            continue
        if not ans:
            ans = (y1-y2)*5
        elif ans>(y1-y2)*5:
            ans = (y1-y2)*5
        
for x1, y1, d1 in L:
    for x2, y2, d2 in U:
        if x2>=x1 or y2>=y1 or y1-y2!=x1-x2:
            continue
        if not ans:
            ans = (y1-y2)*10
        elif ans>(y1-y2)*10:
            ans = (y1-y2)*10
        
for x1, y1, d1 in R:
    for x2, y2, d2 in U:
        if x1>=x2 or y2>=y1 or y1-y2!=x2-x1:
            continue
        if not ans:
            ans = (y1-y2)*10
        elif ans>(y1-y2)*10:
            ans = (y1-y2)*10

for x1, y1, d1 in D:
    for x2, y2, d2 in L:
        if y2>=y1 or x1>=x2 or y1-y2!=x2-x1:
            continue
        if not ans:
            ans = (y1-y2)*10
        if ans>(y1-y2)*10:
            ans = (y1-y2)*10
        
for x1, y1, d1 in D:
    for x2, y2, d2 in R:
        if y2>=y1 or x2>=x1 or y1-y2!=x1-x2:
            continue
        if not ans:
            ans = (y1-y2)*10
        if ans>(y1-y2)*10:
            ans = (y1-y2)*10

print(ans if ans else 'SAFE')

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
input = stdin.read

n = input().split()

U = []
D = []
R = []
L = []

for i in range(int(n[0])):
    x, y, di = n[1 + i*3], n[i*3 + 2], n[i*3 + 3]
    x = int(x)
    y = int(y)
    if di=='U':
        U.append((x, y, di))
    if di=='D':
        D.append((x, y, di))
    if di=='R':
        R.append((x, y, di))
    if di=='L':
        L.append((x, y, di))

ans = 200000200000

for x1, y1, d1 in L:
    for x2, y2, d2 in R:
        if y2!=y1 or x2>x1:
            continue
        ans = min(ans, (x1-x2)*5)

for x1, y1, d1 in D:
    for x2, y2, d2 in U:
        if x2!=x1 or y2>y1:
            continue
        ans = min(ans, abs(y1-y2)*5)
        
for x1, y1, d1 in L:
    for x2, y2, d2 in U:
        if x2>=x1 or y2>=y1 or y1-y2!=x1-x2:
            continue
        ans = min(ans, (y1-y2)*10)

for x1, y1, d1 in R:
    for x2, y2, d2 in U:
        if x1>=x2 or y2>=y1 or y1-y2!=x2-x1:
            continue
        ans = min(ans, (y1-y2)*10)

for x1, y1, d1 in D:
    for x2, y2, d2 in L:
        if y2>=y1 or x1>=x2 or y1-y2!=x2-x1:
            continue
        ans = min(ans, (y1-y2)*10)
        
for x1, y1, d1 in D:
    for x2, y2, d2 in R:
        if y2>=y1 or x2>=x1 or y1-y2!=x1-x2:
            continue
        ans = min(ans, (y1-y2)*10)

if ans==200000200000:
    print('SAFE')

else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
input = stdin.read

n = input().split()
p = []
#print(n)
for i in range(int(n[0])):
    x, y, di = n[1 + i*3], n[i*3 + 2], n[i*3 + 3]
    x = int(x)
    y = int(y)
    p.append((x, y, di))

p.sort(key = lambda x:x[2])

ans = 200000200000
for x1, y1, d1 in p:
    for x2, y2, d2 in p:
        
        if d1==d2:
            continue

        elif (d1=='L' and d2=='R'):            
            if y2!=y1 or x2>x1:
                continue
            ans = min(ans, (x1-x2)*5)
        
        elif (d1=='D' and d2=='U'):
            if x2!=x1 or y2>y1:
                continue
            ans = min(ans, abs(y1-y2)*5)
        
        elif (d1=='L' and d2=='U'):
            if x2>=x1 or y2>=y1 or y1-y2!=x1-x2:
                continue
            ans = min(ans, (y1-y2)*10)

        elif (d1=='R' and d2=='U'):
            if x1>=x2 or y2>=y1 or y1-y2!=x2-x1:
                continue
            ans = min(ans, (y1-y2)*10)
        
        elif (d1=='D' and d2=='L'):
            if y2>=y1 or x1>=x2 or y1-y2!=x2-x1:
                continue
            ans = min(ans, (y1-y2)*10)
        
        elif (d1=='D' and d2=='R'):
            if y2>=y1 or x2>=x1 or y1-y2!=x1-x2:
                continue
            ans = min(ans, (y1-y2)*10)

if ans==200000200000:
    print('SAFE')

else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
input = stdin.read

n = input().split()
p = []
#print(n)
for i in range(int(n[0])):
    x, y, di = n[1 + i*3], n[i*3 + 2], n[i*3 + 3]
    x = int(x)
    y = int(y)
    p.append((x, y, di))

ans = 200000200000
for x1, y1, d1 in p:
    for x2, y2, d2 in p:
        if d1==d2:
            continue
        elif (d1=='R' and d2=='L'):            
            if y1!=y2 or x1>x2:
                continue
            ans = min(ans, (x2-x1)*5)
        elif (d1=='U' and d2=='D'):
            if x1!=x2 or y1>y2:
                continue
            ans = min(ans, abs(y2-y1)*5)
        
        elif (d1=='U' and d2=='L'):
            if x1>=x2 or y1>=y2 or y2-y1!=x2-x1:
                continue
            ans = min(ans, (y2-y1)*10)
        elif (d1=='U' and d2=='R'):
            if x2>=x1 or y1>=y2 or y2-y1!=x1-x2:
                continue
            ans = min(ans, (y2-y1)*10)
        elif (d1=='D' and d2=='L'):
            if y2>=y1 or x1>=x2 or y1-y2!=x2-x1:
                continue
            ans = min(ans, (y1-y2)*10)
        elif (d1=='D' and d2=='R'):
            if y2>=y1 or x2>=x1 or y1-y2!=x1-x2:
                continue
            ans = min(ans, (y1-y2)*10)
if ans==200000200000:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = []
for _ in range(n):
    x, y, di = input().split()
    x = int(x)
    y = int(y)
    p.append((x, y, di))

#print(p)
ans = 200000200000200000
for x1, y1, d1 in p:
    for x2, y2, d2 in p:
        #print(d1, d2)
        if d1==d2:
            continue
        elif (d1=='R' and d2=='L'):# or (d2=='R' and d1=='L'):
#             if d2=='R':
#                 x1, x2 = x2, x1
#                 y1, y2 = y2, y1
#                 d1, d2 = d2, d1
            
            if y1!=y2 or x1>x2:
                continue
            ans = min(ans, (x2-x1)*5)
            #print(ans)
        elif (d1=='U' and d2=='D'):# or (d2=='U' and d1=='D'):
#             if d2=='U':
#                 x1, x2 = x2, x1
#                 y1, y2 = y2, y1
#                 d1, d2 = d2, d1
            if x1!=x2 or y1>y2:
                continue
            ans = min(ans, abs(y2-y1)*5)
            #print(ans)
        
        elif (d1=='U' and d2=='L'):# or (d1=='L' and d2=='U'):
#             if d1=='L':
#                 x1, x2 = x2, x1
#                 y1, y2 = y2, y1
#                 d1, d2 = d2, d1
            if x1>=x2 or y1>=y2 or y2-y1!=x2-x1:
                continue
            ans = min(ans, (y2-y1)*10)
            #print(ans)
        elif (d1=='U' and d2=='R'):# or (d1=='R' and d2=='U'):
#             if d1=='R':
#                 x1, x2 = x2, x1
#                 y1, y2 = y2, y1
#                 d1, d2 = d2, d1
            if x2>=x1 or y1>=y2 or y2-y1!=x1-x2:
                continue
            ans = min(ans, (y2-y1)*10)
            #print(ans)
        elif (d1=='D' and d2=='L'):# or (d1=='L' and d2=='D'):
#             if d1=='L':
#                 x1, x2 = x2, x1
#                 y1, y2 = y2, y1
#                 d1, d2 = d2, d1
            if y2>=y1 or x1>=x2 or y1-y2!=x2-x1:
                continue
            ans = min(ans, (y1-y2)*10)
            #print(ans)
        elif (d1=='D' and d2=='R'):# or (d1=='R' and d2=='D'):
#             if d1=='R':
#                 x1, x2 = x2, x1
#                 y1, y2 = y2, y1
#                 d1, d2 = d2, d1
            if y2>=y1 or x2>=x1 or y1-y2!=x1-x2:
                continue
            ans = min(ans, (y1-y2)*10)
            #print(ans)
        #print(ans, x1, y1, d1, x2, y2, d2)
if ans==200000200000200000:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
b = 2000001
u = []; r = []; d = []; l = []
for i in range(n):
    A = list(input().split())
    a = [int(A[0]), int(A[1])]
    if A[2] == "U":
        u.append(a)
    elif A[2] == "R":
        r.append(a)
    elif A[2] == "D":
        d.append(a)
    else:
        l.append(a)
#ud
u1 = {}; d1 = {}
for i in range(len(u)):
    if u[i][0] not in u1:
        u1[u[i][0]] = []
    u1[u[i][0]].append(u[i][1])
for i in range(len(d)):
    if d[i][0] not in d1:
        d1[d[i][0]] = []
    d1[d[i][0]].append(d[i][1])
for i in range(200001):
    if i in u1 and i in d1:
        u1[i].sort()
        d1[i].sort()
        for j in range(len(u1[i])):
            for k in range(len(d1[i])):
                if u1[i][j] < d1[i][k]:
                    b = min(b, (d1[i][k]-u1[i][j])*5)
                    break
#rl
r1 = {}; l1 = {}
for i in range(len(r)):
    if r[i][1] not in r1:
        r1[r[i][1]] = []
    r1[r[i][1]].append(r[i][0])
for i in range(len(l)):
    if l[i][1] not in l1:
        l1[l[i][1]] = []
    l1[l[i][1]].append(l[i][0])
for i in range(200001):
    if i in r1 and i in l1:
        r1[i].sort()
        l1[i].sort()
        for j in range(len(r1[i])):
            for k in range(len(l1[i])):
                if r1[i][j] < l1[i][k]:
                    b = min(b, (l1[i][k]-r1[i][j])*5)
                    break
#ur
u2 = {}; r2 = {}
for i in range(len(u)):
    if u[i][0]+u[i][1] not in u2:
        u2[u[i][0]+u[i][1]] = []
    u2[u[i][0]+u[i][1]].append(u[i][0])
for i in range(len(r)):
    if r[i][0]+r[i][1] not in r2:
        r2[r[i][0]+r[i][1]] = []
    r2[r[i][0]+r[i][1]].append(r[i][0])
for i in range(400001):
    if i in u2 and i in r2:
        u2[i].sort()
        r2[i].sort()
        for j in range(len(r2[i])):
            for k in range(len(u2[i])):
                if r2[i][j] < u2[i][k]:
                    b = min(b, (u2[i][k]-r2[i][j])*10)
                    break
#ld
l2 = {}; d2 = {}
for i in range(len(l)):
    if l[i][0]+l[i][1] not in l2:
        l2[l[i][0]+l[i][1]] = []
    l2[l[i][0]+l[i][1]].append(l[i][0])
for i in range(len(d)):
    if d[i][0]+d[i][1] not in d2:
        d2[d[i][0]+d[i][1]] = []
    d2[d[i][0]+d[i][1]].append(d[i][0])
for i in range(400001):
    if i in l2 and i in d2:
        l2[i].sort()
        d2[i].sort()
        for j in range(len(d2[i])):
            for k in range(len(l2[i])):
                if d2[i][j] < l2[i][k]:
                    b = min(b, (l2[i][k]-d2[i][j])*10)
                    break
#lu
l3 = {}; u3 = {}
for i in range(len(l)):
    if l[i][0]-l[i][1] not in l3:
        l3[l[i][0]-l[i][1]] = []
    l3[l[i][0]-l[i][1]].append(l[i][0])
for i in range(len(u)):
    if u[i][0]-u[i][1] not in u3:
        u3[u[i][0]-u[i][1]] = []
    u3[u[i][0]-u[i][1]].append(u[i][0])
for i in range(-200000, 200001):
    if i in l3 and i in u3:
        l3[i].sort()
        u3[i].sort()
        for j in range(len(u3[i])):
            for k in range(len(l3[i])):
                if u3[i][j] < l3[i][k]:
                    b = min(b, (l3[i][k]-u3[i][j])*10)
                    break
#dr
d3 = {}; r3 = {}
for i in range(len(d)):
    if d[i][0]-d[i][1] not in d3:
        d3[d[i][0]-d[i][1]] = []
    d3[d[i][0]-d[i][1]].append(d[i][0])
for i in range(len(r)):
    if r[i][0]-r[i][1] not in r3:
        r3[r[i][0]-r[i][1]] = []
    r3[r[i][0]-r[i][1]].append(r[i][0])
for i in range(-200000, 200001):
    if i in d3 and i in r3:
        d3[i].sort()
        r3[i].sort()
        for j in range(len(r3[i])):
            for k in range(len(d3[i])):
                if r3[i][j] < d3[i][k]:
                    b = min(b, (d3[i][k]-r3[i][j])*10)
                    break
print("SAFE") if b == 2000001 else print(b)