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:
from collections import defaultdict
from bisect import *
def solve():
  ans = float('inf')
  N = int(input())
  L_y = defaultdict(lambda: [-float('inf'),float('inf')])
  R_y = defaultdict(lambda: [-float('inf'),float('inf')])
  U_x = defaultdict(lambda: [-float('inf'),float('inf')])
  D_x = defaultdict(lambda: [-float('inf'),float('inf')])
  R_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  R_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  L_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  L_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  U_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  U_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  D_xpy = defaultdict(lambda: [-float('inf'),float('inf')])
  D_y_x = defaultdict(lambda: [-float('inf'),float('inf')])
  for i in range(N):
    x,y,u = input().split()
    x,y = int(x),int(y)
    if u=='D':
      insort(D_x[x],y)
      insort(D_xpy[x+y],x)
      insort(D_y_x[y-x],x)
    if u=='U':
      insort(U_x[x],y)
      insort(U_xpy[x+y],x)
      insort(U_y_x[y-x],x)
    if u=='L':
      insort(L_y[y],x)
      insort(L_xpy[x+y],x)
      insort(L_y_x[y-x],x)
    if u=='R':
      insort(R_y[y],x)
      insort(R_xpy[x+y],x)
      insort(R_y_x[y-x],x)
  for k,v in R_y.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(L_y[k],zahyou)
      dis = L_y[k][ind]-zahyou
      ans = min(ans,dis)
  for k,v in D_x.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(U_x[k],zahyou)
      dis = zahyou-U_x[k][ind-1]
      ans = min(ans,dis)
  for k,v in L_y_x.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(U_y_x[k],zahyou)
      dis = zahyou-U_y_x[k][ind-1]
      dis *= 2
      ans = min(ans,dis)
  for k,v in R_xpy.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(U_xpy[k],zahyou)
      dis = U_xpy[k][ind]-zahyou
      dis *= 2
      ans = min(ans,dis)
  for k,v in L_xpy.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(D_xpy[k],zahyou)
      dis = zahyou-D_xpy[k][ind-1]
      dis *= 2
      ans = min(ans,dis)
  for k,v in R_y_x.items():
    for zahyou in v[1:-1]:
      ind = bisect_right(D_y_x[k],zahyou)
      dis = D_y_x[k][ind]-zahyou
      dis *= 2
      ans = min(ans,dis)
  ans *= 5
  return ans if ans<float('inf') else 'SAFE'
print(solve())

Submission status: Time Limit Exceeded

Solution code:
n= int(input())

mi=[[[],[],[],[],0] for i in range(400001)]
pl=[[[],[],[],[],0] for i in range(400001)]
va=[[[],[],[],[],0] for i in range(200001)]
ho=[[[],[],[],[],0] for i in range(200001)]
ans = 100000000
for i in range(n):
    x,y,u = map(str,input().split())
    x = int(x)
    y = int(y)
    if u== 'U':
        u=0
    elif u== 'R':
        u=1
    elif u== 'D':
        u=2
    else:
        u=3
    print(mi)
    mi[x+y][u].append([x,y])
    mi[x+y][4]+=1
    pl[x-y+200000][u].append([x,y])
    pl[x-y+200000][4] += 1
    va[x][u].append([x,y])
    va[x][4] += 1
    ho[y][u].append([x,y])
    ho[y][4]+=1
