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:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

########################################################################################################################################################################

show_flg=False
show_flg=True

ans=0


n=I()

Dx=[defaultdict(list)for i in range(4)]
Dy=[defaultdict(list)for i in range(4)]
Np=[defaultdict(list)for i in range(4)]
Nm=[defaultdict(list)for i in range(4)]

C=dict(zip('RULD',range(4)))
'''
Dx=defaultdict(list)
Dy=defaultdict(list)
Lx=defaultdict(list)
Ly=defaultdict(list)
Ux=defaultdict(list)
Uy=defaultdict(list)
Rx=defaultdict(list)
Ry=defaultdict(list)
Dx=defaultdict(list)
Dy=defaultdict(list)
'''
D,L,R,U=[defaultdict(list)for i in range(4)]
D3,L3,R3,U3=[defaultdict(list)for i in range(4)]
D4,L4,R4,U4=[defaultdict(list)for i in range(4)]
fl=[]

for i in range(n):
    x,y,q=input().split()
    x,y=map(int,[x,y])
    fl+=(x,y,q),
    d=C[q]
    if q=='D':
        D[x].append(y)
        D3[x-y].append(+(x+y))
        D4[x+y].append(-(x-y))
    elif q=='U':
        U[x].append(-y)
        U3[x-y].append(-(x+y))
        U4[x+y].append(+(x-y))
    elif q=='L':
        L[y].append(x)
        L3[x-y].append(+(x+y))
        L4[x+y].append(+(x-y))
    elif q=='R':
        R[y].append(-x)
        R3[x-y].append(-(x+y))
        R4[x+y].append(-(x-y))

show(D,U,R,L)
ans=inf
for x,y,q in fl:
    if q=='D':
        if x in U:
            m=bisect.bisect(U[x],-y)
            if m<len(U[x]):
                ans=min(ans,abs(U[x][m]+y)*5)
                show(ans)
        if x-y in D3:
            m=bisect.bisect(R3[x-y],-(x+y))
            show(x,y,m)
            if m<len(R3[x-y]):
                ans=min(ans,abs(R3[x-y][m]+x+y)*5)
                show(ans,3)
        if x+y in U4:
            m=bisect.bisect(U4[x+y],-(x-y))
            if m<len(U4[x+y]):
                ans=min(ans,abs(U4[x+y][m]+(x-y))*5)
                show(ans,4)

    elif q=='U7':
        if x in U[x]:
            m=bisect(-y,U[x])
            if m<len(U[x]):
                show(U[x][m])
            
        
    elif q=='U':
        0

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    xyp = [input().split() for _ in [0]*n]
    for i in range(n):
        xyp[i][0] = int(xyp[i][0])
        xyp[i][1] = int(xyp[i][1])
    inf = 10**10
    ans = inf
    u_list, d_list, l_list, r_list = [], [], [], []
    for x, y, d in xyp:
        if d == "D":
            d_list.append((x, y))
        elif d == "R":
            r_list.append((x, y))
        elif d == "L":
            l_list.append((x, y))
        else:
            u_list.append((x, y))
    # 1→u,d
    li, lj = len(u_list), len(d_list)
    u_list.sort()
    d_list.sort()
    i, j = 0, 0
    while(i < li and j < lj):
        v = d_list[j][0] - u_list[i][0]
        w = d_list[j][1] - u_list[i][1]
        if v > 0:
            i += 1
        elif v < 0:
            j += 1
        else:
            if w > 0:
                ans = min(ans, w*5)
                i += 1
            else:
                j += 1
    # 2→r,l
    li, lj = len(r_list), len(l_list)
    r_list.sort(key=lambda x: x[1])
    l_list.sort(key=lambda x: x[1])
    i, j = 0, 0
    while(i < li and j < lj):
        v = l_list[j][1] - r_list[i][1]
        w = l_list[j][0] - r_list[i][0]
        if v > 0:
            i += 1
        elif v < 0:
            j += 1
        else:
            if w > 0:
                ans = min(ans, w*5)
                i += 1
            else:
                j += 1
    # 3→u,l
    li, lj = len(u_list), len(l_list)
    u_list.sort(key=lambda x: x[0]-x[1])
    l_list.sort(key=lambda x: x[0]-x[1])
    i, j = 0, 0
    while(i < li and j < lj):
        v = l_list[j][0]-l_list[j][1] - u_list[i][0]+u_list[i][1]
        w = l_list[j][0] - u_list[i][0]
        if v > 0:
            i += 1
        elif v < 0:
            j += 1
        else:
            if w > 0:
                ans = min(ans, w*10)
                i += 1
            else:
                j += 1
    # 4→d,l
    li, lj = len(d_list), len(l_list)
    d_list.sort(key=lambda x: x[0]+x[1])
    l_list.sort(key=lambda x: x[0]+x[1])
    i, j = 0, 0
    while(i < li and j < lj):
        v = l_list[j][0]+l_list[j][1] - d_list[i][0]-d_list[i][1]
        w = l_list[j][0] - d_list[i][0]
        if v > 0:
            i += 1
        elif v < 0:
            j += 1
        else:
            if w > 0:
                ans = min(ans, w*10)
                i += 1
            else:
                j += 1
    # 5→u,r
    li, lj = len(u_list), len(r_list)
    u_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    i, j = 0, 0
    while(i < li and j < lj):
        v = r_list[j][0]+r_list[j][1] - u_list[i][0]-u_list[i][1]
        w = u_list[i][0] - r_list[j][0]
        if v > 0:
            i += 1
        elif v < 0:
            j += 1
        else:
            if w > 0:
                ans = min(ans, w*10)
                i += 1
            else:
                j += 1
    # 6→d,r
    li, lj = len(d_list), len(r_list)
    d_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    i, j = 0, 0
    while(i < li and j < lj):
        v = r_list[j][0]-r_list[j][1] - d_list[i][0]+d_list[i][1]
        w = d_list[i][0] - r_list[j][0]
        if v > 0:
            i += 1
        elif v < 0:
            j += 1
        else:
            if w > 0:
                ans = min(ans, w*10)
                i += 1
            else:
                j += 1
    if ans == inf:
        print("SAFE")
    else:
        print(ans)


