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 deque, Counter, defaultdict
from itertools import chain, combinations
import json
# import numpy as np
import bisect
import sys
import math
import bisect
from functools import lru_cache
import itertools

sys.setrecursionlimit(10 ** 8)

M = 10 ** 9 + 7
INF = 10 ** 17


def main():
    N = int(input())
    XYU = [
        [a for a in input().split()]
        for _ in range(N)
    ]

    # N, K = [int(a) for a in input().split()]
    # A = [int(a) for a in input().split()]
    # T1, T2, T3 = [int(a) for a in input().split()]

    up = []
    down = []
    right = []
    left = []
    for xi, yi, ui in XYU:
        if ui == 'U':
            up.append((int(xi), int(yi)))
            continue
        if ui == 'D':
            down.append((int(xi), int(yi)))
            continue
        if ui == 'R':
            right.append((int(xi), int(yi)))
            continue
        if ui == 'L':
            left.append((int(xi), int(yi)))
            continue

    def a():
        conflict = 10 ** 50
        xtable = {}
        for xi, yi in down:
            if xi not in xtable:
                xtable[xi] = []
            ind = bisect.bisect_left(xtable[xi], yi)
            xtable[xi].insert(ind, yi)
        for xi, yi in up:
            if xi in xtable:
                ind = bisect.bisect_left(xtable[xi], yi)
                if ind != len(xtable[xi]):
                    conflict = min(conflict, (xtable[xi][ind] - yi) * 5)
        ytable = {}
        for xi, yi in left:
            if yi not in ytable:
                ytable[yi] = []
            ind = bisect.bisect_left(ytable[yi], xi)
            ytable[yi].insert(ind, xi)
        for xi, yi in right:
            if yi in ytable:
                ind = bisect.bisect_left(ytable[yi], xi)
                if ind != len(ytable[yi]):
                    conflict = min(conflict, (ytable[yi][ind] - xi) * 5)
        return conflict

    left_l1 = {}
    left_l2 = {}
    for xi, yi in left:
        v1 = yi - xi
        if v1 not in left_l1:
            left_l1[v1] = []
        ind = bisect.bisect_left(left_l1[v1], xi)
        left_l1[v1].insert(ind, xi)

        v2 = xi + yi
        if v2 not in left_l2:
            left_l2[v2] = []
        ind = bisect.bisect_left(left_l2[v2], xi)
        left_l2[v2].insert(ind, xi)

    right_l1 = {}
    right_l2 = {}
    for xi, yi in right:
        v1 = yi - xi
        if v1 not in right_l1:
            right_l1[v1] = []
        ind = bisect.bisect_left(right_l1[v1], xi)
        right_l1[v1].insert(ind, xi)

        v2 = xi + yi
        if v2 not in right_l2:
            right_l2[v2] = []
        ind = bisect.bisect_left(right_l2[v2], xi)
        right_l2[v2].insert(ind, xi)

    conflict = a()

    for xi, yi in up:
        v1 = yi - xi
        v2 = xi + yi
        if v1 in left_l1:
            l = left_l1[v1]
            ind = bisect.bisect_left(l, xi)
            if ind != len(l):
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
        if v2 in right_l2:
            l = right_l2[v2]
            ind = bisect.bisect_right(l, xi)
            if ind != 0:
                xx = l[ind - 1]
                conflict = min(conflict, abs(xx - xi) * 10)
    for xi, yi in down:
        v1 = yi - xi
        v2 = xi + yi
        if v1 in right_l1:
            l = right_l1[v1]
            ind = bisect.bisect_right(l, xi)
            if ind != 0:
                xx = l[ind - 1]
                conflict = min(conflict, abs(xx - xi) * 10)
        if v2 in left_l2:
            l = left_l2[v2]
            ind = bisect.bisect_left(l, xi)
            if ind != len(l):
                xx = l[ind]
                conflict = min(conflict, abs(xx - xi) * 10)
    if conflict == 10 ** 50:
        print('SAFE')
        return
    print(conflict)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict as dd