for i in range (400001):
    if mi[i][4]>=2:
        if len(mi[i][0])>=1 and len(mi[i][1])>=1:
            for j in range(len(mi[i][0])):
                for k in range(len(mi[i][1])):
                    if mi[i][1][1] >= mi[i][0][1]:
                        ans = min(ans,(mi[i][1][1] - mi[i][0][1])*0.1)
        if len(mi[i][2])>=1 and len(mi[i][3])>=1:
            for j in range(len(mi[i][2])):
                for k in range(len(mi[i][3])):
                    if mi[i][2][1] >= mi[i][3][1]:
                        ans = min(ans,(mi[i][2][1] - mi[i][3][1])*0.1)
    if pl[i][4]>=2:
        if len(pl[i][0])>=1 and len(pl[i][3])>=1:
            for j in range(len(pl[i][0])):
                for k in range(len(pl[i][3])):
                    if pl[i][3][1] >= pl[i][0][1]:
                        ans = min(ans,(pl[i][3][1] - pl[i][0][1])*0.1)
        if len(pl[i][2])>=1 and len(pl[i][1])>=1:
            for j in range(len(pl[i][2])):
                for k in range(len(pl[i][1])):
                    if pl[i][2][1] >= pl[i][1][1]:
                        ans = min(ans,(pl[i][2][1] - pl[i][1][1])*0.1)
for i in range(200001):
    if va[i][4] >= 2:
        if len(va[i][0])>=1 and len(va[i][2])>=1:
            for j in range(len(va[i][0])):
                for k in range(len(va[i][2])):
                    if va[i][2][1] >= va[i][0][1]:
                        ans = min(ans,(va[i][2][1] - va[i][0][1])*0.1/2)
    if ho[i][4] >= 2:
        if len(ho[i][1])>=1 and len(ho[i][3])>=1:
            for j in range(len(ho[i][1])):
                for k in range(len(ho[i][3])):
                    if ho[i][3][0] >= ho[i][1][0]:
                        ans = min(ans,(ho[i][2][1] - ho[i][0][1])*0.1/2)
if ans>=10000000:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N = int(input())
    U = []
    D = []
    R = []
    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=='D':
            D.append([X,Y])
        elif u=='R':
            R.append([X,Y])
        else:
            L.append([X,Y])

    ans = INF
    for x1, y1 in U:
        for x2, y2 in R:
            if x1-x2>0 and x1-x2==y2-y1:
                ans = min(ans, x1-x2)
    for x1,y1 in D:
        for x2, y2 in U:
            if x1==x2 and y1-y2>0:
                ans = min(ans, (y1-y2)/2)

        for  x2, y2 in R:
            if x1-x2>0 and x1-x2==y1-y2:
                ans = min(ans, x1-x2)
    for x1, y1 in L:
        for x2, y2 in R:
            if y1==y2 and x1-x2>0:
                ans = min(ans, (x1-x2)/2)
        for x2,y2 in U:
            if x1-x2==y1-y2 and x1-x2>0:
                ans = min(ans, x1-x2)
        for x2, y2 in D:
            if x1-x2==y2-y1 and x1-x2>0:
                ans = min(ans, x1-x2)
    if ans==INF:
        print('SAFE')
    else:
        print(int(ans*10))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
n = int(input())
d = defaultdict(list)
for i in range(n):
    x, y , u = input().split()
    d[u].append((int(x), int(y)))
# check if 'u' and 'd' would collide

ans = 2*10**6 + 1
for plane1 in d['U']:
    for plane2 in d['D']:
        if plane1[0] == plane2[0] and plane1[1] < plane2[1]:
            ans = min(ans, (plane2[1] - plane1[1])*5)

# check if 'l' and 'r' would collide
for plane1 in d['R']:
    for plane2 in d['L']:
        if plane1[1] == plane2[1] and plane1[0] < plane2[0]:
            ans = min(ans, (plane2[0] - plane1[0])*5)

# check if 'u' and 'l' or 'r' would collide
for plane1 in d['U']:
    for plane2 in d['L']:
        if abs(plane2[0] - plane1[0]) == abs(plane2[1] - plane1[1]) and plane2[0] > plane1[0] and plane2[1] > plane1[1]:
            ans = min(ans, abs(plane2[0] - plane1[0]) * 10)
    for plane2 in d['R']:
        if abs(plane2[0] - plane1[0]) == abs(plane2[1] - plane1[1]) and plane2[0] < plane1[0] and plane2[1] > plane1[1]:
            ans = min(ans, abs(plane2[0] - plane1[0]) * 10)

