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: Wrong Answer

Solution code:
from collections import defaultdict
n = int(input())
x = [0] * n
y = [0] * n
dir = [0] * n
INF = 10**8


def g(v):
    v.sort(key=lambda x: x[0])
    ret = INF
    for i in range(1, len(v)):
        if v[i - 1][1] == 0 and v[1][1] != 0:
            ret = min(ret, v[i][0] - v[i - 1][0])
    return ret


def f(d):
    ret = INF
    for k, v in d.items():
        ret = min(ret, g(v))
    return ret


for i in range(n):
    # x[i], y[i], c = map(int, input().split())
    sx, sy, c = input().split()
    x[i] = int(sx)
    y[i] = int(sy)
    if c == 'U':
        dir[i] = 0
    if c == 'R':
        dir[i] = 1
    if c == 'D':
        dir[i] = 2
    if c == 'L':
        dir[i] = 3

ans = float('inf')
for ri in range(4):
    # UD
    d = defaultdict(list)
    for i in range(n):
        if dir[i] != 0 and dir[i] != 2:
            continue
        d[x[i]].append((y[i], dir[i]))
    ans = min(ans, f(d) * 5)
    # UR
    d = defaultdict(list)
    for i in range(n):
        if dir[i] != 0 and dir[i] != 1:
            continue
        d[x[i] + y[i]].append((y[i], dir[i]))
    ans = min(ans, f(d) * 10)

    # rotate
    for i in range(n):
        px = x[i]
        py = y[i]
        x[i] = py
        y[i] = -px
        dir[i] = (dir[i] + 1) % 4
if ans >= INF:
    print('SAFE')
else:
    print(ans)

Submission status: Wrong Answer

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] += [(x, u)]
    D_diff[x - y] += [(x, u)]
    DX[x] += [(y, u)]
    DY[y] += [(x, u)]


for _, co_list in D_sum.items():
    co_list.sort()
    r = d = -INF
    for co, direction in co_list:
        if direction == "R":
            r = co
        elif direction == "D":
            d = co
        elif direction == "U":
            ans = min(co - r, ans)
        else:
            ans = min(co - d, ans)

for _, co_list in D_diff.items():
    co_list.sort()
    u = r = -INF
    for co, direction in co_list:
        if direction == "U":
            u = co
        elif direction == "R":
            r = co
        elif direction == "D":
            ans = min(co - r, ans)
        else:
            ans = min(co - u, ans)


for _, co_list in DX.items():
    co_list.sort()
    u = -INF
    for co, direction in co_list:
        coo = co
        if direction == "U":
            u = co
        else:
            ans = min((co - u) / 2, ans)


for _, co_list in DY.items():
    co_list.sort()
    r = -INF
    for co, direction in co_list:
        if direction == "R":
            r = co
        else:
            ans = min((co - r) / 2, ans)


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







"""
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)

"""

Submission status: Wrong Answer

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] += [(x, u)]
    D_diff[x - y] += [(x, u)]
    DX[x] += [(y, u)]
    DY[y] += [(x, u)]


for _, co_list in D_sum.items():
    co_list.sort()
    r = d = -INF
    for co, direction in co_list:
        if direction == "R":
            r = co
        elif direction == "D":
            d = co
        elif direction == "U":
            ans = min(co - r, ans)
        else:
            ans = min(co - d, ans)

for _, co_list in D_diff.items():
    co_list.sort()
    u = r = -INF
    for co, direction in co_list:
        if direction == "U":
            u = co
        elif direction == "R":
            r = co
        elif direction == "D":
            ans = min(co - r, ans)
        else:
            ans = min(co - u, ans)


for _, co_list in DX.items():
    co_list.sort()
    u = -INF
    for co, direction in co_list:
        coo = co
        if direction == "U":
            u = co
        else:
            ans = min((co - u) / 2, ans)


for _, co_list in DY.items():
    co_list.sort()
    l = -INF
    for co, direction in co_list:
        if direction == "L":
            l = co
        else:
            ans = min((co - l) / 2, ans)


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







"""
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)

"""

Submission status: Wrong Answer

