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:
n = int(input())
b = 2000001
x = []
u = []
r = []
d = []
l = []
for i in range(n):
    A = list(input().split())
    a = [int(A[0]), int(A[1])]
    if A[2] == "U":
        u.append(a)
    elif A[2] == "R":
        r.append(a)
    elif A[2] == "D":
        d.append(a)
    else:
        l.append(a)
#ud
u1 = {}
d1 = {}
for i in range(len(u)):
    u1[u[i][0]] = u[i][1]
for i in range(len(d)):
    d1[d[i][0]] = d[i][1]
for i in range(200001):
    if i in u1 and i in d1:
        if u1[i] < d1[i]:
            b = min(b, (d1[i]-u1[i])*5)
#rl
r1 = {}
l1 = {}
for i in range(len(r)):
    r1[r[i][1]] = r[i][0]
for i in range(len(l)):
    l1[l[i][1]] = l[i][0]
for i in range(200001):
    if i in r1 and i in l1:
        if r1[i] < l1[i]:
            b = min(b, (l1[i]-r1[i])*5)
#ur
u2 = {}
r2 = {}
for i in range(len(u)):
    u2[u[i][0]+u[i][1]] = u[i][0]
for i in range(len(r)):
    r2[r[i][0]+r[i][1]] = r[i][0]
for i in range(400001):
    if i in u2 and i in r2:
        if r2[i] < u2[i]:
            b = min(b, (u2[i]-r2[i])*10)
#ld
l2 = {}
d2 = {}
for i in range(len(l)):
    l2[l[i][0]+l[i][1]] = l[i][0]
for i in range(len(d)):
    d2[d[i][0]+d[i][1]] = d[i][0]
for i in range(400001):
    if i in l2 and i in d2:
        if d2[i] < l2[i]:
            b = min(b, (l2[i]-d2[i])*10)
#lu
l3 = {}
u3 = {}
for i in range(len(l)):
    l3[l[i][0]-l[i][1]] = l[i][0]
for i in range(len(u)):
    u3[u[i][0]-u[i][1]] = u[i][0]
for i in range(-200000, 200001):
    if i in l3 and i in u3:
        if u3[i] < l3[i]:
            b = min(b, (l3[i]-u3[i])*10)
#dr
d3 = {}
r3 = {}
for i in range(len(d)):
    d3[d[i][0]-d[i][1]] = d[i][0]
for i in range(len(r)):
    r3[r[i][0]-r[i][1]] = r[i][0]
for i in range(-200000, 200001):
    if i in d3 and i in r3:
        if r3[i] < d3[i]:
            b = min(b, (d3[i]-r3[i])*10)
if b == 2000001:
    print("SAFE")
else:
    print(b)

Submission status: Wrong Answer

Solution code:
N = int(input())
P = [input().split() for _ in range(N)]

d = {"U": 0, "D": 0, "L": 1, "R": 1}

res = 10**10
for i in range(N):
    for j in range(i):
        a = P[i]
        b = P[j]

        if a[2] == b[2]:
            continue

        a[0] = int(a[0])
        a[1] = int(a[1])
        b[0] = int(b[0])
        b[1] = int(b[1])

        aa = 0
        bb = 0

        if a[2] == "U":
            aa = abs(a[1]-b[1])
            if b[2] == "D":
                if a[0] == b[0]:
                    if a[1] > b[1]:
                        continue
                    res = min(abs(a[1]-b[1])*5, res)
                    continue
            if b[2] == "L":
                if a[0] < b[0]:
                    bb = abs(a[0]-b[0])
            if b[2] == "R":
                if a[0] > b[0]:
                    bb = abs(a[0]-b[0])
        
        if a[2] == "D":
            aa = abs(a[1]-b[1])
            if b[2] == "U":
                if a[0] == b[0]:
                    if a[1] < b[1]:
                        continue
                    res = min(abs(a[1]-b[1])*5, res)
                    continue
            if b[2] == "L":
                if a[0] < b[0]:
                    bb = abs(a[0]-b[0])
            if b[2] == "R":
                if a[0] > b[0]:
                    bb = abs(a[0]-b[0])

        if a[2] == "L":
            aa = abs(a[0]-b[0])
            if b[2] == "R":
                if a[1] == b[1]:
                    if a[0] < b[0]:
                        continue
                    res = min(abs(a[0]-b[0])*5, res)
                    continue
            if b[2] == "U":
                if a[0] > b[0]:
                    bb = abs(a[1]-b[1])
            if b[2] == "D":
                if a[0] < b[0]:
                    bb = abs(a[1]-b[1])

        if a[2] == "R":
            aa = abs(a[0]-b[0])
            if b[2] == "L":
                if a[1] == b[1]:
                    if a[0] > b[0]:
                        continue
                    res = min(abs(a[0]-b[0])*5, res)
                    continue
            if b[2] == "U":
                if a[0] > b[0]:
                    bb = abs(a[1]-b[1])
            if b[2] == "D":
                if a[0] < b[0]:
                    bb = abs(a[1]-b[1])

        if aa == bb:
            res = min(aa*10, res)
        
        # print(i, j, aa, bb, res)