# check if 'd' and 'l' or 'r' would collid
for plane1 in d['D']:
    for plane2 in d['L']:
        if abs(plane2[0] - plane1[0]) == abs(plane2[1] - plane1[1]) and plane2[0] > plane1[0] and plane2[1] < plane1[1]:
            ans = min(ans, abs(plane2[0] - plane1[0]) * 10)
    for plane2 in d['R']:
        if abs(plane2[0] - plane1[0]) == abs(plane2[1] - plane1[1]) and plane2[0] < plane1[0] and plane2[1] < plane1[1]:
            ans = min(ans, abs(plane2[0] - plane1[0]) * 10)
if ans > 2*10**6:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import math

def func(n):
	r=n
	return(r)

n=int(input())
x=[0]*n
y=[0]*n
dx=[0]*n
dy=[0]*n

for ii in range(n):
	xi,yi,si=input().split()
	x[ii]=int(xi)
	y[ii]=int(yi)
	if si=="U":
		dy[ii]=1
	elif si=="D":
		dy[ii]=-1
	elif si=="R":
		dx[ii]=1
	else:# si=="L":
		dx[ii]=-1
r=0
rb=False
for ii in range(n-1):
	for jj in np.arange(ii+1,n):
		#print(ii,jj,dx[ii],dx[jj],dy[ii],dy[jj])
		if dx[ii]*dx[jj]==1:
			pass
		elif dy[ii]*dy[jj]==1:
			pass
		else:
			tx=0
			ty=0
			if dy[ii]!=dy[jj] and dx[ii]!=dx[jj]:
				tx=-(x[ii]-x[jj])/(dx[ii]-dx[jj])
				ty=-(y[ii]-y[jj])/(dy[ii]-dy[jj])
			elif dy[ii]!=dy[jj] and x[ii]==x[jj]:
				ty=-(y[ii]-y[jj])/(dy[ii]-dy[jj])
				tx=ty
			elif dx[ii]!=dx[jj] and y[ii]==y[jj]:
				tx=-(x[ii]-x[jj])/(dx[ii]-dx[jj])
				ty=tx
			#print(ii,jj,ty,tx,r)
			if tx==ty and tx>0:
				if rb:
					if r>tx:
						r=tx
				else:
					rb=True
					r=tx
			#print(ii,jj,ty,tx,r)
if rb:
	print(int(10*r))
else:
	print("SAFE")

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
import sys
input = sys.stdin.readline
M = 200001
n = int(input())
l = [None] * n
ans = 10 ** 18
for i in range(n):
    x, y, u = input().split()
    u = ('R', 'D', 'L', 'U').index(u)
    l[i] = (int(x), int(y), u)
for _ in range(3):
    l.sort()
    xy = [[] for _ in range(M * 2 - 1)]
    yx = [[] for _ in range(M * 2 - 1)]
    xs = [[] for _ in range(M)]
    k = []
    for i, t in enumerate(l):
        x, y, u = t
        u %= 4
        if u == 3:
            xy[x + y].append(x)
        elif u == 1:
            yx[x - y + M - 1].append(x)
        elif u == 2:
            xs[y].append(x)
        elif u == 0:
            k.append((x, y))
        l[i] = (y, -x + M - 1, u + 1)
    for x, y in k:
        idx = bisect_left(xs[y], x)
        if idx < len(xs[y]):
            ans = min(ans, (xs[y][idx] - x) * 5)
        idx = bisect_left(xy[x + y], x)
        if idx < len(xy[x + y]):
            ans = min(ans, (xy[x + y][idx] - x) * 10)
        idx = bisect_left(yx[x - y + M - 1], x)
        if idx < len(yx[x - y + M - 1]):
            ans = min(ans, (yx[x - y + M - 1][idx] - x) * 10)