Solution code:
INF = 2000000000


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

    a = 0
    b = 0

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

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

            # まさかの二重DP
            aa = astart
            bb = bstart
            while aa <= aend and bb <= bend:
                diff = BB[bb][diff_field] - AA[aa][diff_field]
                if diff > 0:
                    hit_time = diff * mult
                    min_time = min(min_time, hit_time)

                if aa == aend - 1:
                    bb += 1
                elif bb == bend - 1:
                    aa += 1
                elif BB[bb][diff_field] > AA[aa][diff_field]:
                    aa += 1
                else:
                    bb += 1

            a = aend + 1
            b = bend + 1

        elif a == len(A) - 1:
            b += 1
        elif b == len(B) - 1:
            a += 1
        elif AA[a][comp_field] > BB[b][comp_field]:
            b += 1
        elif AA[a][comp_field] < BB[b][comp_field]:
            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(R, U, 10, 2, 0),
        calc_xx(U, D, 5, 0, 1),
        calc_xx(U, L, 10, 3, 0),
        calc_xx(R, D, 10, 3, 0),
        calc_xx(R, L, 5, 1, 0),
        calc_xx(D, L, 10, 2, 0),
    )

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


main()

Submission status: Wrong Answer

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] += [(x, y)]
    DY[y, u] += [(x, y)]
    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, 0))
        if ii < len(ll):
            ans = min(ans, (ll[ii][0] - xi) / 2)
    if u == "U" and DX[xi, "D"]:
        ll = sorted(DX[(xi, "D")], key=lambda z:z[1])
        ii = bisect_right(ll, (yi, 0))
        if ii < len(ll):
            ans = min(ans, abs(ll[ii][1] - 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: Wrong Answer

Solution code:
N = int(input())
U, R, D, L = [], [], [], []
for _ in range(N):
    x, y, u = input().split()
    x, y = int(x), int(y)
    {
        'U': U,
        'R': R,
        'D': D,
        'L': L,
    }[u].append((x, y))


def find():
    INF = 10 ** 20
    ans = INF

    # U & D
    uxs = {x for x, y in U}
    dxs = {x for x, y in D}
    xs = uxs & dxs
    if xs:
        ys = []
        ds = {}
        for x, y in U:
            if x in xs:
                ys.append(y)
                ds[y] = 'U'
        for x, y in D:
            if x in xs:
                ys.append(y)
                ds[y] = 'D'
        ys.sort()
        for i in range(len(ys) - 1):
            y1, y2 = ys[i], ys[i + 1]
            if (ds[y1], ds[y2]) == ('U', 'D'):
                ans = min(ans, (y2 - y1) * 10 // 2)

    # L & R
    rys = {y for x, y in R}
    lys = {y for x, y in L}
    ys = rys & lys
    if ys:
        xs = []
        ds = {}
        for x, y in R:
            if y in ys:
                xs.append(x)
                ds[x] = 'R'
        for x, y in L:
            if y in ys:
                xs.append(x)
                ds[x] = 'L'
        xs.sort()
        for i in range(len(xs) - 1):
            x1, x2 = xs[i], xs[i + 1]
            if (ds[x1], ds[x2]) == ('R', 'L'):
                ans = min(ans, (x2 - x1) * 10 // 2)

    # U & R
    r = sorted(R, key=lambda xy: xy[1] - xy[0])
    for ux, uy in U:
        s, e = 0, len(r)
        while s + 1 < e:
            m = (s + e) // 2
            rx, ry = r[m]
            if 0 < ux - rx == ry - uy:
                ans = min(ans, (ux - rx) * 10)
                break
            if ux - rx < ry - uy:
                e = m
            else:
                s = m
        if s < len(r):
            rx, ry = r[s]
            if 0 < ux - rx == ry - uy:
                ans = min(ans, (ux - rx) * 10)

    # U & L
    l = sorted(L, key=lambda xy: xy[0] + xy[1])
    for ux, uy in U:
        s, e = 0, len(l)
        while s + 1 < e:
            m = (s + e) // 2
            lx, ly = l[m]
            if 0 < lx - ux == ly - uy:
                ans = min(ans, (lx - ux) * 10)
                break
            if lx - ux < ly - uy:
                e = m
            else:
                s = m
        if s < len(l):
            lx, ly = l[s]
            if 0 < lx - ux == ly - uy:
                ans = min(ans, (lx - ux) * 10)

    # D & R
    r = sorted(R, key=lambda xy: -xy[0] - xy[1])
    for dx, dy in D:
        s, e = 0, len(r)
        while s + 1 < e:
            m = (s + e) // 2
            rx, ry = r[m]
            if 0 < dx - rx == dy - ry:
                ans = min(ans, (dx - rx) * 10)
                break
            if dx - rx < dy - ry:
                e = m
            else:
                s = m
        if s < len(R):
            rx, ry = r[s]
            if 0 < dx - rx == dy - ry:
                ans = min(ans, (dx - rx) * 10)

    # D & L
    l = sorted(L, key=lambda xy: xy[0] - xy[1])
    for dx, dy in D:
        s, e = 0, len(l)
        while s + 1 < e:
            m = (s + e) // 2
            lx, ly = l[m]
            if 0 < lx - dx == dy - ly:
                ans = min(ans, (lx - dx) * 10)
                break
            if lx - dx < dy - ly:
                e = m
            else:
                s = m
        if s < len(l):
            lx, ly = l[s]
            if 0 < lx - dx == dy - ly:
                ans = min(ans, (lx - dx) * 10)

    if ans == INF:
        return 'SAFE'
    return ans

print(find())

Submission status: Wrong Answer

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):
        ap = AA[a]
        bp = BB[b]
        diff = diff_func(ap, bp)

        # 衝突判定
        if ap[k] == bp[k] and diff > 0:
            hit_time = diff * mult
            min_time = min(min_time, hit_time)

        # インデックス進める
        if a == len(A) - 1:
            b += 1
        elif b == len(B) - 1:
            a += 1
        elif ap[k] > bp[k]:
            b += 1
        elif ap[k] < bp[k]:
            a += 1
        elif BB[b + 1][k] > bp[k]:
            a += 1
        else:
            b += 1
        # elif AA[a + 1][k] > ap[k]:
        #     b += 1
        # else:
        #     a += 1

    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: Wrong Answer

Solution code:
INF = 2000000000


def calc_dl(D, L):
    DD = list(sorted(D, key=lambda pp: pp[0] + pp[1]))
    LL = list(sorted(L, key=lambda pp: pp[0] + pp[1]))
    d = 0
    l = 0

    min_time = INF
    while d < len(D) and l < len(L):
        # 衝突判定
        if (dp[0] + dp[1]) == (lp[0] + lp[1]) and dp[0] < lp[0]:
            hit_time = (lp[0] - dp[0]) * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if d == len(D) - 1:
            l += 1
        elif l == len(L) - 1:
            d += 1
        elif (dp[0] + dp[1]) > (lp[0] + lp[1]):
            l += 1
        elif (dp[0] + dp[1]) < (lp[0] + lp[1]):
            d += 1
        elif (DD[d + 1][0] + DD[d + 1][1]) > (dp[0] + dp[1]):
            l += 1
        else:
            d += 1

    return min_time


def calc_rl(R, L):
    RR = list(sorted(R, key=lambda pp: pp[1]))
    LL = list(sorted(L, key=lambda pp: pp[1]))
    r = 0
    l = 0

    min_time = INF
    while r < len(R) and l < len(L):
        # 衝突判定
        if rp[1] == lp[1] and rp[0] < lp[0]:
            hit_time = (lp[0] - rp[0]) * 5
            min_time = min(min_time, hit_time)

        # インデックス進める
        if r == len(R) - 1:
            l += 1
        elif l == len(L) - 1:
            r += 1
        elif rp[1] > lp[1]:
            l += 1
        elif rp[1] < lp[1]:
            r += 1
        elif RR[r + 1][1] > rp[1]:
            l += 1
        else:
            r += 1

    return min_time


def calc_rd(R, D):
    RR = list(sorted(R, key=lambda pp: pp[1] - pp[0]))
    DD = list(sorted(D, key=lambda pp: pp[1] - pp[0]))
    r = 0
    d = 0

    min_time = INF
    while r < len(R) and d < len(D):
        # 衝突判定
        if (rp[1] - rp[0]) == (dp[1] - dp[0]) and rp[0] < dp[0]:
            hit_time = (dp[0] - rp[0]) * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if r == len(R) - 1:
            d += 1
        elif d == len(D) - 1:
            r += 1
        elif (rp[1] - rp[0]) > (dp[1] - dp[0]):
            d += 1
        elif (rp[1] - rp[0]) < (dp[1] - dp[0]):
            r += 1
        elif (RR[r + 1][1] - RR[r + 1][0]) > (rp[1] - rp[0]):
            d += 1
        else:
            r += 1

    return min_time


def calc_ul(U, L):
    UU = list(sorted(U, key=lambda pp: pp[1] - pp[0]))
    LL = list(sorted(L, key=lambda pp: pp[1] - pp[0]))
    u = 0
    l = 0

    min_time = INF
    while u < len(U) and l < len(L):
        # 衝突判定
        if (up[1] - up[0]) == (lp[1] - lp[0]) and up[0] < lp[0]:
            hit_time = (lp[0] - up[0]) * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if u == len(U) - 1:
            l += 1
        elif l == len(L) - 1:
            u += 1
        elif (up[1] - up[0]) > (lp[1] - lp[0]):
            l += 1
        elif (up[1] - up[0]) < (lp[1] - lp[0]):
            u += 1
        elif (UU[u + 1][1] - UU[u + 1][0]) > (up[1] - up[0]):
            l += 1
        else:
            u += 1

    return min_time


def calc_ur(U, R):
    k = 2
    UU = list(sorted(U, key=lambda pp: pp[k]))
    RR = list(sorted(R, key=lambda pp: pp[k]))
    u = 0
    r = 0

    min_time = INF
    while u < len(U) and r < len(R):
        up = UU[u]
        rp = RR[r]
        diff = up[0] - rp[0]

        # 衝突判定
        if up[k] == rp[k] and diff > 0:
            hit_time = diff * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if u == len(U) - 1:
            r += 1
        elif r == len(R) - 1:
            u += 1
        elif up[k] > rp[k]:
            r += 1
        elif up[k] < rp[k]:
            u += 1
        elif UU[u + 1][k] > up[k]:
            r += 1
        else:
            u += 1

    return min_time


def calc_ud(U, D):
    k = 0
    UU = list(sorted(U, key=lambda pp: pp[k]))
    DD = list(sorted(D, key=lambda pp: pp[k]))
    u = 0
    d = 0

    min_time = INF
    while u < len(U) and d < len(D):
        up = UU[u]
        dp = DD[d]
        diff = dp[1] - up[1]

        # 衝突判定
        if up[k] == dp[k] and diff > 0:
            hit_time = diff * 5
            min_time = min(min_time, hit_time)

        # インデックス進める
        if u == len(U) - 1:
            d += 1
        elif d == len(D) - 1:
            u += 1
        elif up[k] > dp[k]:
            d += 1
        elif up[k] < dp[k]:
            u += 1
        elif UU[u + 1][k] > up[k]:
            d += 1
        else:
            u += 1

    return min_time


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):
        ap = AA[a]
        bp = BB[b]
        diff = diff_func(ap, bp)

        # 衝突判定
        if ap[k] == bp[k] and diff > 0:
            hit_time = diff * mult
            min_time = min(min_time, hit_time)

        # インデックス進める
        if a == len(A) - 1:
            b += 1
        elif b == len(B) - 1:
            a += 1
        elif ap[k] > bp[k]:
            b += 1
        elif ap[k] < bp[k]:
            a += 1
        elif AA[a + 1][k] > ap[k]:
            b += 1
        else:
            a += 1

    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)

    # print(calc_ur(U, R))
    # print(calc_ud(U, D))
    # print(calc_ul(U, L))
    # print(calc_rd(R, D))
    # print(calc_rl(R, L))
    # print(calc_dl(D, L))

    # min_time = min(
    #     calc_ur(U, R),
    #     calc_ud(U, D),
    #     calc_ul(U, L),
    #     calc_rd(R, D),
    #     calc_rl(R, L),
    #     calc_dl(D, L)
    # )

    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: Wrong Answer

Solution code:
INF = 2000000000


def calc_dl(D, L):
    DD = list(sorted(D, key=lambda pp: pp[0] + pp[1]))
    LL = list(sorted(L, key=lambda pp: pp[0] + pp[1]))
    d = 0
    l = 0

    min_time = INF
    while d < len(D) and l < len(L):
        # 衝突判定
        if (DD[d][0] + DD[d][1]) == (LL[l][0] + LL[l][1]) and DD[d][0] < LL[l][0]:
            hit_time = (LL[l][0] - DD[d][0]) * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if d == len(D) - 1:
            l += 1
        elif l == len(L) - 1:
            d += 1
        elif (DD[d][0] + DD[d][1]) > (LL[l][0] + LL[l][1]):
            l += 1
        elif (DD[d][0] + DD[d][1]) < (LL[l][0] + LL[l][1]):
            d += 1
        elif (DD[d + 1][0] + DD[d + 1][1]) > (DD[d][0] + DD[d][1]):
            l += 1
        else:
            d += 1

    return min_time


def calc_rl(R, L):
    RR = list(sorted(R, key=lambda pp: pp[1]))
    LL = list(sorted(L, key=lambda pp: pp[1]))
    r = 0
    l = 0

    min_time = INF
    while r < len(R) and l < len(L):
        # 衝突判定
        if RR[r][1] == LL[l][1] and RR[r][0] < LL[l][0]:
            hit_time = (LL[l][0] - RR[r][0]) * 5
            min_time = min(min_time, hit_time)

        # インデックス進める
        if r == len(R) - 1:
            l += 1
        elif l == len(L) - 1:
            r += 1
        elif RR[r][1] > LL[l][1]:
            l += 1
        elif RR[r][1] < LL[l][1]:
            r += 1
        elif RR[r + 1][1] > RR[r][1]:
            l += 1
        else:
            r += 1

    return min_time


def calc_rd(R, D):
    RR = list(sorted(R, key=lambda pp: pp[1] - pp[0]))
    DD = list(sorted(D, key=lambda pp: pp[1] - pp[0]))
    r = 0
    d = 0

    min_time = INF
    while r < len(R) and d < len(D):
        # 衝突判定
        if (RR[r][1] - RR[r][0]) == (DD[d][1] - DD[d][0]) and RR[r][0] < DD[d][0]:
            hit_time = (DD[d][0] - RR[r][0]) * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if r == len(R) - 1:
            d += 1
        elif d == len(D) - 1:
            r += 1
        elif (RR[r][1] - RR[r][0]) > (DD[d][1] - DD[d][0]):
            d += 1
        elif (RR[r][1] - RR[r][0]) < (DD[d][1] - DD[d][0]):
            r += 1
        elif (RR[r + 1][1] - RR[r + 1][0]) > (RR[r][1] - RR[r][0]):
            d += 1
        else:
            r += 1

    return min_time


def calc_ul(U, L):
    UU = list(sorted(U, key=lambda pp: pp[1] - pp[0]))
    LL = list(sorted(L, key=lambda pp: pp[1] - pp[0]))
    u = 0
    l = 0

    min_time = INF
    while u < len(U) and l < len(L):
        # 衝突判定
        if (UU[u][1] - UU[u][0]) == (LL[l][1] - LL[l][0]) and UU[u][0] < LL[l][0]:
            hit_time = (LL[l][0] - UU[u][0]) * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if u == len(U) - 1:
            l += 1
        elif l == len(L) - 1:
            u += 1
        elif (UU[u][1] - UU[u][0]) > (LL[l][1] - LL[l][0]):
            l += 1
        elif (UU[u][1] - UU[u][0]) < (LL[l][1] - LL[l][0]):
            u += 1
        elif (UU[u + 1][1] - UU[u + 1][0]) > (UU[u][1] - UU[u][0]):
            l += 1
        else:
            u += 1

    return min_time


def calc_ur(U, R):
    UU = list(sorted(U, key=lambda pp: pp[0] + pp[1]))
    RR = list(sorted(R, key=lambda pp: pp[0] + pp[1]))
    u = 0
    r = 0

    min_time = INF
    while u < len(U) and r < len(R):
        # 衝突判定
        if (UU[u][0] + UU[u][1]) == (RR[r][0] + RR[r][1]) and UU[u][0] > RR[r][0]:
            hit_time = (UU[u][0] - RR[r][0]) * 10
            min_time = min(min_time, hit_time)

        # インデックス進める
        if u == len(U) - 1:
            r += 1
        elif r == len(R) - 1:
            u += 1
        elif (UU[u][0] + UU[u][1]) > (RR[r][0] + RR[r][1]):
            r += 1
        elif (UU[u][0] + UU[u][1]) < (RR[r][0] + RR[r][1]):
            u += 1
        elif (UU[u + 1][0] + UU[u + 1][1]) > (UU[u][0] + UU[u][1]):
            r += 1
        else:
            u += 1

    return min_time


def calc_ud(U, D):
    UU = list(sorted(U, key=lambda pp: pp[0]))
    DD = list(sorted(D, key=lambda pp: pp[0]))
    u = 0
    d = 0

    min_time = INF
    while u < len(U) and d < len(D):
        # 衝突判定
        if UU[u][0] == DD[d][0] and UU[u][1] < DD[d][1]:
            hit_time = (DD[d][1] - UU[u][1]) * 5
            min_time = min(min_time, hit_time)

        # インデックス進める
        if u == len(U) - 1:
            d += 1
        elif d == len(D) - 1:
            u += 1
        elif UU[u][0] > DD[d][0]:
            d += 1
        elif UU[u][0] < DD[d][0]:
            u += 1
        elif UU[u + 1][0] > UU[u][0]:
            d += 1
        else:
            u += 1

    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])
        PLANES.append(p)
        if p[2] == "U":
            U.append(p)
        elif p[2] == "R":
            R.append(p)
        elif p[2] == "D":
            D.append(p)
        else:
            L.append(p)

    # print(calc_ur(U, R))
    # print(calc_ud(U, D))
    # print(calc_ul(U, L))
    # print(calc_rd(R, D))
    # print(calc_rl(R, L))
    # print(calc_dl(D, L))

    min_time = min(
        calc_ur(U, R),
        calc_ud(U, D),
        calc_ul(U, L),
        calc_rd(R, D),
        calc_rl(R, L),
        calc_dl(D, L)
    )

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


main()