if res != 10**10:    
    print(res)
else:
    print("SAFE")

Submission status: Wrong Answer

Solution code:
n=int(input())
xp=[]
xm=[]
yp=[]
ym=[]
for i in range(200001):
    xp.append([-1])
    xm.append([-1])
    yp.append([-1])
    ym.append([-1])
mn=float("inf")
for i in range(n):
  x,y,u=input().split()
  x,y=int(x),int(y)
  if u=="U":
    if ym[x]!=[]:
      dist=float("inf")
      for j in ym[x]:
        if len(ym[x])==1:
          break
        if j==-1:
          continue
        if j<y:
          continue
        dist=min(dist, abs(j-y))

      else:
        if dist !=float("inf"):
           mn=min(mn,dist)
    yp[x].append(y)


  if u=="D":
    if yp[x]!=[]:
      dist=float("inf")
      for j in yp[x]:
        if len(yp[x])==1:
          break
        if j==-1:
          continue
        if j>y:
          continue
        dist=min(dist, abs(j-y))
      else:
        if dist !=float("inf"):
           mn=min(mn,dist)
    ym[x].append(y)

  if u=="R":
    if xm[y]!=[]:
      dist=float("inf")
      for j in xm[y]:
        if len(xm[y])==1:
          break
        if j==-1:
          continue
        if j<x:
          continue
        dist=min(dist, abs(j-x))
      else:
        if dist !=float("inf"):
           mn=min(mn,dist)
    xp[y].append(x)
  if u=="L":
    if xp[y]!=[]:
      dist=float("inf")
      for j in xp[y]:
        if len(xp[y])==1:
          break
        if j==-1:
          continue
        if j>x:
          continue
        dist=min(dist, abs(j-x))
      else:
        if dist !=float("inf"):
           mn=min(mn,dist)
    xm[y].append(x)
if mn==float("inf"):
  print("SAFE")
else:
  print(mn*5)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = []
ans = []
b = len(A) // 3
for i in range(N):
    X, Y, o = input().split()
    A.append(X)
    A.append(Y)
    A.append(o)
x = A[ : :3]
y = A[1: :3]
n = A[2: :3]
print(x)
print(y)
print(n)
for i in range(N):
    for j in range(N):
        if x[i] == x[j]:
            if n[i] == 'U' and n[j] =='D' or n[i] == 'D' and n[j] =='U' or n[i] == 'R' and n[j] == 'L' or n[i] == 'L' and n[j] == 'R':
                y[i] =int(y[i])
                y[j] =int(y[j])
                t = abs(y[i] - y[j]) / 0.2
                ans.append(t)
        if y[i] == y[j]:
            if n[i] == 'U' and n[j] =='D' or n[i] == 'D' and n[j] =='U' or n[i] == 'R' and n[j] == 'L' or n[i] == 'L' and n[j] == 'R':
                x[i] =int(x[i])
                x[j] =int(x[j])
                t = abs(x[i] - x[j]) / 0.2
                ans.append(t)
print(ans)
if len(ans) == 0:
    print('SAFE')
else:
    ans = sorted(ans)
    print(int(ans[0]))

Submission status: Wrong Answer