main()

Submission status: Wrong Answer

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

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect
input = sys.stdin.readline

# 再起回数上限変更
# sys.setrecursionlimit(1000000)

n = int(input())
# data = [[] for _ in range(n)]
data = []

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

ans = 0

# x, yでソート
data = sorted(data, key=lambda x:(x[0], x[1]))

flg = False
prev_x = -1
for i in range(n):
    x, y, u = data[i][0], data[i][1], data[i][2]
    if x == prev_x and flg and u == 'D':
            ans = max(ans, y - prev_y)
    if u == 'U':
        flg = True
        prev_y = data[i][1]
    else:
        flg = False
    prev_x = data[i][0]

# y, xでソート
data = sorted(data, key=lambda x:(x[1], x[0]))

flg = False
prev_y = -1
for i in range(n):
    x, y, u = data[i][0], data[i][1], data[i][2]
    if y == prev_y and flg and u == 'L':
            ans = max(ans, x - prev_x)
    if u == 'R':
        flg = True
        prev_x = data[i][0]
    else:
        flg = False
    prev_y = data[i][1]

if ans == 0:
    print('SAFE')
else:
    print(ans*5)

Submission status: Wrong Answer

Solution code:
n = int(input())

u = [[] for i in range(200001)]
uw = [[] for i in range(400001)]
us = [[] for i in range(400001)]

d = [[] for i in range(200001)]
dw = [[] for i in range(400001)]
ds = [[] for i in range(400001)]

l = [[] for i in range(200001)]
lw = [[] for i in range(400001)]
ls = [[] for i in range(400001)]

r = [[] for i in range(200001)]
rw = [[] for i in range(400001)]
rs = [[] for i in range(400001)]

