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

Solution code:
from collections import defaultdict
from bisect import bisect_left

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

dis = 10 ** 19 

# 正面衝突用
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])
    
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

# 右肩下がりの同一直線上から発進した機体の衝突用
cox = {"U":defaultdict(list),"D":defaultdict(list),"L":defaultdict(list),"R":defaultdict(list)}

for x, y, u in XYU:
  x = int(x)
  y = int(y)
  cox[u][x+y].append(x) 
    
for k1 in cox.keys():
  for k2 in cox[k1].keys():
    cox[k1][k2] = sorted(cox[k1][k2])
    
for k, v in cox["U"].items():
  if k in cox["R"]:
    for pos in v:
      if pos > cox["R"][k][0]:
        a = bisect_left(cox["R"][k], pos)
        dis = min(dis, cox["R"][k][a] - pos) * 10

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

# 右肩上がりの同一直線上から発進した機体の衝突用
dox = {"U":defaultdict(list),"D":defaultdict(list),"L":defaultdict(list),"R":defaultdict(list)}

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

for k, v in dox["D"].items():
  if k in dox["R"]:
    for pos in v:
      if pos > dox["R"][k][0]:  
        a = bisect_left(dox["R"][k], pos)
        dis = min(dis, dox["R"][k][a] - pos) * 10

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import itertools
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n = readInt()
xyu = [readChars() for i in range(n)]

class mydict:
	def __init__(self):
		self.d = {}
	def add(self,key,value):
		if key in self.d:
			self.d[key].append(value)
		else:
			self.d[key]=[value]
	def p(self):
		print("{")
		for key in self.d:
			print(key,self.d[key])
		print("}")
	def mysort(self):
		for i in self.d:
			self.d[i].sort()
	def getDict(self):
		return self.d;

ud = mydict()
rl = mydict()
for x,y,u in xyu:
	if u=="U" or u=="D":
		ud.add(int(x),[int(y),u])
	else:
		rl.add(int(y),[int(x),u])
ud.mysort()
rl.mysort()
#ud.p()
#rl.p()
ans = float("inf")

tar = ud.getDict()
for key in tar:
	s = ""
	be = "-1"
	bev = "-1"
	for v in tar[key]:
		if be=="U" and v[1]=="D":
			ans = min(ans,(int(v[0])-int(bev))*5)
		be = v[1]
		bev = v[0]
tar = rl.getDict()
for key in tar:
	s = ""
	be = "-1"
	bev = "-1"
	for v in tar[key]:
		if be=="R" and v[1]=="L":
			ans = min(ans,(int(v[0])-int(bev))*5)
			raise Exception
		be = v[1]
		bev = v[0]

xy = mydict()
for x,y,u in xyu:
	xy.add(int(x)+int(y),[int(x),u])
#xy.p()
xy.mysort()
d = xy.getDict()
for key in d:
	beu = "-1"
	bex = -1
	for arr in d[key]:
		if beu=="R" and arr[1]=="U":
			ans = min(ans,(arr[0]-bex)*10)
		if beu=="D" and arr[1]=="L":
			ans = min(ans,(arr[0]-bex)*10)
		beu = arr[1]
		bex = arr[0]
mxy = mydict()
for x,y,u in xyu:
	mxy.add(int(y)-int(x),[int(x),u])
mxy.mysort()
#mxy.p()
d = mxy.getDict()
for key in d:
	beu = "-1"
	bex = -1
	for arr in d[key]:
		if beu=="R" and arr[1]=="D":
			ans = min(ans,(arr[0]-bex)*10)
		if beu=="U" and arr[1]=="L":
			ans = min(ans,(arr[0]-bex)*10)
		beu = arr[1]
		bex = arr[0]

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import itertools
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n = readInt()
xyu = [readChars() for i in range(n)]

class mydict:
	def __init__(self):
		self.d = {}
	def add(self,key,value):
		if key in self.d:
			self.d[key].append(value)
		else:
			self.d[key]=[value]
	def p(self):
		print("{")
		for key in self.d:
			print(key,self.d[key])
		print("}")
	def mysort(self):
		for i in self.d:
			self.d[i].sort()
	def getDict(self):
		return self.d;

ud = mydict()
rl = mydict()
for x,y,u in xyu:
	if u=="U" or u=="D":
		ud.add(int(x),[int(y),u])
	else:
		rl.add(int(y),[int(x),u])