from bisect import bisect_left, bisect

def stc(L, R, mp):
    m = 10**20
    for y, ll in L.items():
        if y not in R:
            continue
        ll.sort()
        for r in R[y]:
            i = bisect(ll, r)
            if i == len(ll):
                continue
            m = min(m, ll[i] - r)
    return m * mp


def main():
    N = int(input())
    UL, UR, DL, DR = dd(list), dd(list), dd(list), dd(list)
    ULa, URa, DLa, DRa = dd(list), dd(list), dd(list), dd(list)
    D, U, L, R = dd(list), dd(list), dd(list), dd(list)
    for _ in range(N):
        _x, _y, u = input().split()
        x, y = int(_x), int(_y)
        if u == 'U':
            UL[x - y].append(x)
            UR[x + y].append(x)
            U[x].append(y)
        elif u == 'D':
            DL[x + y].append(x)
            DR[x - y].append(x)
            D[x].append(y)
        elif u == 'L':
            ULa[x - y].append(x)
            DLa[x + y].append(x)
            L[y].append(x)
        else:
            URa[x + y].append(x)
            DRa[x - y].append(x)
            R[y].append(x)
    m = 10 ** 20
    m = min(m, stc(L, R, 5))
    m = min(m, stc(D, U, 5))
    m = min(m, stc(ULa, UL, 10))
    m = min(m, stc(UR, URa, 10))
    m = min(m, stc(DLa, DL, 10))
    m = min(m, stc(DR, DRa, 10))
    print('SAFE' if m >= 10 ** 20 else m)