Solution code:
N = int(input())
XYU = [list(map(str,input().split())) for _ in range(N)]
from collections import deque
INF = float('inf')

R = [deque() for _ in range(200001)]
L = [deque() for _ in range(200001)]
U = [deque() for _ in range(200001)]
D = [deque() for _ in range(200001)]

for X,Y,u in XYU:
  X = int(X)
  Y = int(Y)
  if u=='R':
    R[Y].append(X)
  elif u=='L':
    L[Y].append(X)
  elif u=='U':
    U[X].append(Y)
  else:
    D[X].append(Y)
    
safe = True
ans = INF
for a,b in zip(U,D):
  if (len(a)!=0)and(len(b)!=0):
    for x in a:
      for y in b:
        z = y-x
        if z>=0:
          safe = False
          ans = min(ans,y-x)
          
for a,b in zip(R,L):
  if (len(a)!=0)and(len(b)!=0):
    for x in a:
      for y in b:
        z = y-x
        if z>=0:
          safe = False
          ans = min(ans,y-x)
          
          
if safe:
  print('SAFE')
else:
  print(ans//2 * 10)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

N = int(input())

In = defaultdict(lambda: list())
Dn = defaultdict(lambda: list())

un = defaultdict(lambda: list())
rn = defaultdict(lambda: list())

for _ in range(N):
    X, Y, U = input().split()
    X = int(X)
    Y = int(Y)

    bi = Y - X
    bd = X + Y
    if U == 'U':
        In[bi].append((X, 0))
        Dn[bd].append((X, 1))
        un[X].append((Y, 0))
    if U == 'R':
        In[bi].append((X, 0))
        Dn[bd].append((X, 0))
        rn[Y].append((X, 0))
    if U == 'D':
        In[bi].append((X, 1))
        Dn[bd].append((X, 0))
        un[X].append((Y, 1))
    if U == 'L':
        In[bi].append((X, 1))
        Dn[bd].append((X, 1))
        rn[Y].append((X, 1))

def get_mins(ns):
    r = None
    pn, pu = ns[0]
    for n, u in ns[1:]:
        if pu == 0:
            if u == 1:
                cr = n - pn
                if r is None or cr < r:
                    r = cr
        pn, pu = (n, u)
    return r


res = None

for k in In:
    In[k] = sorted(In[k], key=lambda x: x[0])
    mins = get_mins(In[k])
    if res is None or (mins is not None and mins < res):
        res = mins

for k in un:
    un[k] = sorted(un[k], key=lambda x: x[0])
    mins = get_mins(un[k])
    if mins is None:
        continue
    mins = int(mins / 2)
    if res is None or (mins is not None and mins < res):
        res = mins

for k in rn:
    rn[k] = sorted(rn[k], key=lambda x: x[0])
    mins = get_mins(rn[k])
    if mins is None:
        continue
    mins = int(mins / 2)
    if res is None or (mins is not None and mins < res):
        res = mins

for k in Dn:
    Dn[k] = sorted(Dn[k], key=lambda x: x[0])
    mins = get_mins(Dn[k])
    if res is None or (mins is not None and mins < res):
        res = mins

if res is None:
    print('SAFE')
else:
    print(res * 10)

Submission status: Wrong Answer

Solution code:
n = int(input())
x = [0]*n
y = [0]*n

ux = [0]*n
uy = [0]*n


for i in range(n):
    x[i],y[i],u =  input().split()
    if u=="U":
        uy[i] =1
    elif u=="R":
        ux[i] =1
    elif u=="D":
        uy[i] =-1
    elif u=="L":
        ux[i] =-1
    x[i]= int(x[i])
    y[i]= int(y[i])
time = 2*10**7
for i in range(n):
    for j in range(n-1-i):

            if x[i]-x[i+1+j] == 0 and  y[i]-y[i+1+j] == 0:
                time = min(time,0)
            elif x[i]-x[i+1+j] == 0 and uy[i]*uy[i+1+j]==-1 and (y[i]-y[i+1+j])*uy[i]>0:
                time = min(time,abs((y[i]-y[i+1+j])/0.2))
            elif y[i]-y[i+1+j] == 0 and ux[i]*ux[i+1+j]==-1 and (x[i]-x[i+1+j])*ux[i]>0:
                time = min(time,abs((x[i]-x[i+1+j])/0.2))
            elif (ux[i]-ux[i+1+j])==0 or (uy[i]-uy[i+1+j])==0:
                time =time
            elif (x[i]-x[i+1+j]) /(ux[i]-ux[i+1+j]) ==(y[i]-y[i+1+j]) /(uy[i]-uy[i+1+j]):
                time = min(time,abs((x[i]-x[i+1+j])/0.1))

if time == 2*10**7:
    print("SAFE")
else:
    print(int(time))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [list(input().split()) for i in range(n)]
l = 2*10**5 + 5
# l = 5
# B = [[int(A[i][0]), int(A[i][1]), int(A[i][0])+int(A[i][1]), int(A[i][0])-int(A[i][1])+l, A[i][2]] for i in range(n)]

D = [[[] for j in range(2*l)] for i in range(4)]

# for i in range(4):
#     for j in range(n):
#         D[i][B[j][i]].append(B[j])

for i in range(n):
    x = int(A[i][0])
    y = int(A[i][1])
    nn = [x,y,A[i][2]]
    D[0][x].append(nn)
    D[1][y].append(nn)
    D[2][x+y].append(nn)
    D[3][x-y+l].append(nn)

# print(D)
import bisect
ans = float("inf")
for i in range(l):
    # print(D[1][i])
    LR = [[], []]
    for j in range(len(D[1][i])):
        
        if D[1][i][j][2] == "L":
            LR[0].append(D[1][i][j][0])
        if D[1][i][j][2] == "R":
            LR[1].append(D[1][i][j][0])
    LR[0].sort()
        # print(j,LR)
    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, LR[0][ind]-LR[1][k]) * 5