ans = 10 ** 100
for i in range(n):
  _x, _y, _u = map(str, input().split())
  x = int(_x)
  y = int(_y)
  
  if _u == 'U':
    u[x].append(y)
    uw[x + y].append(x - y)
    us[(x - y) + 200000].append(x + y)
    
    for __y in d[x]:
      if y < __y:
        ans = min(ans, (__y - y) * 5)
  
    for __sa in rw[x + y]:
      if x - y > __sa:
        ans = min(ans, (x - y - __sa) * 5)

    for __wa in ls[x - y + 200000]:
      if x + y < __wa:
        ans = min(ans, (__wa - x - y) * 5)
  
  if _u == 'D':
    d[y].append(x)
    dw[x + y].append(x - y)
    ds[(x - y) + 200000].append(x + y)

    for __y in u[x]:
      if y > __y:
        ans = min(ans, (y - __y) * 5)
  
    for __sa in lw[x + y]:
      if x - y < __sa:
        ans = min(ans, (__sa - x + y) * 5)

    for __wa in rs[x - y + 200000]:
      if x + y > __wa:
        ans = min(ans, (x + y - __wa) * 5)
  
  if _u == 'L':
    l[y].append(x)
    lw[x + y].append(x - y)
    ls[(x - y) + 200000].append(x + y)

    for __x in r[y]:
      if x > __x:
        ans = min(ans, (x - __x) * 5)
  
    for __sa in dw[x + y]:
      if x - y > __sa:
        ans = min(ans, (x - y - __sa) * 5)

    for __wa in us[x - y + 200000]:
      if x + y > __wa:
        ans = min(ans, (x + y - __wa) * 5)
  
  if _u == 'R':
    r[y].append(x)
    rw[x + y].append(x - y)
    rs[(x - y) + 200000].append(x + y)
    
    for __x in l[y]:
      if x < __x:
        ans = min(ans, (__x - x) * 5)
  
    for __sa in uw[x + y]:
      if x - y < __sa:
        ans = min(ans, (__sa - x + y) * 5)

    for __wa in ds[x - y + 200000]:
      if x + y < __wa:
        ans = min(ans, (__wa - x - y) * 5)

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

Submission status: Wrong Answer

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[x].append(y)

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

Solution code:
from collections import defaultdict
import bisect

n = int(input())
# x, yの値 URDLの順
p = [[] for _ in range(4)]
# xに対するyの値 URDLの順
px = [defaultdict(list) for _ in range(4)]
# yに対するyの値 URDLの順
py = [defaultdict(list) for _ in range(4)]
# x, yの和　URDLの順
s = [defaultdict(list) for _ in range(4)]
# x, yの差　URDLの順
d = [defaultdict(list) for _ in range(4)]

directions = {"U":0, "R":1, "D":2, "L":3}

for i in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    p.append([x, y])
    px[directions[u]][x].append(y)
    py[directions[u]][y].append(x)
    s[directions[u]][x+y].append([x, y])
    d[directions[u]][x-y].append([x, y])

print("SAFE")

Submission status: Wrong Answer

Solution code:
import numpy as np
from collections import Counter

n = int(input())

x, y, u = [], [], []

for _ in range(n):
    a, b, c = map(str, input().split())
    x.append(int(a))
    y.append(int(b))
    u.append(c)


INF = 1 << 60
ans = INF

x = np.array(x)
y = np.array(y)
u = np.array(u)


# 縦でぶつかる
c = Counter(x)

tate = [x for x, y in list(c.items()) if y > 1]

for t in tate:
    up = y[np.where((x == t) & (u == "U"))]
    down = y[np.where((x == t) & (u == "D"))]
    for a in up:
        for b in down:
            if a < b:
                ans = min(ans, (b - a) * 5)

# 横でぶつかる
c = Counter(y)

yoko = [x for x, y in list(c.items()) if y > 1]

for t in yoko:
    right = y[np.where((x == t) & (u == "R"))]
    left = y[np.where((x == t) & (u == "L"))]
    for a in right:
        for b in left:
            if a < b:
                ans = min(ans, (b - a) * 5)

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

Submission status: Wrong Answer

Solution code:
N=int(input())
A=[]
U,R,D,L=[],[],[],[]
for i in range(N):
  x,y,a=input().split()
  x,y=int(x),int(y)
  A.append((x,y))
  if a=='U':
    U.append((x,y))
  elif a=='R':
    R.append((x,y))
  elif a=='D':
    D.append((x,y))
  elif a=='L':
    L.append((x,y))