ud.mysort()
rl.mysort()
#ud.p()
#rl.p()
ans = float("inf")

tar = ud.getDict()
for key in tar:
	s = ""
	be = "-1"
	bev = "-1"
	for v in tar[key]:
		if be=="U" and v[1]=="D":
			ans = min(ans,(int(v[0])-int(bev))*5)
			raise Exception
		be = v[1]
		bev = v[0]
tar = rl.getDict()
for key in tar:
	s = ""
	be = "-1"
	bev = "-1"
	for v in tar[key]:
		if be=="R" and v[1]=="L":
			ans = min(ans,(int(v[0])-int(bev))*5)
		be = v[1]
		bev = v[0]

xy = mydict()
for x,y,u in xyu:
	xy.add(int(x)+int(y),[int(x),u])
#xy.p()
xy.mysort()
d = xy.getDict()
for key in d:
	beu = "-1"
	bex = -1
	for arr in d[key]:
		if beu=="R" and arr[1]=="U":
			ans = min(ans,(arr[0]-bex)*10)
		if beu=="D" and arr[1]=="L":
			ans = min(ans,(arr[0]-bex)*10)
		beu = arr[1]
		bex = arr[0]
mxy = mydict()
for x,y,u in xyu:
	mxy.add(int(y)-int(x),[int(x),u])
mxy.mysort()
#mxy.p()
d = mxy.getDict()
for key in d:
	beu = "-1"
	bex = -1
	for arr in d[key]:
		if beu=="R" and arr[1]=="D":
			ans = min(ans,(arr[0]-bex)*10)
		if beu=="U" and arr[1]=="L":
			ans = min(ans,(arr[0]-bex)*10)
		beu = arr[1]
		bex = arr[0]

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

Submission status: Runtime Error

Solution code:
N=int(input())
XYU=[tuple(input().split()) for _ in range(N)]
U=[]
R=[]
D=[]
L=[]
for x,y,u in XYU:
 x,y = int(x),int(y)
 if u=="U":
  U.append((x,y))
 elif u=="D":
  D.append((x,y))
 elif u=="L":
  L.append((x,y))
 else:
  R.append((x,y))
r=10**9
def z(A):
 global r
 A.sort()
 n=p=-10**9
 for k,c,a in A:
  if k!=n:
   if a==1:
    n=k
    p=c
   continue
  if a==1:
   p=c
   continue
  if (c-p)*5<ans:
   ans=(c-p)*5
z([(x,y,1) for x,y in U]+[(x,y,-1) for x,y in D])
z([(y,x,1) for x,y in R]+[(y,x,-1) for x,y in L])
z([(x+y,x-y,1) for x,y in R]+[(x+y,x-y,-1) for x,y in U])
z([(x+y,x-y,1) for x,y in D]+[(x+y,x-y,-1) for x,y in L])
z([(x-y,x+y,1) for x,y in U]+[(x-y,x+y,-1) for x,y in L])
z([(x-y,x+y,1) for x,y in R]+[(x-y,x+y,-1) for x,y in D])
print("SAFE" if r>=10**9 else r)

Submission status: Runtime Error

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


n = int(input())
Rp = []
Rm = []
Lp = []
Lm = []
Up = []
Um = []
Dp = []
Dm = []
U = []
D = []
R = []
L = []

for i in range(n):
    x,y,u = input().split()
    x,y = int(x), int(y)
    if u == "U":
        U.append([x,y])
        Up.append((x+y,x,y))
        Um.append((x-y,x,y))
    elif u == "D":
        D.append([x,y])
        Dp.append((x+y,x,y))
        Dm.append((x-y,x,y))
    elif u == "R":
        R.append([y,x])    
        Rp.append((x+y,x,y))
        Rm.append((x-y,x,y))
    else:
        L.append([y,x])
        Lp.append((x+y,x,y))
        Lm.append((x-y,x,y))

Rp.sort()
Rm.sort()
Up.sort()
Um.sort()
Lp.sort()
Lm.sort()
Dp.sort()
Dm.sort()
U.sort()
D.sort()
R.sort()
L.sort()
ans = float("INF")