for i in range(l):
    # print(D[0][i])
    LR = [[], []]
    for j in range(len(D[0][i])):
        
        if D[0][i][j][2] == "U":
            LR[0].append(D[0][i][j][1])
        if D[0][i][j][2] == "D":
            LR[1].append(D[0][i][j][1])

    LR[1].sort()
        # print(j,LR)
    for k in range(len(LR[0])):
        ind = bisect.bisect(LR[1], LR[0][k])
        # print("ind",ind)
        if ind != len(LR[1]):
            ans = min(ans, LR[1][ind]-LR[0][k]) * 5

for i in range(2*l):
    # print(D[1][i])
    LR = [[], []]
    LR2 = [[], []]
    for j in range(len(D[2][i])):
        
        if D[2][i][j][2] == "L":
            LR[0].append(D[2][i][j][0])
        if D[2][i][j][2] == "D":
            LR[1].append(D[2][i][j][0])

        if D[2][i][j][2] == "U":
            LR2[0].append(D[2][i][j][0])
        if D[2][i][j][2] == "R":
            LR2[1].append(D[2][i][j][0])
        

    # print(j,LR2)
    LR[0].sort()
    LR2[0].sort()

    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, LR[0][ind]-LR[1][k]) * 10
    
    for k in range(len(LR2[1])):
        ind = bisect.bisect(LR2[0], LR2[1][k])
        if ind != len(LR2[0]):
            ans = min(ans, LR2[0][ind]-LR2[1][k]) * 10

for i in range(2*l):
    # print(D[1][i])
    LR = [[], []]
    LR2 = [[], []]
    for j in range(len(D[3][i])):
        
        if D[3][i][j][2] == "D":
            LR[0].append(D[3][i][j][1])
        if D[3][i][j][2] == "R":
            LR[1].append(D[3][i][j][1])

        if D[3][i][j][2] == "L":
            LR2[0].append(D[3][i][j][1])
        if D[3][i][j][2] == "U":
            LR2[1].append(D[3][i][j][1])
    
    LR[0].sort()
    LR2[0].sort()

        # print(j,LR)
    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, LR[0][ind]-LR[1][k]) * 10
    
    for k in range(len(LR2[1])):
        ind = bisect.bisect(LR2[0], LR2[1][k])
        if ind != len(LR2[0]):
            ans = min(ans, LR2[0][ind]-LR2[1][k]) * 10


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

Submission status: Wrong Answer

Solution code:
N = int(input())