if ans == 10 ** 18:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
XYU = []
from collections import defaultdict
UR = defaultdict(list)
UL = defaultdict(list)
DR = defaultdict(list)
DL = defaultdict(list)
LR = defaultdict(list)
UD = defaultdict(list)
for _ in range(N):
    x, y, u = input().split()
    x, y = int(x), int(y)
    if u=='U':
        UR[(x+y)].append((x, y))
        UL[(x-y)].append((x, y))
        UD[x].append((x, y))
    if u=='R':
        LR[y].append((x, y))
    if u=='D':
        DL[(x+y)].append((x, y))
        DR[(x-y)].append((x, y))
    XYU.append((x, y, u))

ans = 10**18
def check(x, y, u):
    global ans
    if u=='R':
        for px, py in UR[(x+y)]:
            if x<px and y>py:
                ans = min(ans, px-x)
                
        for px, py in DR[(x-y)]:
            if x<px and py>y:
                ans = min(ans, px-x)
                
    if u=='L':
        for px, py in UL[(x-y)]:
            if x>px and y>py:
                ans = min(ans, x-px)
                
        for px, py in DL[(x+y)]:
            if x>px and py>y:
                ans = min(ans, x-px) 
                
        for px, py in LR[y]:
            if x>px:
                ans = min(ans, (x-px)/2)
                
    if u=='D':
        for px, py in UD[x]:
            if py<y:
                ans = min(ans, (y-py)/2)

for x, y, u in XYU:
    check(x, y, u)

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

Submission status: Time Limit Exceeded

Solution code:
# Contest No.: M-SOLUTIONS Programming Contest 2020
# Problem No.: F
# Solver:      JEMINI
# Date:        20200725

import sys
import heapq

def main():
    n = int(input())
    XUList = []
    #YUList = []
    XRList = []
    #YRList = []
    XDList = []
    #YDList = []
    XLList = []
    #YLList = []

    for _ in range(n):
        x, y, d = sys.stdin.readline().split()
        x, y = int(x), int(y)
        if d == "U":
            XUList.append((x, y))
            #YUList.append((y, x))
        elif d == "R":
            XRList.append((x, y))
            #YRList.append((y, x))
        elif d == "D":
            XDList.append((x, y))
            #YDList.append((y, x))
        else:
            XLList.append((x, y))
            #YLList.append((y, x))

    XUList.sort()
    #YUList.sort()
    XRList.sort()
    #YRList.sort()
    XDList.sort()
    #YDList.sort()
    XLList.sort()
    #YLList.sort()
    #print(XUList, XRList, XDList, XLList)
    ans = 10 ** 9
    for UPlane in XUList:
        for RPlane in XRList:
            if UPlane[0] > RPlane[0] and UPlane[1] < RPlane[1] and UPlane[0] - RPlane[0] == RPlane[1] - UPlane[1]:
                ans = min(ans, (RPlane[1] - UPlane[1]) * 10)
        for DPlane in XDList:
            if UPlane[0] == DPlane[0] and UPlane[1] < DPlane[1]:
                ans = min(ans, abs(UPlane[1] - DPlane[1]) * 5)
        for LPlane in XLList:
            if UPlane[0] < LPlane[0] and UPlane[1] < LPlane[1] and LPlane[0] - UPlane[0] == LPlane[1] - UPlane[1]:
                ans = min(ans, (LPlane[1] - UPlane[1]) * 10)
    
    for DPlane in XDList:
        for RPlane in XRList:
            if DPlane[0] > RPlane[0] and DPlane[1] > RPlane[1] and DPlane[0] - RPlane[0] == DPlane[1] - RPlane[1]:
                ans = min(ans, (DPlane[1] - RPlane[1]) * 10)
        for LPlane in XLList:
            if DPlane[0] < LPlane[0] and DPlane[1] > LPlane[1] and LPlane[0] - DPlane[0] == DPlane[1] - LPlane[1]:
                ans = min(ans, (DPlane[1] - LPlane[1]) * 10)
            
    for RPlane in XRList:
        for LPlane in XLList:
            if RPlane[1] == LPlane[1] and RPlane[0] < LPlane[0]:
                ans = min(ans, (LPlane[0] - RPlane[0]) * 5)
    if ans == 10 ** 9:
        print("SAFE")
    else:
        print(ans)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# n = int(input())