def syaku(A,B):
    if A == [] or B == []:
        return float("INF")
    la = len(A)
    lb = len(B)
    count = float("INF")
    b = 0
    for i in range(la):
        xy,x,y = A[i]
        if i > 0 and xy == A[i-1][0]:
            if len(l) > 0:
                for nxy,nx,ny in l:
                    if ny >= y:
                        count = min(count, abs(x-nx)*10)
        else:
            if i < la-1 and A[i+1][0] == xy:
                l = []
                while b < lb and B[b][0] <= xy:
                    if B[b][0] == xy:
                        if B[b][2] >= y:
                            count = min(count,abs(x-B[b][1])*10)
                        l.append(B[b])
                    b += 1
            else:
                while b < lb and B[b][0] <= xy:
                    if B[b][0] == xy:
                        if B[b][2] >= y:
                            count = min(count,abs(x-B[b][1])*10)
                        
                    b += 1
    return count

def syaku2(A,B):
    if A == [] or B == []:
        return float("INF")
    la = len(A)
    lb = len(B)
    count = float("INF")
    b = 0
    for i in range(la):
        xy,x,y = A[i]
        if i > 0 and xy == A[i-1][0]:
            if len(l) > 0:
                for nxy,nx,ny in l:
                    if y >= ny:
                        count = min(count, abs(x-nx)*10)
        else:
            if i < la-1 and A[i+1][0] == xy:
                l = []
                while b < lb and B[b][0] <= xy:
                    if B[b][0] == xy:
                        if y >= B[b][2]:
                            count = min(count,abs(x-B[b][1])*10)
                        l.append(B[b])
                    b += 1
            else:
                while b < lb and B[b][0] <= xy:
                    if B[b][0] == xy:
                        if y >= B[b][2]:
                            count = min(count,abs(x-B[b][1])*10)
                        
                    b += 1
    return count

def syaku3(A,B):
    if A == [] or B == []:
        return float("INF")
    la = len(A)
    lb = len(B)
    count = float("INF")
    b = 0
    for i in range(la):
        x,y = A[i]
        if i > 0 and x == A[i-1][0]:
            if len(l) > 0:
                for nx,ny in l:
                    if y >= ny:
                        count = min(count, abs(y-ny)*5)
        else:
            if i < la-1 and A[i+1][1] == x:
                l = []
                while b < lb and B[b][0] <= x:
                    if B[b][0] == x:
                        if y >= B[b][1]:
                            count = min(count,abs(y-B[b][1])*5)
                        l.append(B[b])
                    b += 1
            else:
                while b < lb and B[b][0] <= x:
                    if B[b][0] == x:
                        if y >= B[b][1]:
                            count = min(count,abs(y-B[b][1])*5)
                    b += 1
    return count

ans = min(ans,syaku(Up,Rp))
ans = min(ans,syaku(Um,Lm))
ans = min(ans,syaku2(Dp,Lp))
ans = min(ans,syaku2(Dm,Rm))
ans = min(ans,syaku3(D,U))
ans = min(ans,syaku3(L,R))

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

Submission status: Runtime Error

Solution code:
N = int(input())

planes = {
  'U': [],
  'R': [],
  'D': [],
  'L': []
}

for _ in range(N):
  x, y, t = input().split()
  x, y = int(x), int(y)
  planes[t].append((x, y))
  
BIG = 10**18
  
def time(ps):
  sort(ps)
  ans = BIG
  for i in range(len(ps)-1):
    y1, x1, t1 = ps[i]
    y2, x2, t2 = ps[i+1]
    
    if y1 != y2:
      continue
    
    if t1 == 1 and t2 = -1:
      ans = min(ans, x2 - x1)
  return 5*ans


ud = [(x, y, 1) for x, y in planes['U']] + [(x, y, -1) for x, y in planes['D']]
lr = [(y, x, 1) for x, y in planes['R']] + [(y, x, -1) for x, y in planes['L']]

ur = [(x+y, y-x, 1) for x, y in planes['U']] + [(x+y, y-x, -1) for x, y in planes['R']]
ul = [(x-y, y+x, 1) for x, y in planes['U']] + [(x-y, y+x, -1) for x, y in planes['L']]
rd = [(x-y, y+x, 1) for x, y in planes['R']] + [(x-y, y+x, -1) for x, y in planes['D']]
ld = [(x+y, y-x, 1) for x, y in planes['L']] + [(x+y, y-x, -1) for x, y in planes['D']]

ans = min(time(ud), time(lr), time(ur), time(ul), time(rd), time(ld))
if ans >= BIG:
  print("SAFE")
else:
  print(ans)

Submission status: Runtime Error

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)