T=10**10
for a,b in R:
  for c,d in U:
    if a<c and b>d:
      if c-a==b-d:
        T=min(T,c-a)
for a,b in R:
  for c,d in D:
    if a<c and b<d:
      if c-a==d-b:
        T=min(T,c-a)
for a,b in L:
  for c,d in U:
    if a>c and b>d:
      if a-c==b-d:
        T=min(T,b-d)
for a,b in L:
  for c,d in D:
    if a>c and b<d:
      if a-c==d-b:
        T=min(T,d-b)

Submission status: Wrong Answer

Solution code:
from itertools import combinations
d = {'U':0, 'D':1, 'L':2, 'R':3}
N = int(input())
xy = [[[] for _ in range(200001)] for _ in range(4)]
xpy = [[[] for _ in range(400001)] for _ in range(4)]
xmy = [[[] for _ in range(400001)] for _ in range(4)]
lst = []
ans = 1001001001
for i in range(N):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    lst.append((x,y,u))
    if u == 'U':
        xy[d[u]][x].append(i)
        for j in xy[d['D']][x]:
            if lst[j][1] > y:
                ans = min(ans, lst[j][1] - y)
        xpy[d[u]][x+y].append(i)
        for j in xpy[d['R']][x+y]:
            if lst[j][0] < x:
                ans = min(ans, (x - lst[j][0])*2)
        xmy[d[u]][x-y+20000].append(i)
    elif u == 'D':
        xy[d[u]][x].append(i)
        for j in xy[d['U']][x]:
            if lst[j][1] < y:
                ans = min(ans, y - lst[j][1])
        xpy[d[u]][x+y].append(i)
        for j in xpy[d['L']][x+y]:
            if lst[j][0] > x:
                ans = min(ans, (lst[j][0]-x)*2)
        xmy[d[u]][x-y+20000].append(i)
    elif u == 'R':
        xy[d[u]][y].append(i)
        for j in xy[d['L']][y]:
            if lst[j][0] > x:
                ans = min(ans, lst[j][0] - x)
        xpy[d[u]][x+y].append(i)
        for j in xpy[d['U']][x+y]:
            if lst[j][0] > x:
                ans = min(ans, (lst[j][0]-x)*2)
        xmy[d[u]][x-y+20000].append(i)
    elif u == 'L':
        xy[d[u]][y].append(i)
        for j in xy[d['R']][y]:
            if lst[j][0] < x:
                ans = min(ans, x - lst[j][0])
        xpy[d[u]][x+y].append(i)
        for j in xpy[d['D']][x+y]:
            if lst[j][0] < x:
                ans = min(ans, (x - lst[j][0])*2)
        xmy[d[u]][x-y+20000].append(i)
# print(lst)
if ans == 1001001001:
    print("SAFE")
else:
    print(ans*5)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import bisect_left

n = int(input())
XYU = [list(input().split()) for _ in range(n)]

# 正面衝突用
box = {"U":defaultdict(list),"D":defaultdict(list),"L":defaultdict(list),"R":defaultdict(list)}

for x, y, u in XYU:
  x = int(x)
  y = int(y)
  if u in ["U","D"]:
    box[u][x].append(y) 
  else:
    box[u][y].append(x)
    
for k1 in box.keys():
  for k2 in box[k1].keys():
    box[k1][k2] = sorted(box[k1][k2])
    
dis = 10 ** 19 
for k, v in box["U"].items():
  if k in box["D"]:
    for pos in v:
      if pos < box["D"][k][0]:
        a = bisect_left(box["D"][k], pos)
        dis = min(dis, box["D"][k][a] - pos) * 10 // 2

for k, v in box["R"].items():
  if k in box["L"]:
    for pos in v:
      if pos < box["L"][k][0]:  
        a = bisect_left(box["L"][k], pos)
        dis = min(dis, box["L"][k][a] - pos) * 10 // 2

if dis == 10 ** 19:
  print("SAFE")
else:
  print(dis)

Submission status: Wrong Answer

