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: Accepted

Solution code:
from collections import defaultdict as dd
from bisect import bisect_left
N = int(input())

Ps = []
for _ in range(N):
    X, Y, U = input().split()
    Ps.append((int(X), int(Y), U))
Ps.sort()

case1 = dd(list)
case2 = dd(list)
case3 = dd(list)
case4 = dd(list)
case5 = dd(list)
case6 = dd(list)

INF = float('inf')
ans = INF
for x, y, u in Ps:
    if u == 'U':
        case2[y-x].append(y)
        case5[x].append(y)
        if y+x in case1:
            idx = bisect_left(case1[y+x], -y)
            if idx > 0:
                t = (-y - case1[y+x][idx-1]) * 10
                ans = ans if ans < t else t

    elif u == 'R':
        case1[y+x].append(-y)
        case3[y-x].append(y)
        case6[y].append(x)
    elif u == 'D':
        case4[y+x].append(-y)
        if y-x in case3:
            idx = bisect_left(case3[y-x], y)
            if idx > 0:
                t = (y - case3[y-x][idx-1]) * 10
                ans = ans if ans < t else t
        if x in case5:
            idx = bisect_left(case5[x], y)
            if idx > 0:
                t = (y - case5[x][idx-1]) * 5
                ans = ans if ans < t else t
    elif u == 'L':
        if y-x in case2:
            idx = bisect_left(case2[y-x], y)
            if idx > 0:
                t = (y - case2[y-x][idx-1]) * 10
                ans = ans if ans < t else t
        if y+x in case4:
            idx = bisect_left(case4[y+x], -y)
            if idx > 0:
                t = (-y - case4[y+x][idx-1]) * 10
                ans = ans if ans < t else t
        if y in case6:
            idx = bisect_left(case6[y], x)
            if idx > 0:
                t = (x - case6[y][idx-1]) * 5
                ans = ans if ans < t else t
if ans == INF:
    print('SAFE')
else:
    print(ans)

Submission status: Accepted

Solution code:

N = int(input())

UD = {}
LR = {}

RU = {}
DL = {}

UL = {}
RD = {}


for i in range(N):

    X,Y,S = input().split()
    X = int(X)
    Y = int(Y)

    if S == 'U' or S == 'D':
        if X not in UD:
            UD[X] = []
        UD[X].append((Y,S))

    if S == 'L' or S == 'R':
        if Y not in LR:
            LR[Y] = []
        LR[Y].append((X,S))

    if S == 'R' or S == 'U':
        if X+Y not in RU:
            RU[X+Y] = []
        RU[X+Y].append((X,S))

    if S == 'D' or S == 'L':
        if X+Y not in DL:
            DL[X+Y] = []
        DL[X+Y].append((X,S))

    if S == 'U' or S == 'L':
        if X-Y not in UL:
            UL[X-Y] = []
        UL[X-Y].append((Y,S))

    if S == 'R' or S == 'D':
        if X-Y not in RD:
            RD[X-Y] = []
        RD[X-Y].append((Y,S))

ans = float("inf")
for i in UD:
    lasu = float("-inf")
    lis = UD[i]
    lis.sort()
    for t,d in lis:
        if d == "U":
            lasu = t
        else:
            ans = min(ans , (t-lasu))

for i in LR:
    lasu = float("-inf")
    lis = LR[i]
    lis.sort()
    for t,d in lis:
        if d == "R":
            lasu = t
        else:
            ans = min(ans , (t-lasu))

for i in RU:
    lasu = float("-inf")
    lis = RU[i]
    lis.sort()
    for t,d in lis:
        if d == "R":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

for i in DL:
    lasu = float("-inf")
    lis = DL[i]
    lis.sort()
    for t,d in lis:
        if d == "D":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

for i in UL:
    lasu = float("-inf")
    lis = UL[i]
    lis.sort()
    for t,d in lis:
        if d == "U":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

for i in RD:
    lasu = float("-inf")
    lis = RD[i]
    lis.sort()
    for t,d in lis:
        if d == "R":
            lasu = t
        else:
            ans = min(ans , (t-lasu)*2)

if ans == float("inf"):
    print ("SAFE")
