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:
n = int(input())
n1, n2 = 200001, 400001
s1, s2 = [[] for _ in range(n1)], [[] for _ in range(n1)]
s3, s4 = [[] for _ in range(n2)], [[] for _ in range(n2)]
for _ in range(n):
    x, y, u = input().split()
    x, y = int(x), int(y)
    a, b = x + y, x - y + 200000
    s1[x].append([y, u])
    s2[y].append([x, u])
    s3[a].append([b, u])
    s4[b].append([a, u])
ans = 100000000
for t in s1:
    if not t:
        continue
    a, b = -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "U":
            a = tt[0]
        elif tt[1] == "D":
            b = tt[0]
        if not min(a, b) == -1 and a < b:
            ans = min(ans, 5 * (b - a))
for t in s2:
    if not t:
        continue
    a, b = -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "R":
            a = tt[0]
        elif tt[1] == "L":
            b = tt[0]
        if not min(a, b) == -1 and a < b:
            ans = min(ans, 5 * (b - a))
for t in s3:
    if not t:
        continue
    a, b, c, d = -1, -1, -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "U":
            a = tt[0]
        elif tt[1] == "D":
            b = tt[0]
        elif tt[1] == "R":
            c = tt[0]
        elif tt[1] == "L":
            d = tt[0]
        if not min(a, c) == -1 and a > c:
            ans = min(ans, 5 * (a - c))
        if not min(b, d) == -1 and d > b:
            ans = min(ans, 5 * (d - b))
for t in s4:
    if not t:
        continue
    a, b, c, d = -1, -1, -1, -1
    t.sort()
    for tt in t:
        if tt[1] == "U":
            a = tt[0]
        elif tt[1] == "D":
            b = tt[0]
        elif tt[1] == "R":
            c = tt[0]
        elif tt[1] == "L":
            d = tt[0]
        if not min(b, c) == -1 and c < b:
            ans = min(ans, 5 * (b - c))
        if not min(a, d) == -1 and a < d:
            ans = min(ans, 5 * (d - a))
print(ans if not ans == 100000000 else "SAFE")

Submission status: Accepted

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

from collections import defaultdict
M = 200001
N = int(input())
F = []
X = [[] for _ in range(M)] #上向きのy座標, 下向きのy座標
Y = [[] for _ in range(M)]

S1 = defaultdict(list) #x+yが一致
S2 = defaultdict(list)
T1 = defaultdict(list)
T2 = defaultdict(list)

for _ in range(N):
    x, y, c = input().split()
    x = int(x)
    y = int(y)
    if c == 'U':
        c = 0
        S1[x + y].append((x - y, c))
        T1[x - y].append((x + y, c))
    elif c == 'R':
        c = 1
        S1[x + y].append((x - y, c))
        T2[x - y].append((x + y, c))
    elif c == 'D':
        c = 2
        S2[x + y].append((x - y, c))
        T2[x - y].append((x + y, c))
    else:
        c = 3
        S2[x + y].append((x - y, c))
        T1[x - y].append((x + y, c))
    if c % 2 == 0:
        X[x].append((y, c))
    else:
        Y[y].append((x, c))

res = 10**18

for i in range(M):
    X[i].sort()
    tmp = None
    for j in range(len(X[i])):
        y, c = X[i][j]
        if c == 0:
            tmp = y
        if c == 2:
            if tmp is not None:
                res = min(res, (y - tmp) * 5)

for i in range(M):
    Y[i].sort()
    tmp = None
    for j in range(len(Y[i])):
        x, c = Y[i][j]
        if c == 1:
            tmp = x
        if c == 3:
            if tmp is not None:
                res = min(res, (x - tmp) * 5)

for k, v in S1.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 1:
            tmp = z
        if c == 0:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

for k, v in S2.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 2:
            tmp = z
        if c == 3:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

for k, v in T1.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 0:
            tmp = z
        if c == 3:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

for k, v in T2.items():
    v.sort()
    tmp = None
    for j in range(len(v)):
        z, c = v[j]
        if c == 1:
            tmp = z
        if c == 2:
            if tmp is not None:
                res = min(res, (z - tmp) * 5)

print(res if res != 10**18 else 'SAFE')

Submission status: Accepted

Solution code:
n = int(input())
xyu = [list(input().split()) for _ in range(n)]

r = []
l = []
u = []
d = []
ans = 10**15

for x,y,U in xyu:
    x = int(x)
    y = int(y)
    if U == 'U':
        u.append((x,y,x+y,x-y))
    elif U == 'R':
        r.append((x,y,x+y,x-y))
    elif U == 'D':
        d.append((x,y,x+y,x-y))
    else:
        l.append((x,y,x+y,x-y))