# arr = []
# for i in range(n):
#     x,y,p = list(map(int,input().split()))
#     arr.append([x,y,p])

# for i in range(n+1):
#     s = 0
#     for j in range(n):
#         s+=(min(arr[i][0],arr[i][1],))


n = int(input())
up,down,left,right = [],[],[],[]
for i in range(n):
    x,y,t = list(map(str,input().split()))
    x,y = int(x),int(y)
    l = [x,y]
    if t=='U':
        up.append(l)
    elif t=='D':
        down.append(l)
    elif t=='L':
        left.append(l)
    else:
        right.append(l)
up.sort()
down.sort()
left.sort()
right.sort()
ans = []
for i in up:
    x,y = i
    for j in down:
        u,v = j
        if x==u and y<=v:
            diff = v-y
            diff = diff*5
            ans.append(diff)

for i in left:
    x, y = i
    for j in right:
        u, v = j
        if y==v and x>=u:
            diff = x-u
            diff = diff*5
            ans.append(diff)

for i in up:
    x,y = i
    for j in left:
        u,v = j
        if v>y and u>x:
            d1 = v-y
            d2 = u-x
            if d1==d2:
                ans.append(d1*10)
    for j in right:
        u,v = j
        if x>u and v>y:
            d1 = v-y
            d2 = x-u
            if d1==d2:
                ans.append(d1*10)

for i in down:
    x, y = i
    for j in left:
        u, v = j
        if y>v and u > x:
            d1 = y-v
            d2 = u-x
            if d1 == d2:
                ans.append(d1*10)
    for j in right:
        u, v = j
        if x > u and y>v:
            d1 = y-v
            d2 = x-u
            if d1 == d2:
                ans.append(d1*10)
if len(ans)==0:
    print("SAFE")
else:
    print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
U = []
D = []
R = []
L = []
for i in range(N):
  da = list(input().split())
  if da[2] == 'U':
    U.append(list(map(int, da[0:2])))
  elif da[2] == 'D':
    D.append(list(map(int, da[0:2])))
  elif da[2] == 'R':
    R.append(list(map(int, da[0:2])))
  elif da[2] == 'L':
    L.append(list(map(int, da[0:2])))
MIN = 2000010
for u in U:
  for d in D:
    if u[0] == d[0] and u[1] < d[1]:
      MIN = min(MIN, (d[1]-u[1])*5)
  for r in R:
    if u[0] > r[0] and u[1] < r[1] and u[0]-r[0] == r[1]-u[1]:
      MIN = min(MIN, (u[0]-r[0])*10)
  for l in L:
    if u[0] < l[0] and u[1] < l[1] and l[0]-u[0] == l[1]-u[1]:
      MIN = min(MIN, (l[0]-u[0])*10)
for d in D:
  for r in R:
    if d[0] > r[0] and d[1] > r[1] and d[0]-r[0] == d[1]-r[1]:
      MIN = min(MIN, (d[0]-r[0])*10)
  for l in L:
    if d[0] < l[0] and d[1] > l[1] and l[0]-d[0] == d[1]-l[1]:
      MIN = min(MIN, (l[0]-d[0])*10)
for r in R:
  for l in L:
    if r[1] == l[1] and r[0] < l[0]:
      MIN = min(MIN, (l[0]-r[0])*5)
if MIN != 2000010:
  print(MIN)
else:
  print("SAFE")