U = []
R = []
D = []
L = []

for i in range(N):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == 'U':
        U.append((x, y))
    elif u == 'R':
        R.append((x, y))
    elif u == 'D':
        D.append((x, y))
    elif u == 'L':
        L.append((x, y))

ans = float('inf')

for ux, uy in U:
    for dx, dy in D:
        if ux == dx and uy <= dy:
            ans = min(ans, ((dy-uy)//2)*10)
    for lx, ly in L:
        if lx - ux == ly - uy and lx - ux >= 0:
            ans = min(ans, (lx-ux) * 10)
    for rx, ry in R:
        if ux - rx == ry - uy and ux - rx >= 0:
            ans = min(ans, (ux-rx) * 10)

for dx, dy in D:
    for lx, ly in L:
        if lx - dx == dy - ly and lx - dx >= 0:
            ans = min(ans, (lx-dx) * 10)
    for rx, ry in R:
        if dx - rx == dy - ry and dx - rx >= 0:
            ans = min(ans, (dx-rx) * 10)

for lx, ly in L:
    for rx, ry in R:
        if ly == ry and lx >= rx:
            ans = min(ans, ((lx-rx)//2)*10)

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
n = int(input())
infos = []
dic = {"L":0,"R":1,"D":0,"U":1}
lr_dic = [defaultdict(list)] * 2 # straight LR
ud_dic =  [defaultdict(list)] * 2 # straight UD
lr_dic_p = [defaultdict(list)] * 2 # x + y LR
ud_dic_p = [defaultdict(list)] * 2 # x + y UD
lr_dic_m = [defaultdict(list)] * 2 # -x + y LR
ud_dic_m = [defaultdict(list)] * 2 # -x + y UD


for i in range(n):
    x,y,u = input().split()
    x = int(x)
    y = int(y)
    if u == "R" or u == "L":
        lr_dic[dic[u]][y].append(x)
        lr_dic_p[dic[u]][x+y].append(y)
        lr_dic_m[dic[u]][-x+y].append(y)
    
    else:
        ud_dic[dic[u]][x].append(y)
        ud_dic_p[dic[u]][x+y].append(x)
        ud_dic_m[dic[u]][-x+y].append(x)
    infos.append((u,x,y))
flg = True
mn = 1 << 50
for u,x,y in infos:
    if u == "D":
        # Lの中で、yより小さくて切片がx+yのもの
        ys = lr_dic_p[dic["L"]][x+y]
        for y_ in ys:
            if y_ < y:
                flg = False
                mn = min(mn, abs(y-y_))
        # Rの中で、yより小さくて切片が-x+yのもの
        ys = lr_dic_p[dic["R"]][x-y]
        for y_ in ys:
            if y_ < y:
                flg = False
                mn = min(mn, abs(y-y_))
        # Uの中でxが一致するもの
        ys = ud_dic[dic["U"]][x]
        for y_ in ys:
            if y_ < y:
                flg = False
                mn = min(mn, abs(y-y_)/2)
    elif u == "U":
        # Lの中で、yより大きくて切片が-x+yのもの
        ys = lr_dic_p[dic["L"]][x-y]
        for y_ in ys:
            if y_ > y:
                flg = False
                mn = min(mn, abs(y-y_))
        # Rの中で、yより大きくて切片がx+yのもの
        ys = lr_dic_p[dic["R"]][x+y]
        for y_ in ys:
            if y_ > y:
                flg = False
                mn = min(mn, abs(y-y_))
        # Dのなかでxが一致するもの
        ys = ud_dic[dic["D"]][x]
        for y_ in ys:
            if y_ > y:
                flg = False
                mn = min(mn, abs(y-y_)/2)

    elif u == "R":
        # Dの中で、xより大きくて切片が-x+yのもの
        xs = ud_dic_m[dic["D"]][-x+y]
        for x_ in xs:
            if x_ > x:
                flg = False
                mn = min(mn, abs(x-x_))
        # Uの中で、xより大きくて切片がx+yのもの
        xs = ud_dic_m[dic["U"]][x+y]
        for x_ in xs:
            if x_ > x:
                flg = False
                mn = min(mn, abs(x-x_))
        # Lのなかでyが一致するもの
        xs = lr_dic[dic["L"]][y]
        for x_ in xs:
            if x_ > x:
                flg = False
                mn = min(mn, abs(x-x_)/2)

    elif u == "L":
        # Dの中で、xより小さくて切片がx+yのもの
        xs = ud_dic_m[dic["D"]][x+y]
        for x_ in xs:
            if x_ < x:
                flg = False
                mn = min(mn, abs(x-x_))
        # Uの中で、xより小さくて切片が-x+yのもの
        xs = ud_dic_m[dic["U"]][-x+y]
        for x_ in xs:
            if x_ < x:
                flg = False
                mn = min(mn, abs(x-x_))

        # Rのなかでyが一致するもの
        xs = lr_dic[dic["R"]][y]
        for x_ in xs:
            if x_ < x:
                flg = False
                mn = min(mn, abs(x-x_)/2)

if flg:
    print("SAFE")
else:
    print(mn*10)

Submission status: Wrong Answer

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(400001)]
w = [[] for _ in range(400002)]
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].append((xi,1))
    w[xi-yi+200001].append((xi,-1))                       
  elif ui == "R":
    y[yi].append((xi,1))
    z[xi+yi].append((xi,1))
    w[xi-yi+200001].append((xi,1))  
  else:
    y[yi].append((xi,-1))
    z[xi+yi].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: 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])