main()

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    from collections import defaultdict
    input = sys.stdin.readline

    N = int(input())
    Uxy = [[] for _ in range(10**6)]
    Rxy = [[] for _ in range(10**6)]
    Dxy = [[] for _ in range(10**6)]
    Lxy = [[] for _ in range(10**6)]
    Ux_y = [[] for _ in range(10 ** 6)]
    Rx_y = [[] for _ in range(10 ** 6)]
    Dx_y = [[] for _ in range(10 ** 6)]
    Lx_y = [[] for _ in range(10 ** 6)]
    Ux = [[] for _ in range(10 ** 6)]
    Ry = [[] for _ in range(10 ** 6)]
    Dx = [[] for _ in range(10 ** 6)]
    Ly = [[] for _ in range(10 ** 6)]
    Xall = set()
    Yall = set()
    XYall = set()
    X_Yall = set()
    for _ in range(N):
        x, y, d = input().split()
        x = int(x)
        y = int(y)
        Xall.add(x)
        Yall.add(y)
        XYall.add(x+y)
        X_Yall.add(x-y)
        if d == "U":
            Uxy[x+y].append((x, y))
            Ux_y[x-y].append((x, y))
            Ux[x].append(y)
        elif d == "R":
            Rxy[x + y].append((x, y))
            Rx_y[x - y].append((x, y))
            Ry[y].append(x)
        elif d == "D":
            Dxy[x + y].append((x, y))
            Dx_y[x - y].append((x, y))
            Dx[x].append(y)
        else:
            Lxy[x + y].append((x, y))
            Lx_y[x - y].append((x, y))
            Ly[y].append(x)

    ans = 10**9
    # RL
    for y in Yall:
        if len(Ry[y]) > 0 and len(Ly[y]) > 0:
            A = []
            for x in Ry[y]:
                A.append((x, 1))
            for x in Ly[y]:
                A.append((x, -1))
            A.sort(key=lambda p: p[0])
            for i in range(len(A) - 1):
                if A[i][1] == 1 and A[i+1][1] == -1:
                    ans = min(ans, (A[i+1][0] - A[i][0]) * 5)

    # UD
    for x in Xall:
        if len(Ux[x]) > 0 and len(Dx[x]) > 0:
            A = []
            for y in Ux[x]:
                A.append((y, 1))
            for y in Dx[x]:
                A.append((y, -1))
            A.sort(key=lambda p: p[0])
            for i in range(len(A) - 1):
                if A[i][1] == 1 and A[i+1][1] == -1:
                    ans = min(ans, (A[i+1][0] - A[i][0]) * 5)

    # RU
    for xy in XYall:
        A = []
        for x, y in Uxy[xy]:
            A.append((x, y, "U"))
        for x, y in Rxy[xy]:
            A.append((x, y, "R"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "R" and A[i+1][2] == "U":
                ans = min(ans, (A[i+1][0] - A[i][0]) * 10)

    # DL
    for xy in XYall:
        A = []
        for x, y in Dxy[xy]:
            A.append((x, y, "D"))
        for x, y in Lxy[xy]:
            A.append((x, y, "L"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "D" and A[i + 1][2] == "L":
                ans = min(ans, (A[i + 1][0] - A[i][0]) * 10)

    # UL
    for x_y in X_Yall:
        A = []
        for x, y in Ux_y[x_y]:
            A.append((x, y, "U"))
        for x, y in Lx_y[x_y]:
            A.append((x, y, "L"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "U" and A[i + 1][2] == "L":
                ans = min(ans, (A[i + 1][0] - A[i][0]) * 10)

    # DR
    for x_y in X_Yall:
        A = []
        for x, y in Dx_y[x_y]:
            A.append((x, y, "D"))
        for x, y in Rx_y[x_y]:
            A.append((x, y, "R"))
        A.sort(key=lambda p: p[0])
        for i in range(len(A) - 1):
            if A[i][2] == "R" and A[i + 1][2] == "D":
                ans = min(ans, (A[i + 1][0] - A[i][0]) * 10)

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right
import sys
input = sys.stdin.readline

def main():
    n = int(input())
    yx_p_u = {}
    yx_p_r = {}
    yx_p_d = {}
    yx_p_l = {}

    yx_m_u = {}
    yx_m_r = {}
    yx_m_d = {}
    yx_m_l = {}

    y_d = {}
    y_u = {}
    x_r = {}
    x_l = {}

    for i in range(-200000,200000+1):
        yx_p_u[i] = []
        yx_p_r[i] = []
        yx_p_d[i] = []
        yx_p_l[i] = []

    for i in range(0,400000+1):
        yx_m_u[i] = []
        yx_m_r[i] = []
        yx_m_d[i] = []
        yx_m_l[i] = []

        if i <= 200000:
            y_d[i] = []
            y_u[i] = []
            x_r[i] = []
            x_l[i] = []


    for _ in range(n):
        x,y,u = map(str, input().split())
        x = int(x)
        y = int(y)
        yxp = y-x
        yxm = y+x
        if u == 'U':
            yx_p_u[yxp].append(x)
            yx_m_u[yxm].append(x)
            y_u[x].append(y)
        if u == 'R':
            yx_p_r[yxp].append(x)
            yx_m_r[yxm].append(x)
            x_r[y].append(x)
        if u == 'D':
            yx_p_d[yxp].append(x)
            yx_m_d[yxm].append(x)
            y_d[x].append(y)
        if u == 'L':
            yx_p_l[yxp].append(x)
            yx_m_l[yxm].append(x)
            x_l[y].append(x)


    # for i in range(-20,20+1):
    for i in range(-200000,200000+1):
        yx_p_u[i].sort()
        yx_p_r[i].sort()
        yx_p_d[i].sort()
        yx_p_l[i].sort()
        # if len(yx_p_u[i]) > 0: print(i,yx_p_u[i])
        # if len(yx_p_r[i])> 0: print(i,yx_p_r[i])
        # if len(yx_p_d[i])> 0: print(i,yx_p_d[i])
        # if len(yx_p_l[i])> 0: print(i,yx_p_l[i])


    for i in range(0,400000+1):
        yx_m_u[i].sort()
        yx_m_r[i].sort()
        yx_m_d[i].sort()
        yx_m_l[i].sort()
        if i <= 200000:
            y_d[i].sort()
            y_u[i].sort()
            x_r[i].sort()
            x_l[i].sort()
        # if yx_m_u[i]: print(i,yx_m_u)
        # if yx_m_r[i]: print(i,yx_m_u)
        # if yx_m_d[i]: print(i,yx_m_u)
        # if yx_m_l[i]: print(i,yx_m_u)


    ans = 10**9
    for i in range(-200000,200000+1):
        for v in yx_p_u[i]:
            ind = bisect_right(yx_p_l[i], v)
            ind = ind if 0 <= ind < len(yx_p_l[i]) else None
            val = yx_p_l[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)

        for v in yx_p_d[i]:
            ind = bisect_left(yx_p_r[i], v) - 1
            ind = ind if 0 <= ind < len(yx_p_r[i]) else None
            val = yx_p_r[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)


    for i in range(0,400000+1):
        for v in yx_m_d[i]:
            ind = bisect_right(yx_m_l[i], v)
            ind = ind if 0 <= ind < len(yx_m_l[i]) else None
            val = yx_m_l[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)

        for v in yx_m_u[i]:
            ind = bisect_left(yx_m_r[i], v) - 1
            ind = ind if 0 <= ind < len(yx_m_r[i]) else None
            val = yx_m_r[i][ind] if ind is not None else None
            if val is not None:
                ans = min(ans, abs(val-v)*10)

        if i <= 200000:
            for v in y_u[i]:
                ind = bisect_right(y_d[i], v)
                ind = ind if 0 <= ind < len(y_d[i]) else None
                val = y_d[i][ind] if ind is not None else None
                if val is not None:
                    ans = min(ans, abs(val-v)*10//2)

            for v in x_r[i]:
                ind = bisect_right(x_l[i], v)
                ind = ind if 0 <= ind < len(x_l[i]) else None
                val = x_l[i][ind] if ind is not None else None
                if val is not None:
                    ans = min(ans, abs(val-v)*10//2)


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


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
x = [[] for _ in range(200001)]
y = [[] for _ in range(200001)]
z = [[] for _ in range(800002)]
w = [[] for _ in range(800002)]
t = float("inf")
for _ in range(n):
  xi,yi,ui = map(str,input().split())
  xi = int(xi)
  yi = int(yi)
  if ui == "U":
    x[xi].append((yi,1))
    z[xi+yi].append((xi,-1))
    w[xi-yi+200001].append((xi,1))
  elif ui == "D":
    x[xi].append((yi,-1))
    z[xi+yi+400001].append((xi,1))
    w[xi-yi+600001].append((xi,-1))                       
  elif ui == "R":
    y[yi].append((xi,1))
    z[xi+yi].append((xi,1))
    w[xi-yi+600001].append((xi,1))  
  else:
    y[yi].append((xi,-1))
    z[xi+yi+400001].append((xi,-1))
    w[xi-yi+200001].append((xi,-1)) 
for xx in x:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*5 < t:
            t = (xx[i][0] - n)*5
          n = -1 
for xx in y:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*5 < t:
            t = (xx[i][0] - n)*5
          n = -1 
for xx in z:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*10 < t:
            t = (xx[i][0] - n)*10
          n = -1 
for xx in w:
  if len(xx) >= 2:
    xx.sort(key=lambda a:a[0])
    n = -1
    for i in range(len(xx)):
      if xx[i][1] == 1:
        n = xx[i][0]
      else:
        if n != -1:
          if (xx[i][0] - n)*10 < t:
            t = (xx[i][0] - n)*10
          n = -1 
if t == float("inf"):
  print("SAFE")
else:
  print(t)

Submission status: Accepted

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

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

ans=10**20
ud=[[]for _ in range(200001)]
lr=[[]for _ in range(200001)]
for x,y,u in xyu:
  if u in "UD":
    ud[x].append((y,u))
  else:
    lr[y].append((x,u))
for i in range(200001):
  ud[i].sort()
  for j in range(1,len(ud[i])):
    if ud[i][j-1][1]+ud[i][j][1]=="UD":
      ans=min(ans,(ud[i][j][0]-ud[i][j-1][0])*5)
  lr[i].sort()
  for j in range(1,len(lr[i])):
    if lr[i][j-1][1]+lr[i][j][1]=="RL":
      ans=min(ans,(lr[i][j][0]-lr[i][j-1][0])*5)

rup_rd=[[]for _ in range(400001)]
rup_lu=[[]for _ in range(400001)]
lup_ld=[[]for _ in range(400001)]
lup_ru=[[]for _ in range(400001)]
for x,y,u in xyu:
  if u=="U":
    rup_lu[x-y+200000].append((x,y,u))
    lup_ru[x+y].append((x,y,u))
  if u=="D":
    rup_rd[x-y+200000].append((x,y,u))
    lup_ld[x+y].append((x,y,u))
  if u=="L":
    rup_lu[x-y+200000].append((x,y,u))
    lup_ld[x+y].append((x,y,u))
  if u=="R":
    rup_rd[x-y+200000].append((x,y,u))
    lup_ru[x+y].append((x,y,u))
for i in range(400001):
  rup_rd[i].sort()
  rup_lu[i].sort()
  lup_ld[i].sort()
  lup_ru[i].sort()
  for j in range(1,len(rup_rd[i])):
    sx,sy,su=rup_rd[i][j-1]
    tx,ty,tu=rup_rd[i][j]
    if su+tu=="RD":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
  for j in range(1,len(rup_lu[i])):
    sx,sy,su=rup_lu[i][j-1]
    tx,ty,tu=rup_lu[i][j]
    if su+tu=="UL":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
  for j in range(1,len(lup_ld[i])):
    sx,sy,su=lup_ld[i][j-1]
    tx,ty,tu=lup_ld[i][j]
    if su+tu=="DL":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
  for j in range(1,len(lup_ru[i])):
    sx,sy,su=lup_ru[i][j-1]
    tx,ty,tu=lup_ru[i][j]
    if su+tu=="RU":ans=min(ans,(abs(sx-tx)+abs(sy-ty))*5)
if ans==10**20:
  print("SAFE")
else:
  print(ans)

Submission status: Accepted

Solution code:
N = int(input())

A1 = []
A2=[]
A3=[]
B1 = []
B4 = []
B5 = []
C2 = []
C4 = []
C6 = []
D3 = []
D5 = []
D6 = []
for i in range(N):
  X, Y, U = input().split()
  X = int(X)
  Y = int(Y)
  U = str(U)
  if U == "R":
    A1.append((Y, X))
    A2.append((X-Y,X))
    A3.append((X+Y,X))
  elif U == "L":
    B1.append((Y,X))
    B4.append((X+Y,-X))
    B5.append((X-Y,-X))
  elif U == "D":
    C2.append((X-Y,X))
    C4.append((X+Y,-X))
    C6.append((X,Y))
  elif U == "U":
    D3.append((X+Y,X))
    D5.append((X-Y,-X))
    D6.append((X,Y))
    

ans = 10 ** 20
A1.sort()
B1.sort()
i = 0
for x1, y1 in A1:
  while i < len(B1):
    x2, y2 = B1[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*5)
      break
    else:
      i += 1
    
A2.sort()
C2.sort()
i = 0
for x1, y1 in A2:
  while i < len(C2):
    x2, y2 = C2[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
A3.sort()
D3.sort()
i = 0
for x1, y1 in A3:
  while i < len(D3):
    x2, y2 = D3[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
C4.sort()
B4.sort()
i = 0
for x1, y1 in B4:
  while i < len(C4):
    x2, y2 = C4[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
D5.sort()
B5.sort()
i = 0
for x1, y1 in B5:
  while i < len(D5):
    x2, y2 = D5[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*10)
      break
    else:
      i += 1
    
C6.sort()
D6.sort()
i = 0
for x1, y1 in D6:
  while i < len(C6):
    x2, y2 = C6[i]
    if (x1, y1) < (x2, y2):
      if x1 == x2:
        ans = min(ans, (y2-y1)*5)
      break
    else:
      i += 1
#print(B4, C4)    
print(ans if ans < 10**20 else "SAFE")

Submission status: Accepted

Solution code:

max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

from collections import defaultdict

def solve(U,R,D,L):

    def helper(U,R):
        A = defaultdict(list)
        B = defaultdict(list)
        for x,y in U:
            A[x+y].append(x)
        for x,y in R:
            B[x+y].append(x)
        m = 1000000
        for d,r in A.items():
            l = B[d]
            j = 0
            for li in l:
                while j < len(r) and li > r[j]:
                    j += 1
                if j == len(r):
                    break
                m = min2(m, r[j]-li)
        return m

    def helper2(U,D):
        A = defaultdict(list)
        B = defaultdict(list)
        for x,y in U:
            A[x].append(y)
        for x,y in D:
            B[x].append(y)
        m = 100000000
        for d,l in A.items():
            l.sort()
            r = B[d]
            r.sort()
            j = 0
            for li in l:
                while j < len(r) and li > r[j]:
                    j += 1
                if j == len(r):
                    break
                m = min2(m, r[j]-li)
        return m



    U.sort()
    R.sort()
    D.sort()
    L.sort()
    m = helper(U,R)
    A,B = [(-x,y) for x,y in U], [(-x,y) for x,y in L]
    A.reverse()
    B.reverse()
    m = min2(helper(A,B), m)
    A,B = [(x,-y) for x,y in D], [(x,-y) for x,y in R]
    m = min2(helper(A,B), m)
    A,B = [(-x,-y) for x,y in D], [(-x,-y) for x,y in L]
    A.reverse()
    B.reverse()
    m = min2(helper(A,B), m)
    m *= 10
    m = min2(helper2(U,D)*5, m)
    A,B = [(y,x) for x,y in L], [(y,x) for x,y in R]
    m = min2(helper2(B,A)*5, m)

    return m if m < 10000000 else 'SAFE'



if __name__ == '__main__':
    N = int(readline())

    t = iter(read().split())

    U,R,D,L = [],[],[],[]
    for x,y,u in zip(t,t,t):
        p = (int(x),int(y))
        u = u.decode('utf8')
        if u == 'U':
            U.append(p)
        elif u == 'R':
            R.append(p)
        elif u == 'D':
            D.append(p)
        else:
            L.append(p)

    print(solve(U,R,D,L))

Submission status: Accepted

Solution code:
n=int(input())
xyu=[list(input().split()) for _ in range(n)]
xyu=[[int(x),int(y),u] for x,y,u in xyu]
ddr={'U':0,'R':1,'D':2,'L':3}
plus={'U':{},'R':{},'D':{},'L':{}}
minus={'U':{},'R':{},'D':{},'L':{}}
drdi={'U':{},'R':{},'D':{},'L':{}}

for i in range(n):
  x,y,u=xyu[i]
  if u=='U':
    if x in drdi[u]:
      drdi[u][x].add(i)
    else:
      drdi[u][x]={i}
  if u=='D':
    if x in drdi[u]:
      drdi[u][x].add(i)
    else:
      drdi[u][x]={i}
  if u=='R':
    if y in drdi[u]:
      drdi[u][y].add(i)
    else:
      drdi[u][y]={i}
  if u=='L':
    if y in drdi[u]:
      drdi[u][y].add(i)
    else:
      drdi[u][y]={i}
  if y-x in plus[u]:
    plus[u][y-x].add(i)
  else:
    plus[u][y-x]={i}
  if y+x in minus[u]:
    minus[u][y+x].add(i)
  else:
    minus[u][y+x]={i}
inf=float('inf')
ans=inf
ukeys=set(drdi['U'].keys())
dkeys=set(drdi['D'].keys())
from bisect import bisect_left
for x in ukeys.intersection(dkeys):
  U=[xyu[i][1] for i in drdi['U'][x]]
  D=[xyu[i][1] for i in drdi['D'][x]]
  if min(U)>=max(D):continue
  D=sorted(D)
  for ui in U:
    tmp=bisect_left(D,ui)
    if tmp==len(D):continue
    ans=min(ans,10*(D[tmp]-ui)//2)

rkeys=set(drdi['R'].keys())
lkeys=set(drdi['L'].keys())
for x in rkeys.intersection(lkeys):
  R=[xyu[i][0] for i in drdi['R'][x]]
  L=[xyu[i][0] for i in drdi['L'][x]]
  if min(R)>=max(L):continue
  L=sorted(L)
  for ri in R:
    tmp=bisect_left(L,ri)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ri)//2)

ukeys=set(plus['U'].keys())
lkeys=set(plus['L'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][1] for i in plus['U'][x]]
  L=[xyu[i][1] for i in plus['L'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))

ukeys=set(plus['R'].keys())
lkeys=set(plus['D'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][0] for i in plus['R'][x]]
  L=[xyu[i][0] for i in plus['D'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))

ukeys=set(minus['U'].keys())
lkeys=set(minus['R'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][1] for i in minus['U'][x]]
  L=[xyu[i][1] for i in minus['R'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))

ukeys=set(minus['D'].keys())
lkeys=set(minus['L'].keys())
for x in ukeys.intersection(lkeys):
  U=[xyu[i][0] for i in minus['D'][x]]
  L=[xyu[i][0] for i in minus['L'][x]]
  if min(U)>=max(L):continue
  L=sorted(L)
  for ui in U:
    tmp=bisect_left(L,ui)
    if tmp==len(L):continue
    ans=min(ans,10*(L[tmp]-ui))
if ans==inf:
  print('SAFE')
else:
  print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
from bisect import bisect_right
N = int(input())
XYU = [None]*N
for i in range(N):
    x, y, u = input().split()
    XYU[i] = (int(x), int(y), u)
U, D = defaultdict(list), defaultdict(list)
R, L = defaultdict(list), defaultdict(list) 
Ru, Rd, Lu, Ld = defaultdict(list), defaultdict(list), defaultdict(list), defaultdict(list)
for x, y, u in XYU:
    if u == 'R':
        Ru[x+y].append(x)
        Rd[y-x].append(x)
        R[y].append(x)
    elif u == 'L':
        Lu[y-x].append(x)
        Ld[x+y].append(x)
        L[y].append(x)
    elif u == 'U':
        U[x].append(y)
    else:
        D[x].append(y)
ans = float('inf')
for x in U:
    if len(D[x]) > 0:
        D[x].sort()
        le = len(D[x])
        for y in U[x]:
            idx = bisect_right(D[x], y)
            if idx < le and ans > (D[x][idx]-y)/2:
                ans = (D[x][idx]-y)/2
for y in R:
    if len(L[y]) > 0:
        L[y].sort()
        le = len(L[y])
        for x in R[y]:
            idx = bisect_right(L[y], x)
            if idx < le and ans > (L[y][idx]-x)/2:
                ans = (L[y][idx]-x)/2
for k in Ru:
    Ru[k].sort()
for k in Lu:
    Lu[k].sort()
for k in Rd:
    Rd[k].sort()
for k in Ld:
    Ld[k].sort()
for x, y, u in XYU:
    if u == 'U':
        if len(Ru[x+y]) > 0:
            idx = bisect_right(Ru[x+y], x)-1
            if 0 <= idx < len(Ru[x+y]):
                ans = min(ans, x-Ru[x+y][idx])
        if len(Lu[y-x]) > 0:
            idx = bisect_right(Lu[y-x], x)
            if idx < len(Lu[y-x]):
                ans = min(ans, Lu[y-x][idx]-x)
    elif u == 'D':
        if len(Rd[y-x]) > 0:
            idx = bisect_right(Rd[y-x], x)-1
            if 0 <= idx < len(Rd[y-x]):
                ans = min(ans, x-Rd[y-x][idx])
        if len(Ld[x+y]) > 0:
            idx = bisect_right(Ld[x+y], x)
            if idx < len(Ld[x+y]):
                ans = min(ans, Ld[x+y][idx]-x)
if ans == float('inf'):
    print('SAFE')
else:
    print(int(ans*10))

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    from collections import defaultdict
    X, Y = defaultdict(list), defaultdict(list)
    dx, dy = defaultdict(list), defaultdict(list)
    for i in range(N):
        x, y, U = list(input().split())
        x, y = int(x), int(y)
        X[x].append((y, U))
        Y[y].append((x, U))
        dy[x+y].append((x-y, U))
        dx[x-y].append((x+y, U))
    ans = float("inf")
    for key in X.keys():
        X[key].sort()
        for i in range(1, len(X[key])):
            y1, dir1 = X[key][i-1]
            y2, dir2 = X[key][i]
            if dir1 == "U" and dir2 == "D":
                ans = min(ans, 5*y2-5*y1)
    for key in Y.keys():
        Y[key].sort()
        for i in range(1, len(Y[key])):
            y1, dir1 = Y[key][i-1]
            y2, dir2 = Y[key][i]
            if dir1 == "R" and dir2 == "L":
                ans = min(ans, 5*y2-5*y1)
    for key in dx.keys():
        dx[key].sort()
        for i in range(1, len(dx[key])):
            y1, dir1 = dx[key][i-1]
            y2, dir2 = dx[key][i]
            if (dir1 == "U" and dir2 == "L") or (dir1 == "R" and dir2 == "D"):
                ans = min(ans, 5*y2-5*y1)
    for key in dy.keys():
        dy[key].sort()
        for i in range(1, len(dy[key])):
            y1, dir1 = dy[key][i-1]
            y2, dir2 = dy[key][i]
            if (dir1 == "R" and dir2 == "U") or(dir1 == "D" and dir2 == "L"):
                ans = min(ans, 5*y2-5*y1)
    if ans == float("inf"):
        print("SAFE")
    else:
        print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]


inf=10**16
n=II()
xyu=[SI().split() for _ in range(n)]
dir="LRDU"
xyu=[(int(x),int(y),dir.index(u)) for x,y,u in xyu]
xyu.sort()

ans=inf
# 左向き
ytox=defaultdict(int)
hu=defaultdict(list)
sei=defaultdict(list)
for x,y,u in xyu:
    if u==1:
        ytox[y]=x
    if u==2:hu[x+y]=[x,y]
    if u==3:sei[x-y]=[x,y]
    if u==0:
        if y in ytox:
            ans=min(ans,(x-ytox[y])*5)
        if x+y in hu:
            ans=min(ans,abs(x-hu[x+y][0])*10)
        if x-y in sei:
            ans=min(ans,abs(x-sei[x-y][0])*10)

# 右
hu=defaultdict(list)
sei=defaultdict(list)
for x,y,u in xyu[::-1]:
    if u==3:hu[x+y]=[x,y]
    if u==2:sei[x-y]=[x,y]
    if u==1:
        if x+y in hu:
            ans=min(ans,abs(x-hu[x+y][0])*10)
        if x-y in sei:
            ans=min(ans,abs(x-sei[x-y][0])*10)

xyu.sort(key=lambda x:x[1])
ytox=defaultdict(int)
hu=defaultdict(list)
sei=defaultdict(list)
for x,y,u in xyu:
    if u==3:
        ytox[x]=y
    if u==2:
        if x in ytox:
            ans=min(ans,(y-ytox[x])*5)

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