Solution code:
n=int(input(""))
listx=[[200000,0]]*200001
listy=[[200000,0]]*200001
for i in range(n):
    lis=input("").split(" ")
    t=int(lis[1])
    s=int(lis[0])
  
    if(lis[2]=="U"):
        
        if(listy[t][0]>s):
            listy[t][0]=s
    elif(lis[2]=="R"):
        if(listx[s][0]>t):
            listx[s][0]=t
    elif(lis[2]=="D"):
        if(listy[t][1]<s):
            listy[t][1]=s
    else:
        if(listx[s][0]<t):
            listx[s][0]=t
time=0
for i in listx:
    tmp=i[0]-i[1]
    if(tmp<0):
        if(time>tmp*10):
            time=tmp*10
for i in listy:
    tmp=i[0]-i[1]
    if(tmp<0):
        if(time>tmp*10):
            time=tmp*10
if(time==0):
    print("SAFE")
else:
    print(time)

Submission status: Wrong Answer

Solution code:
import collections
import heapq
def main():

    N = int(input())

    horizontal = dict()
    horizontal = collections.defaultdict(list)
    vertical = collections.defaultdict(list)
    UL = collections.defaultdict(list)
    UR = collections.defaultdict(list)
    DL = collections.defaultdict(list)
    DR = collections.defaultdict(list)
    for _ in range(N):
        X, Y, U = input().split()
        X = int(X)
        Y = int(Y)
        if U == 'R':
            heapq.heappush(horizontal[Y], [X, 0])
            heapq.heappush(UR[X+Y], [X, 0]) # ok
            heapq.heappush(DR[X-Y], [X, 0]) # ok
        elif U == 'L':
            heapq.heappush(horizontal[Y], [X, 1])
            heapq.heappush(UL[X-Y], [X, 1]) # ok
            heapq.heappush(DL[X+Y], [X, 1]) # ok
        elif U == 'U':
            heapq.heappush(vertical[X], [Y, 0])
            heapq.heappush(UL[X-Y], [X, 0]) #ok
            heapq.heappush(UR[X+Y], [X, 1]) # ok
        else:
            heapq.heappush(vertical[X], [Y, 1])
            heapq.heappush(DL[X+Y], [X, 0]) # ok
            heapq.heappush(DR[X-Y], [X, 1]) # ok
    # print(horizontal)
    # print(vertical)

    ans = float('inf')
    for Y in horizontal:
        if len(horizontal[Y]) > 1:
            for j in range(len(horizontal[Y])-1):
                if horizontal[Y][j][1] == 0 and horizontal[Y][j+1][1] == 1:
                    ans = min(ans, 5 * (horizontal[Y][j+1][0]- horizontal[Y][j][0]))
    for X in vertical:
        if len(vertical[X]) > 1:
            for j in range(len(vertical[X])-1):
                if vertical[X][j][1] == 0 and vertical[X][j+1][1] == 1:
                    ans = min(ans, 5 * (vertical[X][j+1][0]- vertical[X][j][0]))
    for X in UL:
        if len(UL[X]) > 1:
            for j in range(len(UL[X])-1):
                if UL[X][j][1] == 0 and UL[X][j+1][1] == 1 and (UL[X][j+1][0]- UL[X][j][0]) > 0:
                    ans = min(ans, 10 * (UL[X][j+1][0]- UL[X][j][0]))
    for X in UR:
        if len(UR[X]) > 1:
            for j in range(len(UR[X])-1):
                if UR[X][j][1] == 0 and UR[X][j+1][1] == 1 and (UR[X][j+1][0]- UR[X][j][0]) > 0:
                    ans = min(ans, 10 * (UR[X][j+1][0]- UR[X][j][0]))

    for X in DL:
        if len(DL[X]) > 1:
            for j in range(len(DL[X])-1):
                if DL[X][j][1] == 0 and DL[X][j+1][1] == 1 and (DL[X][j+1][0]- DL[X][j][0]) > 0:
                    ans = min(ans, 10 * (DL[X][j+1][0]- DL[X][j][0]))

    for X in DR:
        if len(DR[X]) > 1:
            for j in range(len(DR[X])-1):
                if DR[X][j][1] == 0 and DR[X][j+1][1] == 1 and (DR[X][j+1][0]- DR[X][j][0]) > 0:
                    ans = min(ans, 10 * (DR[X][j+1][0]- DR[X][j][0]))

    if ans == float('inf'): return "SAFE"
    return ans