# 縦横でぶつかる
def solve(x, y, ans, d1="D", d2="L"):
    xy = x + y
    c = Counter(xy)

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

    if len(tateyoko) == 0:
        return ans

    for ty in tateyoko:
        down_x, down_y = x[np.where((xy == ty) & (u == d1))], y[np.where((xy == ty) & (u == d1))]
        left_x, left_y = x[np.where((xy == ty) & (u == d2))], y[np.where((xy == ty) & (u == d2))]
        for a, b in zip(down_x, down_y):
            for c, d in zip(left_x, left_y):
                if down_y > left_y and down_x < left_x:
                    ans = min(ans, abs((a - c) * 10))

    return ans


# 回転なし
ans = solve(x, y, ans, "D", "L")

# 90度回転
xy = np.rot90(np.vstack([x, y]))
ans = solve(xy[:, 0], xy[:, 1], ans, "L", "U")

# 更に90度回転
xy = np.rot90(xy)
ans = solve(xy[0, :], xy[1, :], ans, "U", "R")

# 更に90度回転
xy = np.rot90(xy)
ans = solve(xy[:, 0], xy[:, 1], ans, "R", "D")

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

Submission status: Runtime Error

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]

if len(tate) > 0:
    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]

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


# 縦横でぶつかる
def solve(x, y, ans, d1="D", d2="L"):
    xy = x + y
    c = Counter(xy)

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

    if len(tateyoko) == 0:
        return ans

    for ty in tateyoko:
        down_x, down_y = x[np.where((xy == ty) & (u == d1))], y[np.where((xy == ty) & (u == d1))]
        left_x, left_y = x[np.where((xy == ty) & (u == d2))], y[np.where((xy == ty) & (u == d2))]
        for a, b in zip(down_x, down_y):
            for c, d in zip(left_x, left_y):
                if down_y > left_y and down_x < left_x:
                    ans = min(ans, abs((a - c) * 10))

    return ans


# 回転なし
ans = solve(x, y, ans, "D", "L")

# 90度回転
xy = np.rot90(np.vstack([x, y]))
ans = solve(xy[:, 0], xy[:, 1], ans, "L", "U")

# 更に90度回転
xy = np.rot90(xy)
ans = solve(xy[0, :], xy[1, :], ans, "U", "R")

# 更に90度回転
xy = np.rot90(xy)
ans = solve(xy[:, 0], xy[:, 1], ans, "R", "D")

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

Submission status: Runtime Error

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 = x[np.where((x == t) & (u == "R"))]
    left = x[np.where((x == t) & (u == "L"))]
    for a in right:
        for b in left:
            if a < b:
                ans = min(ans, (b - a) * 5)


# 縦横でぶつかる
def solve(x, y, ans, d1="D", d2="L"):
    xy = x + y
    c = Counter(xy)

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

    if len(tateyoko) == 0:
        return ans

    for ty in tateyoko:
        down_x, down_y = x[np.where((xy == ty) & (u == d1))], y[np.where((xy == ty) & (u == d1))]
        left_x, left_y = x[np.where((xy == ty) & (u == d2))], y[np.where((xy == ty) & (u == d2))]
        for a, b in zip(down_x, down_y):
            for c, d in zip(left_x, left_y):
                if down_y > left_y and down_x < left_x:
                    ans = min(ans, abs((a - c) * 10))

    return ans


# 回転なし
ans = solve(x, y, ans, "D", "L")

# 90度回転
xy = np.rot90(np.vstack([x, y]))
ans = solve(xy[:, 0], xy[:, 1], ans, "R", "D")

# 更に90度回転
xy = np.rot90(xy)
ans = solve(xy[0, :], xy[1, :], ans, "U", "R")

# 更に90度回転
xy = np.rot90(xy)
ans = solve(xy[:, 0], xy[:, 1], ans, "L", "U")

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

Submission status: Runtime Error

Solution code:
import cv2
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 = x[np.where((x == t) & (u == "R"))]
    left = x[np.where((x == t) & (u == "L"))]
    for a in right:
        for b in left:
            if a < b:
                ans = min(ans, (b - a) * 5)


