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())
xyu = []
for i in range(n):
    x, y, u = map(str, input().split())
    x = int(x)
    y = int(y)
    xyu.append( (x, y, u) )

axisx = [[] for _ in range(200001)]
axisy = [[] for _ in range(200001)]
axislb = [[] for _ in range(400001)]
axislt = [[] for _ in range(400001)]

for x, y, u in xyu:
    if u == 'U' or u == 'D':
        axisx[x].append( (y, u) )
    elif u == 'L' or u == 'R':
        axisy[y].append( (x, u) )
    axislb[x+y].append( (x, u) )
    axislt[x-y+200000].append( (x, u) )

m = 100000000

for i in range(200001):
    if axisx[i]:
        axisx[i] = sorted(axisx[i])
        # print('axisx['+str(i)+']: ', axisx[i])
        d = None
        pos = None
        for y, u in axisx[i]:
            if d is None:
                if u == 'U':
                    d = 'U'
                    pos = y
            elif d == 'U':
                if u == 'U':
                    pos = y
                else:
                    m = min((y - pos)*5, m)
                    d = None
                    pos = None

for i in range(200001):
    if axisy[i]:
        axisy[i] = sorted(axisy[i])
        # print('axisy['+str(i)+']: ', axisy[i])
        d = None
        pos = None
        for x, u in axisy[i]:
            if d is None:
                if u == 'U':
                    d = 'U'
                    pos = x
            elif d == 'U':
                if u == 'U':
                    pos = x
                else:
                    m = min((x - pos)*5, m)
                    d = None
                    pos = None