if __name__ == '__main__':
    print(main())

Submission status: Wrong Answer

Solution code:
def main():
    from collections import defaultdict
    from bisect import bisect_left
    import sys
    N=int(sys.stdin.readline())
    x_dic={
        'U':defaultdict(list),
        'R':defaultdict(list),
        'D':defaultdict(list),
        'L':defaultdict(list),
    }
    y_dic={
        'U':defaultdict(list),
        'R':defaultdict(list),
        'D':defaultdict(list),
        'L':defaultdict(list),
    }

    XpY=defaultdict(lambda : defaultdict(list))
    XmY=defaultdict(lambda : defaultdict(list))

    for i in range(N):
        X,Y,U=sys.stdin.readline().split()
        X=int(X)
        Y=int(Y)
        x_dic[U][X].append(Y)
        y_dic[U][Y].append(X)
        
        XpY[X+Y][U].append(X)
        XmY[X-Y][U].append(X)

    mn=10**15

    for key,lst1 in x_dic['R'].items():
        if key in x_dic['L']:
            lst2=x_dic['L'][key]
            
            lst1.sort()
            lst2.sort()

            c1=0
            c2=0
            while True:
                if lst1[c1]<lst2[c2]:
                    tmp=(lst2[c2]-lst1[c1])*5
                    mn=tmp if tmp<mn else mn
                    c1+=1
                    if c1==len(lst1):
                        break
                else:
                    c2+=1
                    if c2==len(lst2):
                        break

            
    for key,lst1 in x_dic['U'].items():
        if key in x_dic['D']:
            lst2=x_dic['D'][key]
            
            lst1.sort()
            lst2.sort()

            c1=0
            c2=0
            while True:
                if lst1[c1]<lst2[c2]:
                    tmp=(lst2[c2]-lst1[c1])*5
                    mn=tmp if tmp<mn else mn
                    c1+=1
                    if c1==len(lst1):
                        break
                else:
                    c2+=1
                    if c2==len(lst2):
                        break

    for _,dic in XpY.items():
        if ('U' in dic and 'R' in dic):
            lst1=sorted(dic['R'])
            lst2=sorted(dic['U'])

            c1=0
            c2=0
            while True:
                if lst1[c1]<lst2[c2]:
                    tmp=(lst2[c2]-lst1[c1])*10
                    mn=tmp if tmp<mn else mn
                    c1+=1
                    if c1==len(lst1):
                        break
                else:
                    c2+=1
                    if c2==len(lst2):
                        break



        elif ('D' in dic and 'L' in dic):
            lst1=sorted(dic['D'])
            lst2=sorted(dic['L'])

            c1=0
            c2=0
            while True:
                if lst1[c1]<lst2[c2]:
                    tmp=(lst2[c2]-lst1[c1])*10
                    mn=tmp if tmp<mn else mn
                    c1+=1
                    if c1==len(lst1):
                        break
                else:
                    c2+=1
                    if c2==len(lst2):
                        break

    for _,dic in XmY.items():
        if ('U' in dic and 'L' in dic):
            lst1=sorted(dic['U'])
            lst2=sorted(dic['L'])

            c1=0
            c2=0
            while True:
                if lst1[c1]<lst2[c2]:
                    tmp=(lst2[c2]-lst1[c1])*10
                    mn=tmp if tmp<mn else mn
                    c1+=1
                    if c1==len(lst1):
                        break
                else:
                    c2+=1
                    if c2==len(lst2):
                        break



        elif ('D' in dic and 'R' in dic):
            lst1=sorted(dic['R'])
            lst2=sorted(dic['D'])

            c1=0
            c2=0
            while True:
                if lst1[c1]<lst2[c2]:
                    tmp=(lst2[c2]-lst1[c1])*10
                    mn=tmp if tmp<mn else mn
                    c1+=1
                    if c1==len(lst1):
                        break
                else:
                    c2+=1
                    if c2==len(lst2):
                        break

    if mn==10**15:
        print('SAFE')
    else:
        print(mn)

main()