# 縦横でぶつかる
def solve(x, y, ans, d1="D", d2="L"):
    xy = x + y
    c = Counter(xy)

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

    if len(tateyoko) == 0:
        return ans

    for ty in tateyoko:
        down_x, down_y = x[np.where((xy == ty) & (u == d1))], y[np.where((xy == ty) & (u == d1))]
        left_x, left_y = x[np.where((xy == ty) & (u == d2))], y[np.where((xy == ty) & (u == d2))]
        for a, b in zip(down_x, down_y):
            for c, d in zip(left_x, left_y):
                if down_y > left_y and down_x < left_x:
                    ans = min(ans, abs((a - c) * 10))

    return ans


# 回転なし
ans = solve(x, y, ans, "D", "L")

# 90度回転
xy = cv2.rotate(np.vstack([x, y]), cv2.ROTATE_90_CLOCKWISE)
ans = solve(xy[:, 0], xy[:, 1], ans, "R", "D")

# 更に90度回転
xy = cv2.rotate(xy, cv2.ROTATE_90_CLOCKWISE)
ans = solve(xy[0, :], xy[1, :], ans, "U", "R")

# 更に90度回転
xy = cv2.rotate(xy, cv2.ROTATE_90_CLOCKWISE)
ans = solve(xy[:, 0], xy[:, 1], ans, "L", "U")

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

Submission status: Runtime Error

Solution code:
import cv2
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 = x[np.where((x == t) & (u == "R"))]
    left = x[np.where((x == t) & (u == "L"))]
    for a in right:
        for b in left:
            if a < b:
                ans = min(ans, (b - a) * 5)


# 縦横でぶつかる
def solve(x, y, ans, d1="D", d2="L"):
    xy = x + y
    c = Counter(xy)

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

    if len(tateyoko) == 0:
        return ans

    for ty in tateyoko:
        down_x, down_y = x[np.where((xy == ty) & (u == d1))], y[np.where((xy == ty) & (u == d1))]
        left_x, left_y = x[np.where((xy == ty) & (u == d2))], y[np.where((xy == ty) & (u == d2))]
        for a, b in zip(down_x, down_y):
            for c, d in zip(left_x, left_y):
                if down_y > left_y and down_x < left_x:
                    ans = min(ans, abs((a - c) * 10))

    return ans


# 回転なし
ans = solve(x, y, ans, "D", "L")

# 90度回転
xy = cv2.rotate(np.vstack([x, y]), cv2.ROTATE_90_CLOCKWISE)
ans = solve(xy[:, 0], xy[:, 1], ans, "R", "D")

# 更に90度回転
xy = cv2.rotate(xy, cv2.ROTATE_90_CLOCKWISE)
ans = solve(xy[0, :], xy[1, :], ans, "U", "R")

# 更に90度回転
xy = cv2.rotate(xy, cv2.ROTATE_90_CLOCKWISE)
ans = solve(xy[:, 0], xy[:, 1], ans, "L", "U")

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7



D_sum = defaultdict(list)
D_diff = defaultdict(list)
DX = defaultdict(list)
DY = defaultdict(list)
n = I()
L = []
ans = INF
for i in range(n):
    x, y, u = LS()
    x = int(x)
    y = int(y)
    D_sum[(x + y, u)] += [x]
    D_diff[(x - y, u)] += [x]
    DX[x, u] += [(x, y)]
    DY[y, u] += [(x, y)]
    L += [(x, y, u)]

for xi, yi, u in L:
    if u == "R" and D_diff[(xi - yi, "D")]:
        ll = sorted(D_diff[(xi - yi, "D")])
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "R" and D_sum[(xi + yi, "U")]:
        ll = sorted(D_sum[(xi + yi, "U")])
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "L" and D_diff[(xi - yi , "U")]:
        ll = sorted(D_diff[(xi - yi, "D")])
        ii = bisect_right(ll, xi)
        if ii:
            ret = min(ll[ii] - xi)
    if u == "L" and D_sum[(xi + yi, "D")]:
        ll = sorted(D_sum[(xi + yi, "D")])
        ii = bisect_right(ll, xi)
        if ii:
            ans = min(ans, xi - ll[ii - 1])
    if u == "R" and DY[yi, "L"]:
        ll = sorted(DY[(yi, "L")])
        ii = bisect_right(ll, (xi, 0))
        if ii < len(ll):
            ans = min(ans, (ll[ii][0] - xi) / 2)
    if u == "U" and DX[xi, "D"]:
        ll = sorted(DX[(xi, "D")], key=lambda z:z[1])
        ii = bisect_right(ll, (yi, 0))
        if ii < len(ll):
            ans = min(ans, abs(ll[ii][1] - yi) / 2)