Submission status: Time Limit Exceeded

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
XYU = []
from collections import defaultdict, deque
UR = defaultdict(deque)
UL = defaultdict(deque)
DR = defaultdict(deque)
DL = defaultdict(deque)
LR = defaultdict(deque)
UD = defaultdict(deque)
for _ in range(N):
    x, y, u = input().split()
    x, y = int(x), int(y)
    if u=='U':
        UR[(x+y)].append((x, y))
        UL[(x-y)].append((x, y))
        UD[x].append((x, y))
    if u=='R':
        LR[y].append((x, y))
    if u=='D':
        DL[(x+y)].append((x, y))
        DR[(x-y)].append((x, y))
    XYU.append((x, y, u))

ans = 10**18
def check(x, y, u):
    global ans
    if u=='R':
        for px, py in UR[(x+y)]:
            if x<px and y>py:
                ans = min(ans, px-x)
                
        for px, py in DR[(x-y)]:
            if x<px and py>y:
                ans = min(ans, px-x)
                
    if u=='L':
        for px, py in UL[(x-y)]:
            if x>px and y>py:
                ans = min(ans, x-px)
                
        for px, py in DL[(x+y)]:
            if x>px and py>y:
                ans = min(ans, x-px) 
                
        for px, py in LR[y]:
            if x>px:
                ans = min(ans, (x-px)/2)
                
    if u=='D':
        for px, py in UD[x]:
            if py<y:
                ans = min(ans, (y-py)/2)
for x, y, u in XYU:
    check(x, y, u)

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

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
M = 200001
n = int(input())
l = [None] * n
ans = 10 ** 18
for i in range(n):
    x, y, u = input().split()
    u = ('R', 'D', 'L', 'U').index(u)
    l[i] = (int(x), int(y), u)
for _ in range(4):
    l.sort()
    xy = [[] for _ in range(M * 2 - 1)]
    yx = [[] for _ in range(M * 2 - 1)]
    xs = [[] for _ in range(M)]
    k = []
    for i, t in enumerate(l):
        x, y, u = t
        u %= 4
        if u == 3:
            xy[x + y].append(x)
        elif u == 1:
            yx[x - y + M - 1].append(x)
        elif u == 2:
            xs[y].append(x)
        else:
            k.append((x, y))
        l[i] = (y, -x + M - 1, u + 1)
    for x, y in k:
        idx = bisect_left(xs[y], x)
        if idx < len(xs[y]):
            ans = min(ans, (xs[y][idx] - x) * 5)
        idx = bisect_left(xy[x + y], x)
        if idx < len(xy[x + y]):
            ans = min(ans, (xy[x + y][idx] - x) * 10)
        idx = bisect_left(yx[x - y + M - 1], x)
        if idx < len(yx[x - y + M - 1]):
            ans = min(ans, (yx[x - y + M - 1][idx] - x) * 10)
if ans == 10 ** 18:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a_list = []
min_crash = 2e5
for _ in range(n):
    x, y, u = list(input().split())
    x = int(x)
    y = int(y)
    a_list.append([x, y, u])