for i in range(400001):
    if axislb[i]:
        axislb[i] = sorted(axislb[i])
        # print('axislb['+str(i)+']: ', axislb[i])
        d = None
        pos = None
        for x, u in axislb[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                elif u == 'U':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None
        d = None
        pos = None
        for x, u in axislb[i]:
            if d is None:
                if u == 'D':
                    d = 'D'
                    pos = x
            elif d == 'D':
                if u == 'D':
                    pos = x
                elif u == 'L':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None

for i in range(400001):
    if axislt[i]:
        axislt[i] = sorted(axislt[i])
        # print('axislt['+str(i)+']: ', axislt[i])
        d = None
        pos = None
        for x, u in axislt[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                elif u == 'D':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None
        d = None
        pos = None
        for x, u in axislt[i]:
            if d is None:
                if u == 'U':
                    d = 'U'
                    pos = x
            elif d == 'U':
                if u == 'U':
                    pos = x
                elif u == 'L':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None

if m == 100000000:
    print('SAFE')
else:
    print(m)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [list(map(str, input().split())) for _ in range(row)]
        return map(list, zip(*read_all))

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

N = I()
X,Y,U = LIR(N,3)
X = [int(x) for x in X]
Y = [int(y) for y in Y]

d1 = defaultdict(lambda:defaultdict(list))
d2 = defaultdict(lambda:defaultdict(list))

u = defaultdict(list)
r = defaultdict(list)
d = defaultdict(list)
l = defaultdict(list)

for i in range(N):
    if U[i] == 'U':
        u[X[i]].append(Y[i])
    elif U[i] == 'D':
        d[X[i]].append(Y[i])
    elif U[i] == 'R':
        r[Y[i]].append(X[i])
    else:
        l[Y[i]].append(X[i])

for k in u.keys():
    u[k].sort()

for k in d.keys():
    d[k].sort()

for k in r.keys():
    r[k].sort()

for k in l.keys():
    l[k].sort()

for i in range(N):
    d1[U[i]][Y[i]-X[i]].append(X[i])
    d2[U[i]][Y[i]+X[i]].append(X[i])

ans = float('inf')
for i in range(N):
    if U[i] == 'U':
        p = bisect_left(d[X[i]],Y[i])
        if p <= len(d[X[i]])-1 and len(d[X[i]]):
            ans = min(ans,(d[X[i]][p]-Y[i])*5)

        p = bisect_left(d1['L'][Y[i]-X[i]],X[i])
        if p <= len(d1['L'][Y[i]-X[i]])-1 and len(d1['L'][Y[i]-X[i]]):
            ans = min(ans,(d1['L'][Y[i]-X[i]][p]-X[i])*10)  

        p = bisect_left(d2['R'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d2['R'][Y[i]+X[i]])-1 and len(d2['R'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d2['R'][Y[i]+X[i]][p-1])*10)

    elif U[i] == 'D':
        p = bisect_left(u[X[i]],Y[i])
        if 0 <= p-1 <= len(u[X[i]])-1 and len(u[X[i]]):
            ans = min(ans,(Y[i]-u[X[i]][p-1])*5)

        p = bisect_left(d1['R'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d1['R'][Y[i]-X[i]])-1 and len(d1['R'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d1['R'][Y[i]-X[i]][p-1])*10)       

        p = bisect_left(d2['L'][Y[i]+X[i]],X[i])
        if p <= len(d2['L'][Y[i]+X[i]])-1 and len(d2['L'][Y[i]+X[i]]):
            ans = min(ans,(d2['L'][Y[i]+X[i]][p]-X[i])*10)

    elif U[i] == 'R':
        p = bisect_left(l[Y[i]],X[i])
        if p <= len(l[Y[i]])-1 and len(l[Y[i]]):
            ans = min(ans,(l[Y[i]][p]-X[i])*5)

        p = bisect_left(d1['D'][Y[i]-X[i]],X[i])
        if p <= len(d1['D'][Y[i]-X[i]])-1 and len(d1['D'][Y[i]-X[i]]):
            ans = min(ans,(d1['D'][Y[i]-X[i]][p]-X[i])*10)       

        p = bisect_left(d2['U'][Y[i]+X[i]],X[i])
        if p <= len(d2['U'][Y[i]+X[i]])-1 and len(d2['U'][Y[i]+X[i]]):
            ans = min(ans,(d2['U'][Y[i]+X[i]][p]-X[i])*10)
    else:
        p = bisect_left(r[Y[i]],X[i])
        if 0 <=p-1 <= len(r[Y[i]])-1 and len(r[Y[i]]):
            ans = min(ans,(X[i]-r[Y[i]][p-1])*5)

        p = bisect_left(d2['D'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d2['D'][Y[i]-X[i]])-1 and len(d2['D'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d2['D'][Y[i]-X[i]][p-1])*10)       

        p = bisect_left(d1['U'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d1['U'][Y[i]+X[i]])-1 and len(d1['U'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d1['U'][Y[i]+X[i]][p-1])*10)


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

Submission status: Wrong Answer

Solution code:
from collections import deque

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

XYU = deque(XYU)

ud = {"U": (0, 1), "D": (0, -1), "R": (1, 0), "L": (-1, 0)}

candi = []

for i in range(N - 1):
    x0, y0, us0 = XYU.pop()
    x0 = int(x0)
    y0 = int(y0)
    u0 = ud[us0]

    for x1, y1, us1 in XYU:
        x1 = int(x1)
        y1 = int(y1)
        u1 = ud[us1]
        if us0 == us1:
            break

        # 直交で衝突しうる場合
        if u0[0] * u1[0] + u0[1] * u1[1] == 0:
            # 衝突する座標
            if u0[0] == 0:
                xx = x0
            else:
                yy = y0

            if u1[0] == 0:
                xx = x1
            else:
                yy = y1

            # 飛んでいく方向に衝突座標があり，衝突する？
            p0 = (xx - x0, yy - y0)
            p1 = (xx - x1, yy - y1)

            if abs(p0[0] + p0[1]) == abs(p1[0] + p1[1]):
                if u0[0] * p0[0] >= 0 and u0[1] * p0[1] >= 0:
                    if u1[0] * p1[0] >= 0 and u1[1] * p1[1] >= 0:
                        candi.append(abs(p0[0] + p0[1]) * 10)

        # 並行で衝突しうる場合
        if u0[0] == u1[0] * -1 and u0[1] == u1[1] * -1:
            if u0[0] == 0:
                if x0 == x1:
                    if y0 > y1 and u0[1] == -1:
                        candi.append(abs(y0 - y1) * 5)
                    elif y0 < y1 and u0[1] == 1:
                        candi.append(abs(y0 - y1) * 5)
            else:
                if y0 == y1:
                    if x0 > x1 and u0[0] == -1:
                        candi.append(abs(x0 - x1) * 5)
                    elif x0 < x1 and u0[0] == 1:
                        candi.append(abs(x0 - x1) * 5)


if candi:
    print(max(candi))
else:
    print("SAFE")

Submission status: Wrong Answer

Solution code:
N = int(input())
X = []
Y = []
U = []
time = 10**10
for i in range(N):
  xappend, yappend, uappend = input().split()
  xappend = int(xappend)
  yappend = int(yappend)
  X.append(xappend)
  Y.append(yappend)
  U.append(uappend)
  if i > 0:
    for j in range(i):
      if U[i] == "U" and U[j] == "D":
        if Y[i] < Y[j] and X[i] == X[j]:
          time = min((Y[j]-Y[i])*5, time)

      elif U[i] == "D" and U[j] == "U":
          if Y[i] > Y[j] and X[i] == X[j]:
            time = min((Y[i]-Y[j])*5, time)

      elif U[i] == "R" and U[j] == "L":
        if X[i] < X[j] and Y[i] == Y[j]:
          time = min((X[j]-X[i])*5, time)

      elif U[i] == "L" and U[j] == "R":
        if X[i] > X[j] and Y[i] == Y[j]:
          time = min((X[i]-X[j])*5, time)

      elif U[i] == "U" and U[j] == "R":
        if X[i] > X[j] and Y[i] < Y[j] and X[i]-X[j] == Y[j]-Y[i]:
          time = min((X[i]-X[j])*5, time)

      elif U[i] == "U" and U[j] == "L":
        if X[i] < X[j] and Y[i] < Y[j] and X[j]-X[i] == Y[j]-Y[i]:
          time = min((X[j]-X[i])*5, time)

      elif U[i] == "D" and U[j] == "R":
        if X[i] > X[j] and Y[i] > Y[j] and X[i]-X[j] == Y[i]-Y[j]:
          time = min((X[i]-X[j])*5, time)

      elif U[i] == "D" and U[j] == "L":
        if X[i] < X[j] and Y[i] > Y[j] and X[j]-X[i] == Y[j]-Y[i]:
          time = min((X[j]-X[i])*5, time)

      elif U[i] == "R" and U[j] == "U":
        if X[i] < X[j] and Y[i] > Y[j] and X[j]-X[i] == Y[i]-Y[j]:
          time = min((X[j]-X[i])*5, time)

      elif U[i] == "R" and U[j] == "D":
        if X[i] < X[j] and Y[i] < Y[j] and X[j]-X[i] == Y[j]-Y[i]:
          time = min((X[i]-X[j])*5, time)

      elif U[i] == "L" and U[j] == "U":
        if X[i] < X[j] and Y[i] < Y[j] and X[i]-X[j] == Y[i]-Y[j]:
          time = min((X[j]-X[i])*5, time)

      elif U[i] == "L" and U[j] == "D":
        if X[i] > X[j] and Y[i] < Y[j] and X[i]-X[j] == Y[j]-Y[i]:
          time = min((X[i]-X[j])*5, time)

if time < 10**8:
  print(time)
else:
  print("SAFE")

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()
    LR[1].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[0].sort()
    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()
    LR[1].sort()
    LR2[1].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][0])
        if D[3][i][j][2] == "R":
            LR[1].append(D[3][i][j][0])

        if D[3][i][j][2] == "L":
            LR2[0].append(D[3][i][j][0])
        if D[3][i][j][2] == "U":
            LR2[1].append(D[3][i][j][0])
    
    LR[0].sort()
    LR2[0].sort()
    LR[1].sort()
    LR2[1].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:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(500000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

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

xyu.sort(lambda x: (x[0],x[1]))
tate=[-1]*200001
yoko=[-1]*200001
ans=float('inf')
for i in range(n):
    x,y,u=xyu[i]
    if u=="D":
        if tate[x]==-1:
            continue
        else:
            ans=min(ans,(y-tate[x])*5)
    else:
        tate[x]=y
# print(ans)
xyu.sort(lambda x: (x[1],x[0]))
for i in range(n):
    x,y,u=xyu[i]
    if u=="L":
        if tate[x]==-1:
            continue
        else:
            ans=min(ans,(x-yoko[y])*5)
    else:
        yoko[y]=x
# print(ans)

dic={"U":0,"R":1,"D":2,"L":3}
cnt=[[] for i in range(2*200001)]
for i in range(n):
    x,y,u=xyu[i]
    cnt[x+y].append(i)
# print(cnt)

for i in range(len(cnt)):
    ul=[-1]*2
    if len(cnt[i])==0:
        continue
    cnt[i].sort(lambda x: xyu[x][1])
    # print(cnt[i])
    for j in range(len(cnt[i])):
        x,y,u=xyu[cnt[i][j]]
        if u=="U":
            ul[0]=y
        elif u=="L":
            ul[1]=y
        elif u=="D":
            if ul[1]!=-1:
                ans=min(ans,(y-ul[1])*10)
        elif u=="R":
            if ul[0]!=1:
                ans=min(ans,(y-ul[0])*10)
        # print(urdl)
# print(ans)
    
cnt=[[] for i in range(2*200001)]
# cnt=[[] for i in range(60)]
for i in range(n):
    x,y,u=xyu[i]
    # print(200000-x+y,u)
    cnt[200000-x+y].append(i)
# print()
for i in range(len(cnt)):
    ul=[-1]*2
    if len(cnt[i])==0:
        continue
    cnt[i].sort(lambda x: xyu[x][1])
    # print(cnt[i])
    for j in range(len(cnt[i])):
        x,y,u=xyu[cnt[i][j]]
        if u=="U":
            ul[0]=y
        elif u=="R":
            ul[1]=y
        elif u=="D":
            if ul[1]!=-1:
                ans=min(ans,(y-ul[1])*10)
        elif u=="L":
            if ul[0]!=1:
                ans=min(ans,(y-ul[0])*10)
        # print(urdl)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict


def input():
    return sys.stdin.readline().rstrip()


def main():
    N = int(input())
    UD = defaultdict(list)
    RL = defaultdict(list)
    RD = defaultdict(list)
    UL = defaultdict(list)
    LD = defaultdict(list)
    RU = defaultdict(list)
    U = []
    D = []
    R = []
    L = []

    for i in range(N):
        x, y, d = input().split()
        x = int(x)
        y = int(y)
        if d == "U":
            UD[x].append(y)
            UL[x - y].append(y)
            U.append((x, y))
        elif d == "D":
            D.append((x, y))
        elif d == "R":
            RL[y].append(x)
            RD[x - y].append(x)
            RU[x + y].append(x)
            R.append((x, y))
        elif d == "L":
            LD[x + y].append(x)
            L.append((x, y))
    ans = 10 ** 9
    if len(set(L))+len(set(D))+len(set(R))+len(set(U)) !=N:
        print(0)

    while L:
        x, y = L.pop()
        rx = RL[y]
        while rx:
            xxx = rx.pop()
            if xxx <= x:
                ans = min(ans, (x - xxx) / 0.2)

        ul = UL[x - y]
        while ul:
            yyy = ul.pop()
            if yyy <= y:
                ans = min(ans, (y - yyy) / 0.1)
    while D:
        x, y = D.pop()
        ud = UD[x]
        while ud:
            yyy = ud.pop()
            if y >= yyy:
                ans = min(ans, (y - yyy) / 0.2)

        rd = RD[x - y]
        while rd:
            xxx = rd.pop()
            if xxx <= x:
                ans = min(ans, (x - xxx) / 0.1)

        ld = LD[x + y]
        while ld:
            xxx = ld.pop()
            if xxx >= x:
                ans = min(ans, (xxx - x) / 0.1)

    while U:
        x, y = U.pop()
        ru = RU[x + y]
        while ru:
            xxx = ru.pop()
            if x >= xxx:
                ans = min(ans, (x - xxx) / 0.1)

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import copy
N = int(input())
XYUs = [list(map(str, input().split())) for _ in range(N)]

up_slopes = [[] for _ in range(400005)]
down_slopes = [[] for _ in range(400005)]
xs = [[] for _ in range(200005)]
ys = [[] for _ in range(200005)]



for XYU in XYUs:
    #y切片
    up_slopes[int(XYU[1])-int(XYU[0])+200000].append([int(XYU[0]),XYU[2]])
    down_slopes[int(XYU[1])+int(XYU[0])].append([int(XYU[0]),XYU[2]])
    xs[int(XYU[0])].append([int(XYU[1]),XYU[2]])
    ys[int(XYU[1])].append([int(XYU[0]),XYU[2]])
    
min_val = int(1e+100)
for up_slope in up_slopes:
    U_posi = -1
    R_posi = -1
    incidents = copy.deepcopy(up_slope)
    incidents = sorted(incidents)
    for incident in up_slope:
        if incident[1] == "U":
            U_posi = incident[0]
        elif incident[1] == "R":
            R_posi = incident[0]
        elif incident[1] == "D" and R_posi != -1:
            accident = incident[0]-R_posi
            if min_val > accident:
                min_val = accident
        elif incident[1] == "L" and U_posi != -1:
            accident = incident[0]-U_posi
            if min_val > accident*10:
                min_val = accident*10

for down_slope in down_slopes:
    D_posi = -1
    R_posi = -1
    incidents = copy.deepcopy(down_slope)
    incidents = sorted(incidents)
    for incident in incidents:
        if incident[1] == "D":
            D_posi = incident[0]
        elif incident[1] == "R":
            R_posi = incident[0]
        elif incident[1] == "U" and R_posi != -1:
            accident = incident[0]-R_posi
            if min_val > accident*10:
                min_val = accident*10
        elif incident[1] == "L" and D_posi != -1:
            accident = incident[0]-D_posi
            if min_val > accident:
                min_val = accident


for x in xs:
    U_posi = -1
    incidents = copy.deepcopy(x)
    incidents = sorted(incidents)
    for incident in incidents:
        if incident[1] == "U":
            U_posi = incident[0]
        elif incident[1] == "D" and U_posi!=-1:
            if min_val > 10*(incident[0]-U_posi)/2:
                min_val = 10*(incident[0]-U_posi)/2
            
for y in ys:
    R_posi = -1
    incidents = copy.deepcopy(y)
    incidents = sorted(incidents)
    for incident in incidents:
        if incident[1] == "R":
            R_posi = incident[0]
        elif incident[1] == "L" and R_posi!=-1:
            if min_val > 10*(incident[0]-R_posi)/2:
                min_val = 10*(incident[0]-R_posi)/2
if min_val < 3000000:
    print(int(min_val))
else:
    print("SAFE")

Submission status: Wrong Answer

Solution code:
#f
n=int(input())
count=0
xy=[]
ans=10**7
for i in range(n):
    xi,yi,ui=input().split()
    xi=int(xi)
    yi=int(yi)
    ansi=10**7
    ansii=10**7
    for j in range(count):
        disx=xy[j][0]-xi
        disy=xy[j][1]-yi
        if disx==0:
            if (ui=='U' and xy[j][2]=='D' and disy>0) or (ui=='D' and xy[j][2]=='U' and disy<0):
                ansi=abs(disy)/2
        elif disy==0:
            if (ui=='R' and xy[j][2]=='L' and disx>0) or (ui=='L' and xy[j][2]=='L' and disx<0):
                ansi=abs(disx)/2
        elif abs(disx)==abs(disy):
            if ui=='U' and disy>0:
                if xy[j][2]=='R' and disx<0:
                    ansi=abs(disx)
                elif xy[j][2]=='L' and disx>0:
                    ansi=abs(disx)
            elif ui=='R' and disx>0:
                if xy[j][2]=='U' and disy<0:
                    ansi=abs(disx)
                elif xy[j][2]=='D' and disy>0:
                    ansi=abs(disx)
            elif ui=='D' and disy<0:
                if xy[j][2]=='R' and disx<0:
                    ansi=abs(disx)
                elif xy[j][2]=='L' and disx<0:
                    ansi=abs(disx)
            elif ui=='L' and disx<0:
                if xy[j][2]=='U' and disy<0:
                    ansi=abs(disx)
                elif xy[j][2]=='D' and disy>0:
                    ansi=abs(disx)
        ansii=min(ansii,ansi)
    count+=1
    ans=min(ans,ansii)
    xy.append([xi,yi,ui])

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

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict


def input():
    return sys.stdin.readline().rstrip()


def main():
    N = int(input())
    UD = defaultdict(list)
    RL = defaultdict(list)
    RD = defaultdict(list)
    UL = defaultdict(list)
    LD = defaultdict(list)
    RU = defaultdict(list)
    U = []
    D = []
    R = []
    L = []

    for i in range(N):
        x, y, d = input().split()
        x = int(x)
        y = int(y)
        if d == "U":
            UD[x].append(y)
            UL[x - y].append(y)
            U.append((x, y))
        elif d == "D":
            D.append((x, y))
        elif d == "R":
            RL[y].append(x)
            RD[x - y].append(x)
            RU[x + y].append(x)
            R.append((x, y))
        elif d == "L":
            LD[x + y].append(x)
            L.append((x, y))
    ans = 10 ** 9
    if len(set(L))+len(set(D))+len(set(R))+len(set(L)) !=N:
        print(0)

    while L:
        x, y = L.pop()
        rx = RL[y]
        while rx:
            xxx = rx.pop()
            if xxx <= x:
                ans = min(ans, (x - xxx) / 0.2)

        ul = UL[x - y]
        while ul:
            yyy = ul.pop()
            if yyy <= y:
                ans = min(ans, (y - yyy) / 0.1)
    while D:
        x, y = D.pop()
        ud = UD[x]
        while ud:
            yyy = ud.pop()
            if y >= yyy:
                ans = min(ans, (y - yyy) / 0.2)

        rd = RD[x - y]
        while rd:
            xxx = rd.pop()
            if xxx <= x:
                ans = min(ans, (x - xxx) / 0.1)

        ld = LD[x + y]
        while ld:
            xxx = ld.pop()
            if xxx >= x:
                ans = min(ans, (xxx - x) / 0.1)

    while U:
        x, y = U.pop()
        ru = RU[x + y]
        while ru:
            xxx = ru.pop()
            if x >= xxx:
                ans = min(ans, (x - xxx) / 0.1)

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from operator import itemgetter
N = int(input())

PP = {
  "D" : [],
  "U" : [],
  "L" : [],
  "R" : [],
}

for i in range(N):
  x,y,d = input().split()
  x,y = int(x), int(y)
  PP[d].append((x,y,x+y, y-x))
  
#print(PP)
ans = 1e10
# DvsU
if PP["D"] and PP["U"]:
  PD = sorted(PP['D'])
  PU = sorted(PP['U'])
  j = 0
  for i in range(len(PD)):
    while j < len(PU)-1 and PD[i][0] > PU[j][0]:
      j += 1

    if PD[i][0] == PU[j][0]:
      if PD[i][1] >= PU[j][1]:
        ans = min(ans, abs(PD[i][1] - PU[j][1]) * 5)
  
# L vs R
if PP["L"] and PP["R"]:
  PL = sorted(PP["L"], key=itemgetter(1))
  PR = sorted(PP["R"], key=itemgetter(1))
  j = 0
  for i in range(len(PL)):
    while j < len(PR)-1 and PL[i][1] > PR[j][1]:
      j += 1

    if PL[i][1] == PR[j][1]:
      if PL[i][0] >= PR[j][0]:
         ans = min(ans, abs(PL[i][0] - PR[j][0]) * 5)

# D vs R
# y = x + k <-> y-x = k が同一の点は当たる可能性
if PP["D"] and PP["R"]:
  PD = sorted(PP['D'], key=itemgetter(3))
  PR = sorted(PP['R'], key=itemgetter(3))
  j = 0
  for i in range(len(PD)):
    while j < len(PR)-1 and PD[i][3] > PR[j][3]:
      j += 1
    if PD[i][3] == PR[j][3]:
      if PD[i][2] >= PR[j][2]:
         ans = min(ans, abs(PD[i][2] - PR[j][2]) * 5)

# R vs U
# y = -x + k <-> y+x = k が同一の点は当たる可能性
if PP["R"] and PP["U"]:
  PR = sorted(PP['R'], key=itemgetter(2))
  PU = sorted(PP['U'], key=itemgetter(2))
  j = 0
  for i in range(len(PR)):
    while j < len(PU)-1 and PR[i][2] > PU[j][2]:
      j += 1
    if PR[i][2] == PU[j][2]:
      if PR[i][3] >= PU[j][3]:
         ans = min(ans, abs(PR[i][3] - PU[j][3]) * 5)

# D vs R
# U vs L
# y = x + k <-> y-x = k が同一の点は当たる可能性
if PP["L"] and PP["U"]:
  PU = sorted(PP['U'], key=itemgetter(3))
  PL = sorted(PP['L'], key=itemgetter(3))
  j = 0
  for i in range(len(PU)):
    while j < len(PL)-1 and PU[i][3] > PL[j][3]:
      j += 1
    if PU[i][3] == PL[j][3]:
      if PU[i][2] <= PL[j][2]:
         ans = min(ans, abs(PU[i][2] - PL[j][2]) * 5)

# R vs U
# L vs D
# y = -x + k <-> y+x = k が同一の点は当たる可能性
if PP["D"] and PP["L"]:
  PL = sorted(PP['L'], key=itemgetter(2))
  PD = sorted(PP['D'], key=itemgetter(2))
  j = 0
  for i in range(len(PL)):
    while j < len(PD)-1 and PL[i][2] > PD[j][2]:
      j += 1
    if PL[i][2] == PD[j][2]:
      if PL[i][3] <= PD[j][3]:
         ans = min(ans, abs(PL[i][3] - PD[j][3]) * 5)

print(ans if ans < 1e10 else "SAFE")

Submission status: Wrong Answer

Solution code:
#! /usr/bin/env python3

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)


def get_unique_list(seq):
    seen = []
    return [x for x in seq if x not in seen and not seen.append(x)]


N = int(readline())
XYU = [readline().decode().split() for _ in range(N)]
XY = [[int(x), int(y)] for x, y, _ in XYU]
U = [u for _, _, u in XYU]

for i in range(1, 100000):
    for idx in range(N):
        if U[idx] == "U":
            XY[idx][1] += .5
        elif U[idx] == "D":
            XY[idx][1] -= .5
        elif U[idx] == "L":
            XY[idx][0] -= .5
        else:
            XY[idx][0] += .5
    if len(get_unique_list(XY)) != N:
        print(i * 5)
        sys.exit()

print('SAFE')