xr = [[] for _ in range(200010)]
xl = [[] for _ in range(200010)]

for x,y,z,w in r:
    xr[y].append(x)

for x,y,z,w in l:
    xl[y].append(x)

for i in range(len(xr)):
    if xr[i] and xl[i]:
        a = sorted(xr[i])
        b = sorted(xl[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*5)

yd = [[] for _ in range(200010)]
yu = [[] for _ in range(200010)]

for x,y,z,w in d:
    yd[x].append(y)

for x,y,z,w in u:
    yu[x].append(y)

for i in range(len(yd)):
    if yd[i] and yu[i]:
        b = sorted(yd[i])
        a = sorted(yu[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*5)

zr = [[] for _ in range(400010)]
zu = [[] for _ in range(400010)]

for x,y,z,w in r:
    zr[z].append(x)

for x,y,z,w in u:
    zu[z].append(x)

for i in range(len(zr)):
    if zr[i] and zu[i]:
        b = sorted(zu[i])
        a = sorted(zr[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

zd = [[] for _ in range(400010)]
zl = [[] for _ in range(400010)]

for x,y,z,w in d:
    zd[z].append(x)

for x,y,z,w in l:
    zl[z].append(x)

for i in range(len(zd)):
    if zd[i] and zl[i]:
        b = sorted(zl[i])
        a = sorted(zd[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

wd = [[] for _ in range(400010)]
wr = [[] for _ in range(400010)]

for x,y,z,w in d:
    wd[w+200005].append(x)

for x,y,z,w in r:
    wr[w+200005].append(x)

for i in range(len(wr)):
    if wd[i] and wr[i]:
        b = sorted(wd[i])
        a = sorted(wr[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

wl = [[] for _ in range(400010)]
wu = [[] for _ in range(400010)]

for x,y,z,w in l:
    wl[w+200005].append(x)

for x,y,z,w in u:
    wu[w+200005].append(x)

for i in range(len(wl)):
    if wl[i] and wu[i]:
        b = sorted(wl[i])
        a = sorted(wu[i])
        tmp = 0
        tmp2 = 10**10
        flag = True
        for j in range(len(a)):
            if flag:
                while a[j] > b[tmp]:
                    tmp += 1
                    if tmp >= len(b):
                        flag = False
                        break
                if flag:
                    tmp2 = min(tmp2, b[tmp]-a[j])
        ans = min(ans, tmp2*10)

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

Submission status: Accepted

Solution code:
import bisect

n = int(input())
xyu_180_1 = {}
xyu_180_2 = {}
xyu_90_1 = {}
xyu_90_2 = {}
xyu_90_3 = {}
xyu_90_4 = {}
for i in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U":
        xyu_180_2.setdefault(x, {"U":[], "D":[]})
        xyu_180_2[x][u].append(y)
        xyu_90_1.setdefault(x + y, {"R":[], "U":[]})
        xyu_90_1[x + y][u].append(x - y)
        xyu_90_2.setdefault(x - y, {"U":[], "L":[]})
        xyu_90_2[x - y][u].append(x + y)
    elif u == "R":
        xyu_180_1.setdefault(y, {"R":[], "L":[]})
        xyu_180_1[y][u].append(x)
        xyu_90_1.setdefault(x + y, {"R":[], "U":[]})
        xyu_90_1[x + y][u].append(x - y)
        xyu_90_4.setdefault(x - y, {"D":[], "R":[]})
        xyu_90_4[x - y][u].append(x + y)
    elif u == "D":
        xyu_180_2.setdefault(x, {"U":[], "D":[]})
        xyu_180_2[x][u].append(y)
        xyu_90_3.setdefault(x + y, {"L":[], "D":[]})
        xyu_90_3[x + y][u].append(x - y)
        xyu_90_4.setdefault(x - y, {"D":[], "R":[]})
        xyu_90_4[x - y][u].append(x + y)
    elif u == "L":
        xyu_180_1.setdefault(y, {"R":[], "L":[]})
        xyu_180_1[y][u].append(x)
        xyu_90_2.setdefault(x - y, {"U":[], "L":[]})
        xyu_90_2[x - y][u].append(x + y)
        xyu_90_3.setdefault(x + y, {"D":[], "L":[]})
        xyu_90_3[x + y][u].append(x - y)
time = float("inf")
for i in xyu_180_1.values():
    if i["R"] and i["L"]:
        num = i["L"]
        num.sort()
        for j in i["R"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_180_2.values():
    if i["U"] and i["D"]:
        num = i["D"]
        num.sort()
        for j in i["U"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_1.values():
    if i["R"] and i["U"]:
        num = i["U"]
        num.sort()
        for j in i["R"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_2.values():
    if i["U"] and i["L"]:
        num = i["L"]
        num.sort()
        for j in i["U"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_3.values():
    if i["D"] and i["L"]:
        num = i["L"]
        num.sort()
        for j in i["D"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
for i in xyu_90_4.values():
    if i["R"] and i["D"]:
        num = i["D"]
        num.sort()
        for j in i["R"]:
            num2 = bisect.bisect(num, j)
            if num2 != len(num):
                temp = (num[num2] - j) * 5
                time = min(time, temp)
if time == float("inf"):
    print("SAFE")
else:
    print(time)

Submission status: Accepted

Solution code:
n = int(input())
ans = 10 ** 10
upanddown = [[] for i in range(200001)]
leftandright = [[] for i in range(200001)]
lis = []
for i in range(n):
    x,y,r = map(str,input().split())
    x,y = int(x),int(y)
    lis.append([x+y,x-y,x,y,r])
    if r == "U":
        upanddown[x].append([y,0])
    elif r == "D":
        upanddown[x].append([y,1])
    elif r == "R":
        leftandright[y].append([x,0])
    else:
        leftandright[y].append([x,1])
  # print(upanddown[11])
for li in upanddown:
    if len(li) >= 2:
        li.sort(key=lambda z:z[1])
        li.sort(key=lambda z:z[0])
        key = 0
        keynum = -1
        for num,r in li:
            if r == 0:
                keynum = num
            else:
                if keynum != -1:
                    ans = min(ans,(num-keynum)*5)
for li in leftandright:
    if len(li) >= 2:
        li.sort(key=lambda z:z[1])
        li.sort(key=lambda z:z[0])
        key = 0
        keynum = -1
        for num,r in li:
            if r == 0:
                keynum = num
            else:
                if keynum != -1:
                    ans = min(ans,(num-keynum)*5)
  # print(ans)
lis.sort(key = lambda z:z[2])
lis.sort(key = lambda z:z[0])

for i in range(n-1):
    if lis[i][0] == lis[i+1][0]:
        if (lis[i][4] == "R" and lis[i+1][4] == "U") or (lis[i][4] == "D" and lis[i+1][4] == "L"):
            ans = min(ans,(lis[i+1][2]-lis[i][2])*10)
lis.sort(key = lambda z:z[2])
lis.sort(key = lambda z:z[1])

for i in range(n-1):
    if lis[i][1] == lis[i+1][1]:
        if (lis[i][4] == "U" and lis[i+1][4] == "L") or (lis[i][4] == "R" and lis[i+1][4] == "D"):
            ans = min(ans,(lis[i+1][2]-lis[i][2])*10)
if ans == 10 ** 10:
    print("SAFE")
else:
    print(ans)

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N = I()
data = SLL(N)

Udic = DD(list)
Ddic = DD(list)
Ldic = DD(list)
Rdic = DD(list)

URdic = DD(lambda:[[],[]])
DLdic = DD(lambda:[[],[]])

ULdic = DD(lambda:[[],[]])
DRdic = DD(lambda:[[],[]])

for i in range(N):
  x,y,s = data[i]
  x,y = int(x), int(y)
  if s == "U":
    Udic[x].append(y)
    URdic[x+y][0].append(x)
    ULdic[x-y][0].append(x)
  if s == "D":
    Ddic[x].append(y)
    DLdic[x+y][0].append(x)
    DRdic[x-y][0].append(x)
  if s == "L":
    Ldic[y].append(x)
    DLdic[x+y][1].append(x)
    ULdic[x-y][1].append(x)
  if s == "R":
    Rdic[y].append(x)
    URdic[x+y][1].append(x)
    DRdic[x-y][1].append(x)

col_t = INF

Uk = [k for k in Udic]
Dk = [k for k in Ddic]
Lk = [k for k in Ldic]
Rk = [k for k in Rdic]

UDk = set(Uk)&set(Dk)
LRk = set(Lk)&set(Rk)

for k in UDk:
  Udic[k].sort()
  for d in Ddic[k]:
    p = bisect.bisect(Udic[k],d)
    if p:
      col_t = min(col_t,(d-Udic[k][p-1])*5)
      
for k in LRk:
  Rdic[k].sort()
  for l in Ldic[k]:
    p = bisect.bisect(Rdic[k],l)
    if p:
      col_t = min(col_t,(l-Rdic[k][p-1])*5)
      
      
for k in URdic:
  if URdic[k][0] and URdic[k][1]:
    URdic[k][1].sort()
    for u in URdic[k][0]:
      p = bisect.bisect(URdic[k][1],u)
      if p:
        col_t = min(col_t,(u-URdic[k][1][p-1])*10)

for k in DLdic:
  if DLdic[k][0] and DLdic[k][1]:
    DLdic[k][0].sort()
    for l in DLdic[k][1]:
      p = bisect.bisect(DLdic[k][0],l)
      if p:
        col_t = min(col_t,(l-DLdic[k][0][p-1])*10)  

for k in ULdic:
  if ULdic[k][0] and ULdic[k][1]:
    ULdic[k][1].sort()
    for u in ULdic[k][0]:
      p = bisect.bisect(ULdic[k][1],u)
      if p<len(ULdic[k][1]):
        col_t = min(col_t,(ULdic[k][1][p]-u)*10)
for k in DRdic:
  if DRdic[k][0] and DRdic[k][1]:
    DRdic[k][0].sort()
    for r in DRdic[k][1]:
      p = bisect.bisect(DRdic[k][0],r)
      if p<len(DRdic[k][0]):
        col_t = min(col_t,(DRdic[k][0][p]-r)*10)
        
        
if col_t != INF:
  print(col_t)
else:
  print("SAFE")

Submission status: Accepted

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

n = int(readline())
xyu = read().split()

# x,y,/=p.\=m
num = 200_000
x,y,p,m = dict(),dict(),dict(),dict()
for i in [x,y]:
    for s in 'URDL':
        i[s] = [[] for _ in range(num+1)]

for i in [p,m]:
    for s in 'URDL':
        i[s] = [[] for _ in range(num*2+1)]

it = iter(xyu)
for a,b,c in zip(it,it,it):
    a = int(a)
    b = int(b)
    if(c in 'UD'):
        y[c][a].append(b)
    if(c in 'RL'):
        x[c][b].append(a)

    p[c][num + a-b].append(b)
    m[c][a+b].append(b)

inf = 10**10
ans = inf
for i in [x]:
    for j in range(num+1):
        #RL
        if(len(i['R'][j])>0)&(len(i['L'][j])>0):
            a = i['R'][j]
            a.sort()
            b = i['L'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*5)

for i in [y]:
    for j in range(num+1):
        #UD
        if(len(i['U'][j])>0)&(len(i['D'][j])>0):
            a = i['U'][j]
            a.sort()
            b = i['D'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*5)

for i in [p]:
    for j in range(num*2+1):
        #UL
        if(len(i['U'][j])>0)&(len(i['L'][j])>0):
            a = i['U'][j]
            a.sort()
            b = i['L'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

        #RD
        if(len(i['R'][j])>0)&(len(i['D'][j])>0):
            a = i['R'][j]
            a.sort()
            b = i['D'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

for i in [m]:
    for j in range(num*2+1):
        #UR
        if(len(i['U'][j])>0)&(len(i['R'][j])>0):
            a = i['U'][j]
            a.sort()
            b = i['R'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

        #LD
        if(len(i['L'][j])>0)&(len(i['D'][j])>0):
            a = i['L'][j]
            a.sort()
            b = i['D'][j]
            b.sort()
            b_ind = 0
            for ai in a:
                while(b_ind < len(b)):
                    if( ai > b[b_ind]):
                        b_ind += 1
                    else:
                        break
                if(b_ind == len(b)):
                    break
                ans = min(ans, abs(ai-b[b_ind])*10)

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

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
from collections import defaultdict

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def core(dic1, dic2):
    ans = INF
    for j in dic1.keys():
        if j not in dic2:
            continue
        dic1[j].sort()
        dic2[j].sort()
        v1 = dic1[j]
        v2 = dic2[j]
        for x in v1:
            i = bisect_left(v2, x)
            if i == len(v2):
                continue
            if ans > (v2[i] - x) * 10:
                ans = (v2[i] - x) * 10

    return ans


def main():
    N = int(readline())
    M = 200000
    U, R, D, L = [], [], [], []
    for _ in range(N):
        x, y, u = readline().split()
        x, y = int(x), int(y)
        if u == 'U':
            U.append((x, y))
        elif u == 'R':
            R.append((x, y))
        elif u == 'D':
            D.append((x, y))
        else:
            L.append((x, y))

    ans = INF

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in U:
        dic1[x].append(y)
    for x, y in D:
        dic2[x].append(y)

    for j in dic1.keys():
        if j not in dic2:
            continue
        dic1[j].sort()
        dic2[j].sort()
        v1 = dic1[j]
        v2 = dic2[j]
        for yu in v1:
            i = bisect_left(v2, yu)
            if i == len(v2):
                continue
            if ans > (v2[i] - yu) * 10 // 2:
                ans = (v2[i] - yu) * 10 // 2

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in R:
        dic1[y].append(x)
    for x, y in L:
        dic2[y].append(x)

    for j in dic1.keys():
        if j not in dic2:
            continue
        dic1[j].sort()
        dic2[j].sort()
        v1 = dic1[j]
        v2 = dic2[j]
        for xr in v1:
            i = bisect_left(v2, xr)
            if i == len(v2):
                continue
            if ans > (v2[i] - xr) * 10 // 2:
                ans = (v2[i] - xr) * 10 // 2

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in R:
        dic1[y - x].append(x)
    for x, y in D:
        dic2[y - x].append(x)

    ans = min(ans, core(dic1, dic2))

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in U:
        dic1[y - x].append(x)
    for x, y in L:
        dic2[y - x].append(x)

    ans = min(ans, core(dic1, dic2))

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in R:
        dic1[y + x].append(x)
    for x, y in U:
        dic2[y + x].append(x)

    ans = min(ans, core(dic1, dic2))

    dic1 = defaultdict(list)
    dic2 = defaultdict(list)
    for x, y in D:
        dic1[y + x].append(x)
    for x, y in L:
        dic2[y + x].append(x)

    ans = min(ans, core(dic1, dic2))

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

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

n = int(input())
m = 200000
y_r = [[] for _ in range(m+1)]
y_l = [[] for _ in range(m+1)]
x_u = [[] for _ in range(m+1)]
x_d = [[] for _ in range(m+1)]
xy_r = [[] for _ in range(2*m+1)]
xy_l = [[] for _ in range(2*m+1)]
xy_u = [[] for _ in range(2*m+1)]
xy_d = [[] for _ in range(2*m+1)]
yx_r = [[] for _ in range(2*m+1)]
yx_l = [[] for _ in range(2*m+1)]
yx_u = [[] for _ in range(2*m+1)]
yx_d = [[] for _ in range(2*m+1)]

for _ in range(n):
    x, y, u = input().split()
    x, y = int(x), int(y)
    if u == 'U':
        x_u[x].append(y)
        xy_u[x+y].append(x)
        yx_u[y-x+m].append(x)
    if u == 'D':
        x_d[x].append(y)
        xy_d[x+y].append(x)
        yx_d[y-x+m].append(x)
    if u == 'R':
        y_r[y].append(x)
        xy_r[x+y].append(x)
        yx_r[y-x+m].append(x)
    if u == 'L':
        y_l[y].append(x)
        xy_l[x+y].append(x)
        yx_l[y-x+m].append(x)

    

ans = 10 ** 9
for i in range(m+1):
    x_u[i].sort()
    x_d[i].sort()
    y_l[i].sort()
    y_r[i].sort()

    for yu in x_u[i]:
        idx = bisect.bisect_left(x_d[i], yu)
        if idx < len(x_d[i]):
            ans = min(ans, (x_d[i][idx] - yu) * 5)

    for xr in y_r[i]:
        idx = bisect.bisect_left(y_l[i], xr)
        if idx < len(y_l[i]):
            ans = min(ans, (y_l[i][idx] - xr) * 5)

for i in range(2*m+1):
    xy_u[i].sort()
    xy_d[i].sort()
    xy_l[i].sort()
    xy_r[i].sort()

    for xr in xy_r[i]:
        idx = bisect.bisect_left(xy_u[i], xr)
        if idx < len(xy_u[i]):
            ans = min(ans, (xy_u[i][idx] - xr) * 10)
    
    for xd in xy_d[i]:
        idx = bisect.bisect_left(xy_l[i], xd)
        if idx < len(xy_l[i]):
            ans = min(ans, (xy_l[i][idx] - xd) * 10)

    yx_u[i].sort()
    yx_d[i].sort()
    yx_l[i].sort()
    yx_r[i].sort()

    for xr in yx_r[i]:
        idx = bisect.bisect_left(yx_d[i], xr)
        if idx < len(yx_d[i]):
            ans = min(ans, (yx_d[i][idx] - xr) * 10)
    
    for xu in yx_u[i]:
        idx = bisect.bisect_left(yx_l[i], xu)
        if idx < len(yx_l[i]):
            ans = min(ans, (yx_l[i][idx] - xu) * 10)


print(ans if ans < 10 ** 9 else 'SAFE')