min_crash = 2e5
x_sort = sorted(a_list, key=lambda a: a[0])
y_sort = sorted(a_list, key=lambda a: a[1])
for i in range(n):
    if i < n-1 and x_sort[i][2] == "R":
        for x, y, u in x_sort[i+1:]:
            if (y < x_sort[i][1] and u == "U") or (y > x_sort[i][1] and u == "D"):
                if abs(x_sort[i][0]-x) == abs(x_sort[i][1] - y):
                    crash = x - x_sort[i][0]
                    min_crash = min(min_crash, crash)
            elif y == x_sort[i][1] and u == "L":
                crash = (x - x_sort[i][0])/2
                min_crash = min(min_crash, crash)
    elif i != 0 and x_sort[i][2] == "L":
        for x, y, u in x_sort[:i]:
            if (y < x_sort[i][1] and u == "U") or (y > x_sort[i][1] and u == "D"):
                if abs(x_sort[i][0]-x) == abs(x_sort[i][1] - y):
                    crash = x_sort[i][0]-x
                    min_crash = min(min_crash, crash)
            elif y == x_sort[i][1] and u == "R":
                crash = (x_sort[i][0] - x)/2
                min_crash = min(min_crash, crash)
    
    if i < n-1 and y_sort[i][2] == "U":
        for x, y, u in y_sort[i+1:]:
            if (x < y_sort[i][0] and u == "R") or (x > y_sort[i][0] and u == "L"):
                if abs(y_sort[i][1]-y) == abs(y_sort[i][0] - x):
                    crash = y-y_sort[i][1]
                    min_crash = min(min_crash, crash)
            elif x == y_sort[i][0] and u == "D":
                crash = (y - y_sort[i][1])/2
                min_crash = min(min_crash, crash)
    elif i != 0 and y_sort[i][2] == "D":
        for x, y, u in y_sort[:i]:
            if (x < y_sort[i][0] and u == "R") or (x > y_sort[i][0] and u == "L"):
                if abs(y_sort[i][1]-y) == abs(y_sort[i][0] - x):
                    crash = y_sort[i][1]-y
                    min_crash = min(min_crash, crash)
            elif x == y_sort[i][0] and u == "U":
                crash = (y_sort[i][1] - y)/2
                min_crash = min(min_crash, crash)


if min_crash == 2e5:
    print("SAFE")
else:
    print(int(min_crash*10))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
M = 200001
n = int(input())
l = [None] * n
ans = 10 ** 18
for i in range(n):
    x, y, u = input().split()
    u = ('R', 'D', 'L', 'U').index(u)
    l[i] = (int(x), int(y), u)
for _ in range(4):
    xy = [[] for _ in range(M * 2 - 1)]
    yx = [[] for _ in range(M * 2 - 1)]
    xs = [[] for _ in range(M)]
    k = []
    for i, t in enumerate(l):
        x, y, u = t
        u %= 4
        if u == 3:
            xy[x + y].append(x)
        elif u == 1:
            yx[x - y + M - 1].append(x)
        elif u == 2:
            xs[y].append(x)
        else:
            k.append((x, y))
        l[i] = (y, -x + M - 1, u + 1)
    for x, y in k:
        xs[y].sort()
        idx = bisect_left(xs[y], x)
        if idx < len(xs[y]):
            ans = min(ans, (xs[y][idx] - x) * 5)
        xy[x + y].sort()
        idx = bisect_left(xy[x + y], x)
        if idx < len(xy[x + y]):
            ans = min(ans, (xy[x + y][idx] - x) * 10)
        yx[x - y + M].sort()
        idx = bisect_left(yx[x - y + M - 1], x)
        if idx < len(yx[x - y + M - 1]):
            ans = min(ans, (yx[x - y + M - 1][idx] - x) * 10)