else:
    print (ans*5)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
from bisect import bisect_left, bisect_right
def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    airplane = {'U':[], 'R':[], 'D':[], 'L':[]}
    for _ in range(N):
        x, y, u = input().split()
        airplane[u].append((int(x), int(y)))
    out = float('inf')

    X = defaultdict(list)
    for x, y in airplane['U']: X[x].append((y, 1))
    for x, y in airplane['D']: X[x].append((y, -1))
    for x in X:
        X[x].sort()
        pre_y, pre_u = None, -2
        for y, u in X[x]:
            if pre_u > u: out = min(out, (y - pre_y) * 5)
            pre_y, pre_u = y, u

    Y = defaultdict(list)
    for x, y in airplane['R']: Y[y].append((x, 1))
    for x, y in airplane['L']: Y[y].append((x, -1))
    for y in Y:
        Y[y].sort()
        pre_x, pre_u = None, -2
        for x, u in Y[y]:
            if pre_u > u: out = min(out, (x - pre_x) * 5)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['U']: D[x + y].append((x, -1))
    for x, y in airplane['R']: D[x + y].append((x, 1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['D']: D[x + y].append((x, 1))
    for x, y in airplane['L']: D[x + y].append((x, -1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['D']: D[x - y].append((x, -1))
    for x, y in airplane['R']: D[x - y].append((x, 1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u

    D = defaultdict(list)
    for x, y in airplane['U']: D[x - y].append((x, 1))
    for x, y in airplane['L']: D[x - y].append((x, -1))
    for z in D:
        D[z].sort()
        pre_x, pre_u = None, -2
        for x, u in D[z]:
            if pre_u > u: out = min(out, (x - pre_x) * 10)
            pre_x, pre_u = x, u
    if out == float('inf'):
        print("SAFE")
    else:
        print(out)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
import heapq as hq
N = int(input())
dicUD = defaultdict(list)
dicRL = defaultdict(list)
dicRUp = defaultdict(list)
dicDLp = defaultdict(list)
dicRDm = defaultdict(list)
dicULm = defaultdict(list)
for i in range(N):
    X,Y,U = input().split()
    X,Y = map(int,(X,Y))
    if U == "L":
        hq.heappush(dicRL[Y],(X,"L"))
        hq.heappush(dicDLp[X+Y],(X-Y,"L"))
        hq.heappush(dicULm[X-Y],(X+Y,"L"))
    if U == "R":
        hq.heappush(dicRL[Y],(X,"R"))
        hq.heappush(dicRUp[X+Y],(X-Y,"R"))
        hq.heappush(dicRDm[X-Y],(X+Y,"R"))
    if U == "U":
        hq.heappush(dicUD[X],(Y,"R"))
        hq.heappush(dicRUp[X+Y],(X-Y,"L"))
        hq.heappush(dicULm[X-Y],(X+Y,"R"))
    if U == "D":
        hq.heappush(dicUD[X],(Y,"L"))
        hq.heappush(dicDLp[X+Y],(X-Y,"R"))
        hq.heappush(dicRDm[X-Y],(X+Y,"L"))
time = 10000000
for q in dicUD.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicRL.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicRUp.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicDLp.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicRDm.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
for q in dicULm.values():
    cur = -1000000
    dir = "L"
    while q:
        X,U = hq.heappop(q)
        if U == "R":
            dir = "R"
        elif U == "L":
            if dir == "R":
                time = min(time,(X-cur)*5)
            dir = "L"
        cur = X
if time == 10000000:
    print("SAFE")
else:
    print(time)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
M = 200000
UD = [[] for _ in range(2 * M + 10)]
RL = [[] for _ in range(2 * M + 10)]

RU = [[] for _ in range(2 * M + 10)]
RD = [[] for _ in range(2 * M + 10)]
LU = [[] for _ in range(2 * M + 10)]
LD = [[] for _ in range(2 * M + 10)]

for _ in range(N):
    x, y, di = input().split()
    x, y = int(x), int(y)
    if di == "R":
        RL[y].append(x * 2)
        RU[x+y].append(x * 2)
        RD[x-y+M].append(x * 2)
    elif di == "L":
        RL[y].append(x * 2 + 1)
        LU[x-y+M].append(x * 2 + 1)
        LD[x+y].append(x * 2 + 1)
    elif di == "U":
        UD[x].append(y * 2)
        RU[x+y].append(x * 2 + 1)
        LU[x-y+M].append(x * 2)
    elif di == "D":
        UD[x].append(y * 2 + 1)
        RD[x-y+M].append(x * 2 + 1)
        LD[x+y].append(x * 2)

def chk(XX):
    def subchk(X):
        t = - (1 << 100)
        re = 1 << 100
        for x in sorted(X):
            a = x >> 1
            b = x & 1
            if b == 0:
                t = a
            else:
                re = min(re, a - t)
        return re * 10
    
    RE = 1 << 100
    for xx in XX:
        RE = min(RE, subchk(xx))
    return RE

ans = 1 << 100
ans = min(ans, chk(UD) // 2)
ans = min(ans, chk(RL) // 2)
ans = min(ans, chk(RU))
ans = min(ans, chk(RD))
ans = min(ans, chk(LU))
ans = min(ans, chk(LD))

print("SAFE" if ans > 1 << 80 else ans)

Submission status: Accepted

Solution code:
# Fast IO (only use in integer input)

import os,io
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

N = int(input())
plane = []
for _ in range(N):
    xb,yb,ub = input().split()
    x = int(xb)
    y = int(yb)
    if ub == b'U':
        u = 'U'
    elif ub == b'R':
        u = 'R'
    elif ub == b'D':
        u = 'D'
    else:
        u = 'L'
    plane.append((x,y,u))

# UD, LR collision
XR = []
XL = []
YU = []
YD = []
for i in range(200001):
    XR.append([])
    XL.append([])
    YU.append([])
    YD.append([])
for elem in plane:
    if elem[2] == 'U':
        YU[elem[0]].append(elem[1])
    if elem[2] == 'D':
        YD[elem[0]].append(elem[1])
    if elem[2] == 'L':
        XL[elem[1]].append(elem[0])
    if elem[2] == 'R':
        XR[elem[1]].append(elem[0])

        
for i in range(200001):
    XR[i].sort()
    XL[i].sort()
    YU[i].sort()
    YD[i].sort()

minTime = 4000000
for i in range(200001):
    indexR = 0
    indexL = 0
    while indexR < len(XR[i]) and indexL < len(XL[i]):
        if XR[i][indexR] > XL[i][indexL]:
            indexL += 1
        else:
            if (XL[i][indexL] - XR[i][indexR]) * 5 < minTime:
                minTime = (XL[i][indexL] - XR[i][indexR]) * 5
            indexR += 1
    
    indexU = 0
    indexD = 0
    while indexU < len(YU[i]) and indexD < len(YD[i]):
        if YU[i][indexU] > YD[i][indexD]:
            indexD += 1
        else:
            if (YD[i][indexD] - YU[i][indexU]) * 5 < minTime:
                minTime = (YD[i][indexD] - YU[i][indexU]) * 5
            indexU += 1

# Other collisions

XYSumR = []
XYSumU = []
XYSumD = []
XYSumL = []
# Diff is X - Y + 200000
XYDiffR = []
XYDiffU = []
XYDiffD = []
XYDiffL = []

for i in range(400001):
    XYSumR.append([])
    XYSumU.append([])
    XYSumD.append([])
    XYSumL.append([])
    XYDiffR.append([])
    XYDiffU.append([])
    XYDiffD.append([])
    XYDiffL.append([])
for elem in plane:
    if elem[2] == 'U':
        XYSumU[elem[0] + elem[1]].append(elem[0])
        XYDiffU[elem[0] - elem[1] + 200000].append(elem[0])
    if elem[2] == 'D':
        XYSumD[elem[0] + elem[1]].append(elem[0])
        XYDiffD[elem[0] - elem[1] + 200000].append(elem[0])
    if elem[2] == 'L':
        XYSumL[elem[0] + elem[1]].append(elem[0])
        XYDiffL[elem[0] - elem[1] + 200000].append(elem[0])
    if elem[2] == 'R':
        XYSumR[elem[0] + elem[1]].append(elem[0])
        XYDiffR[elem[0] - elem[1] + 200000].append(elem[0])

for i in range(400001):
    XYSumU[i].sort()
    XYDiffU[i].sort()
    XYSumD[i].sort()
    XYDiffD[i].sort()
    XYSumL[i].sort()
    XYDiffL[i].sort()
    XYSumR[i].sort()
    XYDiffR[i].sort()

for i in range(400001):
    indexR = 0
    indexU = 0
    while indexR < len(XYSumR[i]) and indexU < len(XYSumU[i]):
        if XYSumU[i][indexU] > XYSumR[i][indexR]:
            if (XYSumU[i][indexU] - XYSumR[i][indexR]) * 10 < minTime:
                minTime = (XYSumU[i][indexU] - XYSumR[i][indexR]) * 10
            indexR += 1
        else:
            indexU += 1
    indexD = 0
    indexL = 0
    while indexL < len(XYSumL[i]) and indexD < len(XYSumD[i]):
        if XYSumD[i][indexD] > XYSumL[i][indexL]:
            indexL += 1
        else:
            if (XYSumL[i][indexL] - XYSumD[i][indexD]) * 10 < minTime:
                minTime = (XYSumL[i][indexL] - XYSumD[i][indexD]) * 10
            indexD += 1    
    indexL = 0
    indexU = 0
    while indexL < len(XYDiffL[i]) and indexU < len(XYDiffU[i]):
        if XYDiffU[i][indexU] > XYDiffL[i][indexL]:
            indexL += 1
        else:
            if (XYDiffL[i][indexL] - XYDiffU[i][indexU]) * 10 < minTime:
                minTime = (XYDiffL[i][indexL] - XYDiffU[i][indexU]) * 10
            indexU += 1
    indexR = 0
    indexD = 0
    while indexR < len(XYDiffR[i]) and indexD < len(XYDiffD[i]):
        if XYDiffR[i][indexR] > XYDiffD[i][indexD]:
            indexD += 1
        else:
            if (XYDiffD[i][indexD] - XYDiffR[i][indexR]) * 10 < minTime:
                minTime = (XYDiffD[i][indexD] - XYDiffR[i][indexR]) * 10
            indexR += 1

if minTime == 4000000:
    print("SAFE")
else:
    print(minTime)

Submission status: Accepted

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


def solve():
    N = int(readline())
    X = [0] * N
    Y = [0] * N
    U = [0] * N

    for i in range(N):
        x, y, u = readline().split()
        X[i] = int(x)
        Y[i] = int(y)
        U[i] = u
    
    ans = 10 ** 10

    _U,D,L,R = 'U','D','L','R'

    rs = [(X[i], Y[i]) for i in range(N) if U[i] == R]
    ls = [(X[i], Y[i]) for i in range(N) if U[i] == L]
    ans = min(ans, horizon(rs, ls))

    rs = [(Y[i], X[i]) for i in range(N) if U[i] == _U]
    ls = [(Y[i], X[i]) for i in range(N) if U[i] == D]
    ans = min(ans, horizon(rs, ls))


    # cross
    rs = [(X[i], Y[i]) for i in range(N) if U[i] == R]
    ds = [(X[i], Y[i]) for i in range(N) if U[i] == D]
    ans = min(ans, cross(rs, ds))

    rs = [(X[i], -Y[i]) for i in range(N) if U[i] == R]
    ds = [(X[i], -Y[i]) for i in range(N) if U[i] == _U]
    ans = min(ans, cross(rs, ds))

    rs = [(-X[i], Y[i]) for i in range(N) if U[i] == L]
    ds = [(-X[i], Y[i]) for i in range(N) if U[i] == D]
    ans = min(ans, cross(rs, ds))

    rs = [(-X[i], -Y[i]) for i in range(N) if U[i] == L]
    ds = [(-X[i], -Y[i]) for i in range(N) if U[i] == _U]
    ans = min(ans, cross(rs, ds))

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


def horizon(rights, lefts):
    Y = {}
    for rx, ry in rights:
        if ry not in Y:
            Y[ry] = []
        Y[ry].append(rx)
    for k in Y:
        Y[k].sort()

    res = 10 ** 10
    
    for lx, ly in lefts:
        if ly not in Y:
            continue
        xs = Y[ly]
        t = bisect_right(xs, lx)
        if t == -1:
            continue
        else:
            res = min(res, (lx - xs[t]) * 5)
    
    return res

def bisect_right(xs, x):
    l, r = -1, len(xs)
    while l + 1 < r:
        m = (l + r) // 2
        if xs[m] < x:
            l = m
        else:
            r = m
    return l

def cross(rights, downs):
    x_seps = {}
    
    for x, y in rights:
        xsep = x - y
        if xsep not in x_seps:
            x_seps[xsep] = []
        
        x_seps[xsep].append(x)
    
    for k in x_seps:
        x_seps[k].sort()
    
    res = 10 ** 10

    for x, y in downs:
        xsep = x - y
        if xsep not in x_seps:
            continue
        xs = x_seps[xsep]
        t = bisect_right(xs, x)
        if t != -1:
            res = min(res, (x - xs[t]) * 10)

    return res

solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys

N, *XYU = map(str, sys.stdin.read().split())

UD = {}
UR = {}
UL = {}
DU = {}
DR = {}
DL = {}
RU = {}
RD = {}
RL = {}
LU = {}
LD = {}
LR = {}

for i in range(int(N)):
  X = int(XYU[3*i])
  Y = int(XYU[3*i+1])
  U = XYU[3*i+2]
  if U == 'U':
    if X in UD.keys():
      UD[X].append(Y)
    else:
      UD[X] = [Y]
    if X+Y in UR.keys():
      UR[X+Y].append(X)
    else:
      UR[X+Y] = [X]
    if X-Y in UL.keys():
      UL[X-Y].append(X)
    else:
      UL[X-Y] = [X]
  elif U == 'D':
    if X in DU.keys():
      DU[X].append(Y)
    else:
      DU[X] = [Y]
    if X+Y in DL.keys():
      DL[X+Y].append(X)
    else:
      DL[X+Y] = [X]
    if X-Y in DR.keys():
      DR[X-Y].append(X)
    else:
      DR[X-Y] = [X]
  elif U == 'R':
    if Y in RL.keys():
      RL[Y].append(X)
    else:
      RL[Y] = [X]
    if X+Y in RU.keys():
      RU[X+Y].append(X)
    else:
      RU[X+Y] = [X]
    if X-Y in RD.keys():
      RD[X-Y].append(X)
    else:
      RD[X-Y] = [X]
  else:
    if Y in LR.keys():
      LR[Y].append(X)
    else:
      LR[Y] = [X]
    if X+Y in LD.keys():
      LD[X+Y].append(X)
    else:
      LD[X+Y] = [X]
    if X-Y in LU.keys():
      LU[X-Y].append(X)
    else:
      LU[X-Y] = [X]

def dist(X,Y):
  minimum = -1
  X_len = len(X)
  X_index = 0
  Y_len = len(Y)
  Y_index = 0
  while X_index<X_len and Y_index<Y_len:
    x = X[X_index]
    y = Y[Y_index]
    if x<y:
      if minimum == -1:
        minimum = y-x
      else:
        minimum = min(minimum, y-x)
      X_index += 1
    else:
      Y_index += 1
  return minimum

second = -1

for x in UD.keys():
  if x in DU.keys():
    distance = dist(sorted(UD[x]),sorted(DU[x]))
    if distance>0:
      if second == -1:
        second = 5*distance
      else:
        second = min(second,5*distance)

for x in RL.keys():
  if x in LR.keys():
    distance = dist(sorted(RL[x]),sorted(LR[x]))
    if distance>0:
      if second == -1:
        second = 5*distance
      else:
        second = min(second,5*distance)

for x in UR.keys():
  if x in RU.keys():
    distance = dist(sorted(RU[x]),sorted(UR[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

for x in UL.keys():
  if x in LU.keys():
    distance = dist(sorted(UL[x]),sorted(LU[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

for x in RD.keys():
  if x in DR.keys():
    distance = dist(sorted(RD[x]),sorted(DR[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

for x in LD.keys():
  if x in DL.keys():
    distance = dist(sorted(DL[x]),sorted(LD[x]))
    if distance>0:
      if second == -1:
        second = 10*distance
      else:
        second = min(second,10*distance)

if second == -1:
  print('SAFE')
else:
  print(second)

Submission status: Accepted

Solution code:
import sys
import heapq, functools, collections
import math, random
from collections import Counter, defaultdict

# available on Google, not available on Codeforces
# import numpy as np
# import scipy


def solve(grid):  # fix inputs here
    console("----- solving ------")
    # grid = [[int(a), int(b), c] for a,b,c in grid]

    n_planes = []
    s_planes = []
    w_planes = []
    e_planes = []

    for a,b,c in grid:
        a, b = int(a), int(b)
        if c == "U":
            n_planes.append((a,b))
        if c == "D":
            s_planes.append((a,b))
        if c == "L":
            w_planes.append((a,b))
        if c == "R":
            e_planes.append((a,b))
        
    console(n_planes)
    console(s_planes)
    console(w_planes)
    console(e_planes)

    # ns collision
    ns = collections.defaultdict(list)
    for a,b in n_planes:
        ns[a].append((b/2,1))
    for a,b in s_planes:
        ns[a].append((b/2,-1))
    
    ns = [(k,sorted(v)) for k,v in ns.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("ns", ns)

    # ew collision
    ew = collections.defaultdict(list)
    for a,b in w_planes:
        ew[b].append((a/2,-1))
    for a,b in e_planes:
        ew[b].append((a/2,1))

    ew = [(k,sorted(v)) for k,v in ew.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("ew", ew)

    # ne collision
    ne = collections.defaultdict(list)
    for a,b in n_planes:
        val = a+b
        ne[val].append((a,-1))
    for a,b in e_planes:
        val = a+b
        ne[val].append((a,1))

    ne = [(k,sorted(v)) for k,v in ne.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("ne", ne)

    # sw collision
    sw = collections.defaultdict(list)
    for a,b in s_planes:
        val = -a-b
        sw[val].append((a,1))
    for a,b in w_planes:
        val = -a-b
        sw[val].append((a,-1))

    sw = [(k,sorted(v)) for k,v in sw.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("sw", sw)

    # nw collision
    nw = collections.defaultdict(list)
    for a,b in n_planes:
        val = a-b
        nw[val].append((a,1))
    for a,b in w_planes:
        val = a-b
        nw[val].append((a,-1))

    nw = [(k,sorted(v)) for k,v in nw.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("nw", nw)

    # se collision
    se = collections.defaultdict(list)
    for a,b in s_planes:
        val = -a+b
        se[val].append((a,-1))
    for a,b in e_planes:
        val = -a+b
        se[val].append((a,1))

    se = [(k,sorted(v)) for k,v in se.items() if len(v) > 1 and len(set(x[1] for x in v)) == 2]
    console("se", se)

    minres = math.inf

    for c in [ns, ew, ne, sw, nw, se]:
        for _,v in c:
            # console(c)
            # console(v)
            for a,b in zip(v, v[1:]):
                # console(a)
                # console(b)
                if a[1] > b[1]:
                    # pass
                    minres = min(minres, b[0] - a[0])
    
    if minres == math.inf:
        return "SAFE"
    return int(minres*10)


def console(*args):  # the judge will not read these print statement
    # print('\033[36m', *args, '\033[0m', file=sys.stderr)
    return

# fast read all
# sys.stdin.readlines()

for case_num in [1]:
    # read line as a string
    # strr = input()

    # read line as an integer
    nrows = int(input())
    
    # read one line and parse each word as a string
    # lst = input().split()

    # read one line and parse each word as an integer
    # lst = list(map(int,input().split()))

    # read matrix and parse as integers (after reading read nrows)
    # lst = list(map(int,input().split()))
    # nrows = lst[0]  # index containing information, please change
    grid = []
    for _ in range(nrows):
        grid.append(input().split())

    res = solve(grid)  # please change
    
    # Google - case number required
    # print("Case #{}: {}".format(case_num+1, res))

    # Codeforces - no case number required
    print(res)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
    n = ni()
    s = 'UDLR'
    g = [list() for _ in range(4)]
    for _ in range(n):
        x, y, u = input().split()
        g[s.index(u)].append((int(x), int(y)))


    def calc(a, b):
        a.sort()
        b.sort()
        idx = 0
        m = len(b)
        res = 10 ** 9
        for x, y in a:
            while idx < m and (b[idx][0] < x or b[idx][0] == x and b[idx][1] < y):
                idx += 1
            if idx >= m:
                break
            if b[idx][0] == x and b[idx][1] >= y:
                res = min(res, b[idx][1] - y)
        return res * 5

    res1 = calc(g[0], g[1])
    res2 = calc([(y, x) for x, y in g[3]], [(y, x) for x, y in g[2]])
    res3 = calc([(x+y, x-y) for x, y in g[3]], [(x+y, x-y) for x, y in g[0]])
    res4 = calc([(x+y, x-y) for x, y in g[1]], [(x+y, x-y) for x, y in g[2]])
    res5 = calc([(x-y, x+y) for x, y in g[0]], [(x-y, x+y) for x, y in g[2]])
    res6 = calc([(x-y, x+y) for x, y in g[3]], [(x-y, x+y) for x, y in g[1]])
    ans = min(res1, res2, res3, res4, res5, res6)
    if ans > 10**9:
        print('SAFE')
    else:
        print(ans)
    return

solve()

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
def smin(x,y):
    if x>y:
        return y
    else:
        return x

sys.setrecursionlimit(500000)
def input():
    return sys.stdin.readline()[:-1]

def main():
    N = int(input())

    dd = defaultdict(list)
    ans = 10**27

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

    dd_u = defaultdict(list)

    for x,y in dd["U"]:
        dd_u[x].append((y,"U"))

    for x,y in dd["D"]:
        if x in dd_u:
            dd_u[x].append((y,"D"))

    for x in dd_u:
        dd_u[x].sort()
        for i in range(len(dd_u[x])-1):
            if dd_u[x][i][1]=="U" and dd_u[x][i+1][1]=="D":
                ans = smin((dd_u[x][i+1][0]-dd_u[x][i][0])/2,ans)

    dd_l = defaultdict(list)

    for x,y in dd["L"]:
        dd_l[y].append((x,"L"))

    for x,y in dd["R"]:
        if y in dd_l:
            dd_l[y].append((x,"R"))

    for y in dd_l:
        dd_l[y].sort()
        for i in range(len(dd_l[y])-1):
            if dd_l[y][i][1]=="R" and dd_l[y][i+1][1]=="L":
                ans = smin((dd_l[y][i+1][0]-dd_l[y][i][0])/2,ans)

    dd_v = defaultdict(list)

    for x,y in dd["U"]:
        v = y-x
        dd_v[v].append((x+y,"U"))

    for x,y in dd["L"]:
        v = y-x
        if v in dd_v:
            dd_v[v].append((x+y,"L"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="U" and dd_v[v][i+1][1]=="L":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)

    dd_v = defaultdict(list)

    for x,y in dd["U"]:
        v = y+x
        dd_v[v].append((x-y,"U"))

    for x,y in dd["R"]:
        v = y+x
        if v in dd_v:
            dd_v[v].append((x-y,"R"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="R" and dd_v[v][i+1][1]=="U":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)


    dd_v = defaultdict(list)

    for x,y in dd["D"]:
        v = y-x
        dd_v[v].append((x+y,"D"))

    for x,y in dd["R"]:
        v = y-x
        if v in dd_v:
            dd_v[v].append((x+y,"R"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="R" and dd_v[v][i+1][1]=="D":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)

    dd_v = defaultdict(list)

    for x,y in dd["D"]:
        v = y+x
        dd_v[v].append((x-y,"D"))

    for x,y in dd["L"]:
        v = y+x
        if v in dd_v:
            dd_v[v].append((x-y,"L"))

    for v in dd_v:
        dd_v[v].sort()
        for i in range(len(dd_v[v])-1):
            if dd_v[v][i][1]=="D" and dd_v[v][i+1][1]=="L":
                ans = smin((dd_v[v][i+1][0]-dd_v[v][i][0])/2,ans)

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


if __name__ == '__main__':
    main()