ans = 10**9

# R, Uパターン
keys = list(s[directions["R"]].keys())
for k in keys:
    for rx, ry in s[directions["R"]][k]:
        for ux, uy in s[directions["U"]][k]:
            if rx > ux:
                continue
            ans = min(ans, abs(rx-ux)*10)
# L, Dパターン
keys = list(s[directions["L"]].keys())
for k in keys:
    for lx, ly in s[directions["L"]][k]:
        for dx, dy in s[directions["D"]][k]:
            if lx < dx:
                continue
            ans = min(ans, abs(lx-dx)*10)
# L, Uパターン
keys = list(s[directions["L"]].keys())
for k in keys:
    for lx, ly in s[directions["L"]][k]:
        for ux, uy in s[directions["U"]][k]:
            if lx < ux:
                continue
            ans = min(ans, abs(lx-ux)*10)
# R, Dパターン
keys = list(s[directions["R"]].keys())
for k in keys:
    for rx, ry in s[directions["R"]][k]:
        for dx, dy in s[directions["D"]][k]:
            if rx > dx:
                break
            ans = min(ans, abs(rx-rx)*10)

# U, Dパターン
keys = list(px[directions["U"]].keys())
for k in keys:
    if len(px[directions["D"]][k]) == 0:
        continue
    px[directions["D"]][k].sort()
    for uy in px[directions["U"]][k]:
        if uy > px[directions["D"]][k][-1]:
            break
        pos = bisect.bisect_left(px[directions["D"]][k], uy)
        ans = min(ans, (px[directions["D"]][k][pos]-uy)*5)

# R, Lパターン
keys = list(px[directions["R"]].keys())
for k in keys:
    if len(px[directions["L"]][k]) == 0:
        continue
    px[directions["L"]][k].sort()
    for uy in px[directions["R"]][k]:
        if uy > px[directions["L"]][k][-1]:
            break
        pos = bisect.bisect_left(px[directions["L"]][k], uy)
        ans = min(ans, (px[directions["L"]][k][pos]-uy)*5)

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

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

import sys, io, os, re
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from pprint import pprint
from math import sin, cos, pi, radians, sqrt, floor, ceil
from copy import copy, deepcopy
from collections import deque
from fractions import gcd
from functools import reduce
from itertools import groupby
from heapq import heapify, heappush, heappop
from collections import defaultdict

# sys.setrecursionlimit(5000)

n1 = lambda: int(sys.stdin.readline().strip())
nn = lambda: list(map(int, sys.stdin.readline().strip().split()))
f1 = lambda: float(sys.stdin.readline().strip())
fn = lambda: list(map(float, sys.stdin.readline().strip().split()))
s1 = lambda: sys.stdin.readline().strip()
sn = lambda: list(sys.stdin.readline().strip().split())
nl = lambda n: [n1() for _ in range(n)]
fl = lambda n: [f1() for _ in range(n)]
sl = lambda n: [s1() for _ in range(n)]
nm = lambda n: [nn() for _ in range(n)]
fm = lambda n: [fn() for _ in range(n)]
sm = lambda n: [sn() for _ in range(n)]

