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: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50

def calc(Asum, Bsum, A, B, ans, ope = 1):
    if not len(A) or not len(B):
        return ans

    #print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        while True:
            try:
                val = B_[bi]
            except:
                break
            #print(bi, val, asum)
            if val == asum:
                bi2 = Bsum[bi][1]
                x1, y1 = A[ai]
                x2, y2 = B[bi2]
                time = (x2 - x1) * ope
                if time <= 0:
                    bi += 1
                    continue
                ans = min(ans, time*10)
            else:
                break
            bi += 1
    return ans

def calc_line(Asum, Bsum, A, B, ans):
    if not len(A) or not len(B):
        return ans

    # print(Asum, Bsum)
    B_ = [val for val, _ in Bsum]
    for asum, ai in Asum:
        bi = bisect.bisect_left(B_, asum)
        while True:
            try:
                val = B_[bi]
            except:
                break
            if val == asum:
                bi2 = Bsum[bi][1]
                x1, y1 = A[ai]
                x2, y2 = B[bi2]
                if x1 == x2:
                    time = y2 - y1
                else:
                    time = x2 - x1
                if time <= 0:
                    bi += 1
                    continue
                ans = min(ans, time*5)
            else:
                break
            bi += 1
    return ans

def run():
    U, D, R, L = [],[],[],[]
    N = int(sysread())
    for i in range(N):
        x,y,u = input().split()
        #print(x, y, u)
        x,y = int(x), int(y)
        if u == 'U':
            U.append((x,y))
        elif u == 'D':
            D.append((x,y))
        elif u == 'R':
            R.append((x,y))
        elif u == 'L':
            L.append((x,y))

    #print(U, D, R, L)
    ans = INF
    # U vs R
    Usum = sorted([(x+y, i) for i, (x,y) in enumerate(U)])
    Rsum = sorted([(x+y, i) for i, (x,y) in enumerate(R)])
    ans = calc(Usum, Rsum, U, R, ans, ope=-1)

    # D vs L
    Dsum = sorted([(x + y, i) for i, (x, y) in enumerate(D)])
    Lsum = sorted([(x + y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Dsum, Lsum, D, L, ans, ope=1)

    # U vs L
    Usub = sorted([(x - y, i) for i, (x, y) in enumerate(U)])
    Lsub = sorted([(x - y, i) for i, (x, y) in enumerate(L)])
    ans = calc(Usub, Lsub, U, L, ans, ope=1)

    # D vs R
    Dsub = sorted([(x - y, i) for i, (x, y) in enumerate(D)])
    Rsub = sorted([(x - y, i) for i, (x, y) in enumerate(R)])
    ans = calc(Dsub, Rsub, D, R, ans, ope=-1)

    # U vs D
    UU = sorted([(x, i) for i, (x,y) in enumerate(U)])
    DD = sorted([(x, i) for i, (x, y) in enumerate(D)])
    ans = calc_line(UU, DD, U, D, ans)

    # R vs L
    RR = sorted([(y, i) for i, (x, y) in enumerate(R)])
    LL = sorted([(y, i) for i, (x, y) in enumerate(L)])
    ans = calc_line(RR, LL, R, L, ans)

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



if __name__ == "__main__":
    run()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

sideLen = 200000
def solve_reverse():
    tmpAns = sideLen * 100
    values = []
    for num in range(N):
        if not (U[num] == "R" or U[num] == "L"):
            continue
        else:
            values.append([Y[num], X[num], U[num]])
    values.sort()
    # print(values)
    for num in range(len(values)-1):
        if not (values[num][2] == "R" and values[num + 1][2] == "L") or values[num][0] != values[num+1][0]:
            continue
        else:
            tmpAns = min(tmpAns, values[num + 1][1] - values[num][1])
            #print(1, tmpAns, values[num+1], values[num])
    return tmpAns * 5


def solve_90degree():
    tmpAns = sideLen * 100
    values = []
    for num in range(N):
        if not (U[num] == "R" or U[num] == "U"):
            continue
        else:
            values.append([X[num]+Y[num], X[num], U[num]])
    values.sort()
    for num in range(len(values)-1):
        if not (values[num][2] == "R" and values[num + 1][2] == "U") or values[num][0] != values[num+1][0]:
            continue
        else:
            tmpAns = min(tmpAns, values[num + 1][1] - values[num][1])
            #print(2, tmpAns, values[num+1], values[num])
    return tmpAns * 10


N = int(input())
X = deque()
Y = deque()
U = deque()
def rotate():
    degLis = ["U", "R", "D", "L", "L", "U", "R", "D"]
    for num in range(N):
        tmpX = sideLen - Y[num]
        Y[num] = X[num]
        X[num] = tmpX
        U[num] = degLis[degLis.index(U[num])+4]

for _ in range(N):
    x, y, u = map(str, input().split())
    X.append(int(x))
    Y.append(int(y))
    U.append(u)
ans = sideLen * 100

for i in range(4):
    if i >= 2:
        revNum = solve_reverse()
        ans = min(revNum, ans)
    degNum = solve_90degree()
    ans = min(degNum, ans)
    rotate()

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** -10

N = INT()
XYD = []
for _ in range(N):
    x, y, d = input().split()
    x = int(x)
    y = int(y)
    if d == 'U':
        XYD.append([x, y, 0])
    elif d == 'R':
        XYD.append([x, y, 1])
    elif d == 'D':
        XYD.append([x, y, 2])
    else:
        XYD.append([x, y, 3])

DX = defaultdict(list)
DY = defaultdict(list)
for x, y, d in XYD:
    if d == 0:
        DX[x].append((y, 0))
    elif d == 1:
        DY[y].append((x, 0))
    elif d == 2:
        DX[x].append((y, 1))
    else:
        DY[y].append((x, 1))

ans = INF
for li in DX.values():
    li.sort()
    mxl = -1
    for y, d in li:
        if d == 0:
            mxl = y
        elif d == 1 and mxl != -1:
            ans = min(ans, (y-mxl) * 10 // 2)
for li in DY.values():
    li.sort()
    mxl = -1
    for x, d in li:
        if d == 0:
            mxl = x
        elif d == 1 and mxl != -1:
            ans = min(ans, (x-mxl) * 10 // 2)

for d1 in range(4):
    d2 = (d1+1) % 4
    D = defaultdict(list)
    for x, y, d in XYD:
        if d == d1:
            D[x+y].append((x, y))
    for x, y, d in XYD:
        if d == d2:
            for x2, y2 in D[x+y]:
                if y > y2:
                    ans = min(ans, (abs(x-x2)+abs(y-y2)) * 10 // 2)
    if d1 % 2 == 0:
        for i in range(N):
            XYD[i][0] *= -1
    else:
        for i in range(N):
            XYD[i][1] *= -1
if ans == INF:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
I,*U=N,*D,=9**9,
P,*L='x+y,',
M,*R='x-y,',
for t in[*open(0)][1:]:*z,u=t.split();exec(u+'+=[*map(int,z)],')
for*A,S in(D,U,'x,y,'),(L,R,'y,x,'),(U,R,P+M),(L,D,P+M),(L,U,M+P),(D,R,M+P):
  n=I
  for x,y,r in eval('sorted((%sQ)for Q,P in enumerate(A)for x,y in P)'%S):exec(r*'n,p=x,y'or'N=min(N,y-p)'*(x==n))
print(N%I*5or'SAFE')

Submission status: Time Limit Exceeded

Solution code:
import collections
import itertools
N = int(input())
#cnt[UDLR][x y x+y x-y][value]=set()
cnt = [[collections.defaultdict(set) for _ in range(4)] for _ in range(4)]
for _ in range(N):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    p = y + x
    q = y - x
    i = 'UDLR'.index(u)
    cnt[i][0][x].add(y)
    cnt[i][1][y].add(x)
    cnt[i][2][p].add(q)
    cnt[i][3][q].add(p)

INF = float('inf')


def calc(up, down):
    cand = up.keys() & down.keys()
    ans = min(
        [INF] +
        [v2 - v1 for c in cand for v1 in up[c] for v2 in down[c] if v2 >= v1])
    return ans


#U(0)とD(1)がx(0)が一緒:d-u(>=0)の最小値
#R(3)とL(2)がy(1)が一緒:l-r(>=0)の最小値
#U(0)とR(3)がx+y(2)が一緒:(y-x)のr-u(>=0)の最小値
#L(2)とD(1)がx+y(2)が一緒:(y-x)のd-l(>=0)の最小値
#U(0)とL(2)がy-x(3)が一緒:(y+x)のl-u(>=0)の最小値
#R(3)とD(1)がy-x(3)が一緒:(y+x)のd-r(>=0)の最小値
ans = min(
    calc(cnt[0][0], cnt[1][0]), calc(cnt[3][1], cnt[2][1]),
    calc(cnt[0][2], cnt[3][2]), calc(cnt[2][2], cnt[1][2]),
    calc(cnt[0][3], cnt[2][3]), calc(cnt[3][3], cnt[1][3]))

print('SAFE' if ans == INF else ans * 5)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from bisect import bisect
from collections import defaultdict

XU = [[] for i in range(2*10**5+1)]
XD = [[] for i in range(2*10**5+1)]
YL = [[] for i in range(2*10**5+1)]
YR = [[] for i in range(2*10**5+1)]
xu = []; xd = []
c1 = 1; c2 = 1; c3 = 1; c4 = 1
dyls = defaultdict(int)
dyrs = defaultdict(int)
dylsa = defaultdict(int)
dyrsa = defaultdict(int)
yls = [[] for i in range(2*10**5+1)]
yrs = [[] for i in range(2*10**5+1)]
ylsa = [[] for i in range(2*10**5+1)]
yrsa = [[] for i in range(2*10**5+1)]

n = int(input())
ans = float('inf')

for i in range(n):
  x,y,u = input().split()
  x = int(x); y = int(y)
  if u == 'U':
    XU[x].append(y)
    xu.append((x,y))
  if u == 'D':
    XD[x].append(y)
    xd.append((x,y))
  if u == 'L':
    YL[y].append(x)
    if dyls[x+y] == 0:
      dyls[x+y] = c1
      c1 += 1
    if dylsa[x-y] == 0:
      dylsa[x-y] = c2
      c2 += 1
    yls[dyls[x+y]].append(x)
    ylsa[dylsa[x-y]].append(x)
  if u == 'R':
    YR[y].append(x)
    if dyrs[x+y] == 0:
      dyrs[x+y] = c3
      c3 += 1
    if dyrsa[x-y] == 0:
      dyrsa[x-y] = c4
      c4 += 1
    yrs[dyrs[x+y]].append(x)
    yrsa[dyrsa[x-y]].append(x)

for x,y in xu: #上
  if dyrs[x+y] != 0:
    yrs[dyrs[x+y]].sort()
    ind = bisect(yrs[dyrs[x+y]],x)
    if ind > 0:
      ans = min(ans,abs(x-yrs[dyrs[x+y]][ind-1])*10)
  if dylsa[x-y] != 0:
    ylsa[dylsa[x-y]].append(10**9)
    ylsa[dylsa[x-y]].sort()
    ind = bisect(ylsa[dylsa[x-y]],x)
    if ylsa[dylsa[x-y]][ind] != 10**9:
      ans = min(ans,abs(ylsa[dylsa[x-y]][ind]-x)*10)
  
for x,y in xd: #下
  if dyls[x+y] != 0:
    yls[dyls[x+y]].append(10**9)
    yls[dyls[x+y]].sort()
    ind = bisect(yls[dyls[x+y]],x)
    if yls[dyls[x+y]][ind] != 10**9:
      ans = min(ans,abs(x-yls[dyls[x+y]][ind])*10)
  if dyrsa[x-y] != []:
    yrsa[dyrsa[x-y]].sort()
    ind = bisect(yrsa[dyrsa[x-y]],x)
    if ind != 0:
      ans = min(ans,abs(yrsa[dyrsa[x-y]][ind-1]-x)*10)

for i in range(2*10**5+1):
  if XU[i] != [] and XD[i] != []:
    XU[i].append(10**9)
    XU[i].sort()
    for j in XD[i]:
      ind = bisect(XU[i],j)
      if ind > 0:
        chk = min(abs(XU[i][ind]-j),abs(XU[i][ind-1]-j))
        ans = min(ans,5*chk)
  if YL[i] != [] and YR[i] != []:
    YR[i].append(10**9)
    YR[i].sort()
    for j in YL[i]:
      ind = bisect(YR[i],j)
      if ind > 0:
        chk = min(abs(YR[i][ind]-j),abs(YR[i][ind-1]-j))
        ans = min(ans,5*chk)
      
if ans == float('inf'):
  print('SAFE')
else:
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip('\r\n')

from collections import defaultdict

N = int(input())

S = 'RULD'

class Plane:
	__slots__ = ('x', 'y', 'd')

	def __init__(s, x, y, d):
		s.x, s.y, s.d = int(x), int(y), d

	def __lt__(s, o):
		return s.x < o.x

	def rotate(s):
		s.x, s.y = -s.y, s.x
		s.d = S[(S.index(s.d)+1)%4]


P = [Plane(*input().split()) for _ in range(N)]

INF = 10 ** 18
best = INF
MAXC = 400000

for trial in range(4):
	P.sort()

	rdu, rdd, ry = ([INF] * (2*MAXC+1) for _ in range(3))

	for p in P:
		if p.d == 'R':
			ry[p.y+MAXC] = p.x
			rdu[p.y-p.x+MAXC] = p.x
			rdd[p.y+p.x+MAXC] = p.x
		elif p.d == 'L':
			ty = p.y + MAXC
			if ry[ty] != INF:
				best = min(best, (p.x - ry[ty]) * 5)
		elif p.d == 'U':
			ty = p.x + p.y + MAXC
			if rdd[ty] != INF:
				best = min(best, (p.x - rdd[ty]) * 10)
		elif p.d == 'D':
			ty = p.y - p.x + MAXC
			if rdu[ty] != INF:
				best = min(best, (p.x - rdu[ty]) * 10)

	if trial != 3:
		for p in P: p.rotate()

print('SAFE' if best == INF else best)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip('\r\n')

from collections import defaultdict

N = int(input())

S = 'RULD'

class Plane:
	__slots__ = ('x', 'y', 'd')

	def __init__(s, x, y, d):
		s.x, s.y, s.d = int(x), int(y), d

	def __lt__(s, o):
		return s.x < o.x

	def rotate(s):
		s.x, s.y = -s.y, s.x
		s.d = S[(S.index(s.d)+1)%4]


P = [Plane(*input().split()) for _ in range(N)]

INF = 10 ** 18
best = INF
for trial in range(4):
	P.sort()

	rdu, rdd, ry = (defaultdict(lambda: -INF) for _ in range(3))

	for p in P:
		if p.d == 'R':
			ry[p.y] = p.x
			rdu[p.y-p.x] = p.x
			rdd[p.y+p.x] = p.x
		elif p.d == 'L':
			if p.y in ry:
				best = min(best, (p.x - ry[p.y]) * 5)
		elif p.d == 'U':
			ty = p.x + p.y
			if ty in rdd:
				best = min(best, (p.x - rdd[ty]) * 10)
		elif p.d == 'D':
			ty = p.y - p.x
			if ty in rdu:
				best = min(best, (p.x - rdu[ty]) * 10)

	if trial != 3:
		for p in P: p.rotate()

print('SAFE' if best == INF else best)

Submission status: Time Limit Exceeded

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

n = int(input())
Rp = {}
Lp = {}
Rm = {}
Lm = {}
U = []
R = []
L = []
D = []

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

ans = float("INF")

for x,y in U:
    if x+y in Rp:
        for nx,ny in Rp[x+y]:
            if ny >= y:
                ans = min(ans,abs(ny-y)*10)
    if x-y in Lm:
        for nx,ny in Lm[x-y]:
            if ny >= y:
                ans = min(ans,abs(ny-y)*10)
for x,y in D:
    if x+y in Lp:
        for nx,ny in Lp[x+y]:
            if y >= ny:
                ans = min(ans,abs(ny-y)*10)
    if x-y in Rm:
        for nx,ny in Rm[x-y]:
            if y >= ny:
                ans = min(ans,abs(ny-y)*10)

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):
        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:
            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
    return count


D.sort()
U.sort()
L.sort()
R.sort()
ans = min(ans,syaku(D,U))
ans = min(ans,syaku(L,R))

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

Submission status: Time Limit Exceeded

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

n = int(input())
Rp = []
Lp = []
Up = []
Dp = []


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

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:
            l = []
            while b < lb and B[b][0] <= xy:
                if B[b][0] == xy:
                    if B[b][3] >= y:
                        count = min(count,abs(x-B[b][2])*10)
                    l.append(B[b])
                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:
            l = []
            while b < lb and B[b][0] <= xy:
                if B[b][0] == xy:
                    if y >= B[b][3]:
                        count = min(count,abs(x-B[b][2])*10)
                    l.append(B[b])
                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][2]:
            if len(l) > 0:
                for _,_,nx,ny in l:
                    if y >= ny:
                        count = min(count, abs(y-ny)*5)
        else:
            l = []
            while b < lb and B[b][2] <= x:
                if B[b][2] == x:
                    if y >= B[b][3]:
                        count = min(count,abs(y-B[b][3])*5)
                    l.append(B[b])
                b += 1
    return count

def syaku4(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][1]:
            if len(l) > 0:
                for _,nxy,nx,ny in l:
                    if ny >= y:
                        count = min(count, abs(x-nx)*10)
        else:
            l = []
            while b < lb and B[b][1] <= xy:
                if B[b][1] == xy:
                    if B[b][3] >= y:
                        count = min(count,abs(x-B[b][2])*10)
                    l.append(B[b])
                b += 1
    return count

def syaku5(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][1]:
            if len(l) > 0:
                for _,nxy,nx,ny in l:
                    if y >= ny:
                        count = min(count, abs(x-nx)*10)
        else:
            l = []
            while b < lb and B[b][1] <= xy:
                if B[b][1] == xy:
                    if y >= B[b][3]:
                        count = min(count,abs(x-B[b][2])*10)
                    l.append(B[b])
                b += 1
    return count

def syaku6(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 y == A[i-1][3]:
            if len(l) > 0:
                for _,_,nx,ny in l:
                    if x >= nx:
                        count = min(count, abs(x-nx)*5)
        else:
            l = []
            while b < lb and B[b][3] <= y:
                if B[b][3] == y:
                    if x >= B[b][2]:
                        count = min(count,abs(x-B[b][2])*5)
                    l.append(B[b])
                b += 1
    return count
ans = float("INF")
Rp.sort()
Up.sort()
Lp.sort()
Dp.sort()
ans = min(ans,syaku(Up,Rp))
ans = min(ans,syaku2(Dp,Lp))
Rp.sort(key = lambda x: x[1])
Up.sort(key = lambda x: x[1])
Lp.sort(key = lambda x: x[1])
Dp.sort(key = lambda x: x[1])
ans = min(ans,syaku4(Up,Lp))
ans = min(ans,syaku5(Dp,Rp))
Rp.sort(key = lambda x: x[3])
Up.sort(key = lambda x: x[2])
Lp.sort(key = lambda x: x[3])
Dp.sort(key = lambda x: x[2])
ans = min(ans,syaku3(Dp,Up))
ans = min(ans,syaku6(Lp,Rp))

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

Submission status: Time Limit Exceeded

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
U = []
D = []
R = []
L = []
U_ = defaultdict(list)
U__ = defaultdict(list)
D_ = defaultdict(list)
D__ = defaultdict(list)
Ux = defaultdict(list)
Dx = defaultdict(list)
Ry = defaultdict(list)
Ly = defaultdict(list)
for _ in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == 'U':
        Ux[x].append(y)
        U_[x+y].append((x, y))
        U__[x-y].append((x, y))
        U.append((x, y))
    elif u == 'D':
        Dx[x].append(y)
        D_[x+y].append((x, y))
        D__[x-y].append((x, y))
        D.append((x, y))
    elif u == 'R':
        Ry[y].append(x)
        R.append((x, y))
    else:
        Ly[y].append(x)
        L.append((x, y))

for i in Ux.values():
    i.sort()
for i in Ry.values():
    i.sort()

ans = inf
for i, j in Dx.items():
    for k in j:
        r = br(Ux[i], k)
        if r != 0:
            ans = min(ans, int((k - Ux[i][r-1]) / 2 * 10))
for i, j in Ly.items():
    for k in j:
        r = br(Ry[i], k)
        if r != 0:
            ans = min(ans, int((k - Ry[i][r-1]) / 2 * 10))
for (i, j) in R:
    for (k, l) in D__[i-j]:
        if l - j >= 0:
            ans = min(ans, (l - j) * 10)

for (i, j) in R:
    for (k, l) in U_[i+j]:
        if j - l >= 0:
            ans = min(ans, (j - l) * 10)

for (i, j) in L:
    for (k, l) in U__[i-j]:
        if i - k >= 0:
            ans = min(ans, (i - k) * 10)

for (i, j) in L:
    for (k, l) in D_[i+j]:
        if i - k >= 0:
            ans = min(ans, (i - k) * 10)

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

Submission status: Time Limit Exceeded

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

def main():
    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:
                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
        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:
                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
        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:
                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
        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)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
U, D, R, L = [], [], [], []
Ux = defaultdict(list)
Dx = defaultdict(list)
Ry = defaultdict(list)
Ly = defaultdict(list)
for _ in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == 'U':
        Ux[x].append(y)
        U.append((x, y))
    elif u == 'D':
        Dx[x].append(y)
        D.append((x, y))
    elif u == 'R':
        Ry[y].append(x)
        R.append((x, y))
    else:
        Ly[y].append(x)
        L.append((x, y))

for i in Ux.values():
    i.sort()
for i in Ry.values():
    i.sort()

ans = inf
for i, j in Dx.items():
    for k in j:
        r = br(Ux[i], k)
        if r != 0:
            ans = min(ans, int((k - Ux[i][r-1]) / 2 * 10))
for i, j in Ly.items():
    for k in j:
        r = br(Ry[i], k)
        if r != 0:
            ans = min(ans, int((k - Ry[i][r-1]) / 2 * 10))
for (i, j) in R:
    for (k, l) in D:
        if l - j == k - i and l - j >= 0:
            ans = min(ans, (l - j) * 10)

for (i, j) in R:
    for (k, l) in U:
        if j - l == k - i and j - l >= 0:
            ans = min(ans, (j - l) * 10)

for (i, j) in L:
    for (k, l) in U:
        if i - k == j - l and i - k >= 0:
            ans = min(ans, (i - k) * 10)

for (i, j) in L:
    for (k, l) in D:
        if i - k == l - j and i - k >= 0:
            ans = min(ans, (i - k) * 10)

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