"""
L1 = []
L2 = []
L3 = []
L4 = []
for xk, yk ,u in L:
    L1 += [(xk - yk)]
    L2 += [(- xk - yk)]
    L3 += [(xk + yk)]
    L4 += [(- xk + yk)]

print(L1)
print(L2)
print(L3)
print(L4)

"""

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

Submission status: Runtime Error

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7



D_sum = defaultdict(list)
D_diff = defaultdict(list)
DX = defaultdict(list)
DY = defaultdict(list)
n = I()
L = []
ans = INF
for i in range(n):
    x, y, u = LS()
    x = int(x)
    y = int(y)
    D_sum[(x + y, u)] += [x]
    D_diff[(x - y, u)] += [x]
    DX[x, u] += [(x, y)]
    DY[y, u] += [(x, y)]
    L += [(x, y, u)]

for xi, yi, u in L:
    if u == "R" and D_diff[(xi - yi, "D")]:
        ll = sorted(D_diff[(xi - yi, "D")])
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "R" and D_sum[(xi + yi, "U")]:
        ll = sorted(D_sum[(xi + yi, "U")])
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "L" and D_diff[(xi - yi , "U")]:
        ll = sorted(D_diff[(xi - yi, "D")])
        ii = bisect_right(ll, xi)
        if ii:
            ret = min(ll[ii] - xi)
    if u == "L" and D_sum[(xi + yi, "D")]:
        ll = sorted(D_sum[(xi + yi, "D")])
        ii = bisect_right(ll, xi)
        if ii:
            ans = min(ans, xi - ll[ii - 1])
    if u == "L" and DY[yi, "R"]:
        ll = sorted(DY[(yi, "R")])
        ii = bisect_right(ll, (xi, 0))
        if ii < len(ll):
            ans = min(ans, (ll[ii][0] - xi) / 2)
    if u == "U" and DX[xi, "D"]:
        ll = sorted(DX[(xi, "D")], key=lambda z:z[1])
        ii = bisect_right(ll, (yi, 0))
        if ii < len(ll):
            ans = min(ans, abs(ll[ii][1] - yi) / 2)


"""
L1 = []
L2 = []
L3 = []
L4 = []
for xk, yk ,u in L:
    L1 += [(xk - yk)]
    L2 += [(- xk - yk)]
    L3 += [(xk + yk)]
    L4 += [(- xk + yk)]

print(L1)
print(L2)
print(L3)
print(L4)

"""

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

Submission status: Runtime Error

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

N=int(input())

X1={}
X2={}

X={}
Y={}

for i in range(N):
    x,y,u=input().split()
    x=int(x)
    y=int(y)
    if x+y not in X1:
        X1[x+y]=[[x,u]]
    else:
        X1[x+y].append([x,u])
    if y-x not in X2:
        X2[y-x]=[[x,u]]
    else:
        X2[y-x].append([x,u])
    if x not in X:
        X[x]=[[y,u]]
    else:
        X[x].append([y,u])
    if y not in Y:
        Y[y]=[[x,u]]
    else:
        Y[y].append([x,u])


Dead=10**9


for k,v in X1.items():
    D=-1
    R=-1
    v.sort()
    #print(v)
    for a,u in v:
        if u=="D":
            D=a
        elif u=="R":
            R=a
        elif u=="L":
            if D>=0:
                Dead=min(Dead,(a-D)*10)
        elif u=="U":
            if R>=0:
                Dead=min(Dead,(a-R)*10)
for k,v in X2.items():
    U=-1
    R=-1
    v.sort()
    #print(v)
    for a,u in v:
        if u=="U":
            U=a
        elif u=="R":
            R=a
        elif u=="L":
            if U>=0:
                Dead=min(Dead,(a-U)*10)
        elif u=="D":
            if L>=0:
                Dead=min(Dead,(a-R)*10)
for k,v in X.items():
    U=-1
    v.sort()
    #print(v)
    for a,u in v:
        if u=="U":
            U=a
        elif u=="D":
            if U>=0:
                Dead=min(Dead,(a-U)*5)
for k,v in Y.items():
    R=-1
    v.sort()
    #print(v)
    for a,u in v:
        if u=="R":
            R=a
        elif u=="L":
            if R>=0:
                Dead=min(Dead,(a-R)*5)
if Dead==10**9:
    print("SAFE")
else:
    print(Dead)