def array1(n, d=0): return [d] * n
def array2(n, m, d=0): return [[d] * m for x in range(n)]
def array3(n, m, l, d=0): return [[[d] * l for y in xrange(m)] for x in xrange(n)]
def linc(A, d=1): return map(lambda x: x + d, A)
def ldec(A, d=1): return map(lambda x: x - d, A)

N = n1()
X = []
Y = []
U = []
ZX = defaultdict(list)
ZY = defaultdict(list)
for i in range(N):
    x, y, u = sn()
    X.append(int(x))
    Y.append(int(y))
    U.append(u)
    ZX[x].append([int(y), u])
    ZY[y].append([int(x), u])

ns_min = 10**10
tmp = ns_min
for k in ZX.keys():
    if len(ZX[k]) >= 2:
        for i in range(len(ZX[k])):
            for j in range(i+1, len(ZX[k])):
                if ZX[k][i][1] == "U" and ZX[k][j][1] == "D" and ZX[k][i][0] < ZX[k][j][0]:
                    tmp = (ZX[k][j][0] - ZX[k][i][0]) / 2
                if ZX[k][i][1] == "D" and ZX[k][j][1] == "U" and ZX[k][i][0] > ZX[k][j][0]:
                    tmp = (ZX[k][i][0] - ZX[k][j][0]) / 2
                if tmp < ns_min: ns_min = tmp                    

ew_min = 10**10
tmp = ew_min
for k in ZY.keys():
    if len(ZY[k]) >= 2:
        for i in range(len(ZY[k])):
            for j in range(i+1, len(ZY[k])):
                if ZY[k][i][1] == "R" and ZY[k][j][1] == "L" and ZY[k][i][0] < ZY[k][j][0]:
                    tmp = (ZY[k][j][0] - ZY[k][i][0]) / 2
                if ZY[k][i][1] == "L" and ZY[k][j][1] == "R" and ZY[k][i][0] > ZY[k][j][0]:
                    tmp = (ZY[k][i][0] - ZY[k][j][0]) / 2
                if tmp < ew_min: ew_min = tmp                    


def trans(a, b):
    return (a+b, b-a)    

ZX = defaultdict(list)
ZY = defaultdict(list)
for i in range(N):
    x, y = trans(X[i], Y[i])
    u = U[i]
    ZX[x].append([int(y), u])
    ZY[y].append([int(x), u])

ns2_min = 10**10
for k in ZX.keys():
    if len(ZX[k]) >= 2:
        for i in range(len(ZX[k])):
            for j in range(i+1, len(ZX[k])):
                if ZX[k][i][1] == "U" and ZX[k][j][1] == "R" and ZX[k][i][0] < ZX[k][j][0]:
                    tmp = (ZX[k][j][0] - ZX[k][i][0]) / 2
                if ZX[k][i][1] == "D" and ZX[k][j][1] == "L" and ZX[k][i][0] > ZX[k][j][0]:
                    tmp = (ZX[k][i][0] - ZX[k][j][0]) / 2
                if tmp < ns2_min: ns2_min = tmp                    

ew2_min = 10**10
for k in ZY.keys():
    if len(ZY[k]) >= 2:
        for i in range(len(ZY[k])):
            for j in range(i+1, len(ZY[k])):
                if ZY[k][i][1] == "R" and ZY[k][j][1] == "D" and ZY[k][i][0] < ZY[k][j][0]:
                    tmp = (ZY[k][j][0] - ZY[k][i][0]) / 2
                if ZY[k][i][1] == "L" and ZY[k][j][1] == "U" and ZY[k][i][0] > ZY[k][j][0]:
                    tmp = (ZY[k][i][0] - ZY[k][j][0]) / 2
                if tmp < ew2_min: ew2_min = tmp    

ans = min(ns_min, ew_min, ns2_min, ew2_min)*10
if ans == 100000000000:
    ans = "SAFE"

print(ans)