if ans == 10 ** 18:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    xr = []
    xl = []
    yu = []
    yd = []
    safe_flg = True
    for i in range(N):
        line = input().split()
        if line[2] == "U":
            yu.append([int(line[0]) * 10, int(line[1]) * 10])
        elif line[2] == "R":
            xr.append([int(line[0]) * 10, int(line[1]) * 10])
        elif line[2] == "D":
            yd.append([int(line[0]) * 10, int(line[1]) * 10])
        elif line[2] == "L":
            xl.append([int(line[0]) * 10, int(line[1]) * 10])
    
    t = 999999999
    for i in range(len(yu)):
        x0 = yu[i][0]
        y0 = yu[i][1]
        for j in range(len(xr)):
            x1 = xr[j][0]
            y1 = xr[j][1]
            if x1 - x0 == y0 - y1 and y0 <= y1:
                safe_flg = False
                # print("yuxr", y1, y0)
                t = min(t, y1 - y0)
        for j in range(len(yd)):
            x1 = yd[j][0]
            y1 = yd[j][1]
            if x1 == x0 and (y1 - y0) % 2 == 0 and y0 <= y1:
                safe_flg = False
                # print("yuyd", y1, y0)
                t = min(t, int((y1 - y0) / 2))
        for j in range(len(xl)):
            x1 = xl[j][0]
            y1 = xl[j][1]
            if x1 - x0 == y1 - y0 and y0 <= y1:
                safe_flg = False
                # print("yuxl", y1, y0)
                t = min(t, y1 - y0)

    for i in range(len(yd)):
        x0 = yd[i][0]
        y0 = yd[i][1]
        for j in range(len(xr)):
            x1 = xr[j][0]
            y1 = xr[j][1]
            if x1 - x0 == y1 - y0 and y0 >= y1:
                safe_flg = False
                # print("ydxr", y1, y0)
                t = min(t, y0 - y1)
        for j in range(len(xl)):
            x1 = xl[j][0]
            y1 = xl[j][1]
            if x1 - x0 == y0 - y1 and y0 >= y1:
                safe_flg = False
                # print("ydxl", y1, y0)
                t = min(t, y0 - y1)

    for i in range(len(xr)):
        x0 = xr[i][0]
        y0 = xr[i][1]
        for j in range(len(xl)):
            x1 = xl[j][0]
            y1 = xl[j][1]
            if y1 == y0 and (x1 - x0) % 2 == 0 and x0 <= x1:
                safe_flg = False
                t = min(t, int((x1 - x0) // 2))
    
    if safe_flg:
        return "SAFE"
    else:
        return t

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n = int(input())
xy = []
u = []
for i in range(n):
    x,y,d = input().split()
    xy.append([int(x),int(y)])
    if d == 'R':
        u.append([1,0])
    elif d == 'L':
        u.append([-1,0])
    elif d == 'D':
        u.append([0,-1])
    elif d == 'U':
        u.append([0,1])
xy_ = np.array(xy)
u_ = np.array(u)
ans = 'SAFE'
for i in range(400000):
    xy_ = xy_ + u_*0.5
    if len(set([tuple(j) for j in xy_.tolist()]))!= n:
        ans = (i+1)*5
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
U = []
D = []
R = []
L = []
for i in range(N):
  da = list(input().split())
  if da[2] == 'U':
    U.append(list(map(int, da[0:2])))
  elif da[2] == 'D':
    D.append(list(map(int, da[0:2])))
  elif da[2] == 'R':
    R.append(list(map(int, da[0:2])))
  elif da[2] == 'L':
    L.append(list(map(int, da[0:2])))
U.sort()
D.sort()
R.sort()
L.sort()
MIN = 2000010
for u in U:
  for d in D:
    if u[0] == d[0] and u[1] < d[1]:
      MIN = min(MIN, (d[1]-u[1])*5)
  for r in R:
    if u[0] > r[0] and u[1] < r[1] and u[0]-r[0] == r[1]-u[1]:
      MIN = min(MIN, (u[0]-r[0])*10)
  for l in L:
    if u[0] < l[0] and u[1] < l[1] and l[0]-u[0] == l[1]-u[1]:
      MIN = min(MIN, (l[0]-u[0])*10)
for d in D:
  for r in R:
    if d[0] > r[0] and d[1] > r[1] and d[0]-r[0] == d[1]-r[1]:
      MIN = min(MIN, (d[0]-r[0])*10)
  for l in L:
    if d[0] < l[0] and d[1] > l[1] and l[0]-d[0] == d[1]-l[1]:
      MIN = min(MIN, (l[0]-d[0])*10)
for r in R:
  for l in L:
    if r[1] == l[1] and r[0] < l[0]:
      MIN = min(MIN, (l[0]-r[0])*5)
if MIN != 2000010:
  print(MIN)
else:
  print("SAFE")