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:
N = int(input())

Xaxis = [[] for _ in range(200001)]
Yaxis = [[] for _ in range(200001)]
sum = [[] for _ in range(400001)]
dif = [[] for _ in range(400001)]
value = []
ans = 10**8

for i in range(N):
    X,Y,P = input().split()
    X,Y = int(X),int(Y)
    value.append([X,Y,P])
    Xaxis[X].append(i)
    Yaxis[Y].append(i)
    sum[X+Y].append(i)
    dif[X-Y].append(i)

for i in Xaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'D' and value[i[k]][2] == 'U'):
                    if value[i[j]][1] >= value[i[k]][1]:
                        ans = min((value[i[j]][1]-value[i[k]][1])*5,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'D'):
                    if value[i[j]][1] <= value[i[k]][1]:
                        ans = min((value[i[k]][1]-value[i[j]][1])*5,ans)

for i in Yaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*5,ans)
                elif (value[i[j]][2] == 'R' and value[i[k]][2] == 'L'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*5,ans)

for i in sum:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if  (value[i[j]][2] == 'L' and value[i[k]][2] == 'D') or (value[i[j]][2] == 'U' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'D' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'U'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

for i in dif:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'U') or (value[i[j]][2] == 'D' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'D'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

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

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

Xaxis = [[] for _ in range(200001)]
Yaxis = [[] for _ in range(200001)]
sum = [[] for _ in range(400001)]
dif = [[] for _ in range(400001)]
value = []
ans = 10**8

for i in range(N):
    X,Y,P = input().split()
    X,Y = int(X),int(Y)
    value.append([X,Y,P])
    Xaxis[X].append(i)
    Yaxis[Y].append(i)
    sum[X+Y].append(i)
    dif[X-Y].append(i)

for i in Xaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'D' and value[i[k]][2] == 'U'):
                    if value[i[j]][1] >= value[i[k]][1]:
                        ans = min((value[i[j]][1]-value[i[k]][1])*5,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'D'):
                    if value[i[j]][1] <= value[i[k]][1]:
                        ans = min((value[i[k]][1]-value[i[j]][1])*5,ans)

for i in Yaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*5,ans)
                elif (value[i[j]][2] == 'R' and value[i[k]][2] == 'L'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*5,ans)

for i in sum:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if  (value[i[j]][2] == 'L' and value[i[k]][2] == 'D') or (value[i[j]][2] == 'U' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'D' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'U'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

for i in dif:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'U') or (value[i[j]][2] == 'D' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'D'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

if ans == 10**8:
    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 = []
UR = {}
URs = set()
UL = {}
ULs = set()
DR = {}
DRs = set()
DL = {}
DLs = set()
LR = {}
LRs = set()
UD = {}
UDs = set()
for _ in range(N):
    x, y, u = input().split()
    x, y = int(x), int(y)
    XYU.append((x, y, u))
XYU.sort()
for x, y, u in XYU:
    if u=='U':
        if x+y in URs:
            UR[(x+y)].append((x, y))
        else:
            UR[x+y] = [(x, y)]
            URs.add(x+y)
        if x-y in ULs:
            UL[(x-y)].append((x, y))
        else:
            UL[x-y] = [(x, y)]
            ULs.add(x-y)
        if x in UDs:
            UD[x].append((x, y))
        else:
            UD[x] = [(x, y)]
            UDs.add(x)
    if u=='R':
        if y in LRs:
            LR[y].append((x, y))
        else:
            LRs.add(y)
            LR[y] = [(x, y)]
    if u=='D':
        if x+y in DLs:
            DL[(x+y)].append((x, y))
        else:
            DL[x+y] = [(x, y)]
            DLs.add(x+y)
        if x-y in DRs:
            DR[(x-y)].append((x, y))
        else:
            DR[(x-y)] = [(x, y)]
            DRs.add(x-y)

ans = 10**18
def check(x, y, u):
    global ans
    if u=='R':
        if x+y in URs:
            for px, py in UR[(x+y)]:
                if x<px and y>py:
                    ans = min(ans, px-x)
        
        if x-y in DRs:      
            for px, py in DR[(x-y)]:
                if x<px and py>y:
                    ans = min(ans, px-x)
                
    if u=='L':
        if x-y in ULs:
            for px, py in UL[(x-y)]:
                if px>x: break
                if x>px and y>py:
                    ans = min(ans, x-px)
            
        if x+y in DLs:    
            for px, py in DL[(x+y)]:
                if px>x: break
                if x>px and py>y:
                    ans = min(ans, x-px) 
        
        if y in LRs:      
            for px, py in LR[y]:
                if px>x: break
                if x>px:
                    ans = min(ans, (x-px)/2)
                
    if u=='D':
        if x in UDs:
            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:
N = int(input())

Xaxis = [[] for _ in range(200001)]
Yaxis = [[] for _ in range(200001)]
sum = [[] for _ in range(400001)]
dif = [[] for _ in range(400001)]
value = []
ans = [10**8]

for i in range(N):
    X,Y,P = input().split()
    X,Y = int(X),int(Y)
    value.append([X,Y,P])
    Xaxis[X].append(i)
    Yaxis[Y].append(i)
    sum[X+Y].append(i)
    dif[X-Y].append(i)

for i in Xaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'D' and value[i[k]][2] == 'U'):
                    if value[i[j]][1] >= value[i[k]][1]:
                        ans.append(abs((value[i[j]][1]-value[i[k]][1])*5))
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'D'):
                    if value[i[j]][1] <= value[i[k]][1]:
                        ans.append(abs((value[i[j]][1]-value[i[k]][1])*5))

for i in Yaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans.append(abs((value[i[j]][0]-value[i[k]][0])*5))
                elif (value[i[j]][2] == 'R' and value[i[k]][2] == 'L'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans.append(abs((value[i[j]][0]-value[i[k]][0])*5))

for i in sum:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if  (value[i[j]][2] == 'L' and value[i[k]][2] == 'D') or (value[i[j]][2] == 'U' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans.append(abs((value[i[j]][0]-value[i[k]][0])*10))
                elif (value[i[j]][2] == 'D' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'U'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans.append(abs((value[i[j]][0]-value[i[k]][0])*10))

for i in dif:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'U') or (value[i[j]][2] == 'D' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans.append(abs((value[i[j]][0]-value[i[k]][0])*10))
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'D'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans.append(abs((value[i[j]][0]-value[i[k]][0])*10))

ans = min(ans)
if ans == 10**8:
    print('SAFE')
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n = int(input())
xy = np.array([])
u = np.array([])
for _ in range(n):
    a,b,c = input().split()
    xy = np.append(xy,np.array([int(a),int(b)]))
    if c == "U":
        u = np.append(u,np.array([[0,1]]))
    elif c == "D":
        u = np.append(u,np.array([[0,-1]]))
    elif c == "R":
        u = np.append(u,np.array([[1,0]]))
    else:
        u = np.append(u,np.array([[-1,0]]))

xy = xy.reshape(n,2)
u = u.reshape(n,2)

s = 200001
for i in range(n-1):
    for j in range(i+1,n):
        if max(xy[i]-xy[j])/2 < s:
            z = (xy[i]-xy[j])/(-u[i]+u[j])
            if np.isnan(z[0]):
                if s>z[1] and z[1]>0:
                    s = z[1]
            elif np.isnan(z[1]):
                if s>z[0] and z[0]>0:
                    s = z[0]
            elif z[0]==z[1] and s>z[0] and z[0]>0:
                s=z[0]
if s == 200001:
    print("SAFE")
else:
    print(int(s*10))

Submission status: Time Limit Exceeded

Solution code:
import itertools

def main():
    n = int(input())
    ans = 10**9
    u = []
    r = []
    d = []
    l = []
    for _ in range(n):
        k = input().split()
        x,y = int(k[0]),int(k[1])
        if(k[2] == "U"):
            u.append((x,y))
        elif(k[2] == "R"):
            r.append((x,y))
        elif(k[2] == "D"):
            d.append((x,y))
        elif(k[2] == "L"):
            l.append((x,y))

    prd = itertools.product(l,r)
    for j in prd:
        one = j[0]
        two = j[1]
        if(one[1] == two[1] and one[0] > two[0]):
            dif = one[0] - two[0]
            ans = min(ans,dif*10 //2)
            
    prd = itertools.product(u,d)
    for j in prd:
        one = j[0]
        two = j[1]
        if(one[0] == two[0] and one[1] < two[1]):
            dif = - one[1] + two[1]
            ans = min(ans,dif* 10 //2)

    prd = itertools.product(u,r)
    for j in prd:
        one = j[0]
        two = j[1]
        if(one[0]-two[0] == two[1]-one[1] and one[0]-two[0] > 0 and one[1] - two[1] < 0):
            ans = min(ans,(one[0]-two[0])*10)

    prd = itertools.product(u,l)
    for j in prd:
        one = j[0]
        two = j[1]
        if(-one[0] + two[0] == - one[1] + two[1] and one[0]-two[0] < 0 and one[1] - two[1] < 0):
            ans = min(ans,(two[0]-one[0])*10)
    
    prd = itertools.product(d,r)
    for j in prd:
        one = j[0]
        two = j[1]
        if(one[0]-two[0] == one[1]-two[1] and one[0]-two[0] > 0 and one[1] - two[1] > 0):
            ans = min(ans,(-two[0] + one[0])*10)

    prd = itertools.product(d,l)
    for j in prd:
        one = j[0]
        two = j[1]
        if(two[0]-one[0] == one[1] - two[1] and one[0]-two[0] < 0 and one[1] - two[1] > 0):
            ans = min(ans,(two[0] - one[0])*10)
    if(ans == 10**9):
        print("SAFE")
        return
    else:
        print(ans)
        return

if __name__ == "__main__":
    main()

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)
    XYU.append((x, y, u))
XYU.sort()
for x, y, u in XYU:
    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))

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 px>x: break
            if x>px and y>py:
                ans = min(ans, x-px)
                
        for px, py in DL[(x+y)]:
            if px>x: break
            if x>px and py>y:
                ans = min(ans, x-px) 
                
        for px, py in LR[y]:
            if px>x: break
            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:
import numpy as np
n = int(input())
xy = np.array([])
u = np.array([])
for _ in range(n):
    a,b,c = input().split()
    xy = np.append(xy,np.array([int(a),int(b)]))
    if c == "U":
        u = np.append(u,np.array([[0,1]]))
    elif c == "D":
        u = np.append(u,np.array([[0,-1]]))
    elif c == "R":
        u = np.append(u,np.array([[1,0]]))
    else:
        u = np.append(u,np.array([[-1,0]]))

xy = xy.reshape(n,2)
u = u.reshape(n,2)

s = 200001
for i in range(n-1):
    for j in range(i+1,n):
        z = (xy[i]-xy[j])/(-u[i]+u[j])
        if np.isnan(z[0]):
            if s>z[1] and z[1]>0:
                s = z[1]
        elif np.isnan(z[1]):
            if s>z[0] and z[0]>0:
                s = z[0]            
        elif z[0]==z[1] and s>z[0] and z[0]>0:
            s=z[0]
if s == 200001:
    print("SAFE")
else:
    print(int(s*10))

Submission status: Time Limit Exceeded

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

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

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

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

      elif U[i] == "U" and U[j] == "R":
        if X[i] > X[j] and Y[i] < Y[j] and X[i]-X[j] == Y[j]-Y[i]:
          time.append((X[i]-X[j])*10)

      elif U[i] == "U" and U[j] == "L":
        if X[i] < X[j] and Y[i] < Y[j] and X[j]-X[i] == Y[j]-Y[i]:
          time.append((X[j]-X[i])*10)

      elif U[i] == "D" and U[j] == "R":
        if X[i] > X[j] and Y[i] > Y[j] and X[i]-X[j] == Y[i]-Y[j]:
          time.append((X[i]-X[j])*10)

      elif U[i] == "D" and U[j] == "L":
        if X[i] < X[j] and Y[i] > Y[j] and X[j]-X[i] == Y[j]-Y[i]:
          time.append((X[j]-X[i])*10)

      elif U[i] == "R" and U[j] == "U":
        if X[i] < X[j] and Y[i] > Y[j] and X[j]-X[i] == Y[i]-Y[j]:
          time.append((X[j]-X[i])*10)

      elif U[i] == "R" and U[j] == "D":
        if X[i] < X[j] and Y[i] < Y[j] and X[j]-X[i] == Y[j]-Y[i]:
          time.append((X[j]-X[i])*10)

      elif U[i] == "L" and U[j] == "U":
        if X[i] > X[j] and Y[i] > Y[j] and X[i]-X[j] == Y[i]-Y[j]:
          time.append((X[i]-X[j])*10)

      elif U[i] == "L" and U[j] == "D":
        if X[i] > X[j] and Y[i] < Y[j] and X[i]-X[j] == Y[j]-Y[i]:
          time.append((X[i]-X[j])*10)

if len(time) > 0:
  time.sort()
  print(time[0])
else:
  print("SAFE")

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)

INF = 10**10
M = 4*10**5 + 10

N = int(input())
PUs = [[] for _ in range(M)]
PRs = [[] for _ in range(M)]
PDs = [[] for _ in range(M)]
PLs = [[] for _ in range(M)]
nUs = [[] for _ in range(M)]
nRs = [[] for _ in range(M)]
nDs = [[] for _ in range(M)]
nLs = [[] for _ in range(M)]
xUs = [[] for _ in range(M)]
xDs = [[] for _ in range(M)]
yLs = [[] for _ in range(M)]
yRs = [[] for _ in range(M)]

for _ in range(N):
    X, Y, U = input().split()
    X, Y = int(X), int(Y)
    if U == 'L':
        PLs[X+Y].append((X, U))
        nLs[X-Y].append((X, U))
        yLs[Y].append((X, U))
    elif U == 'R':
        PRs[X+Y].append((X, U))
        nRs[X-Y].append((X, U))
        yRs[Y].append((X, U))
    elif U == 'U':
        PUs[X+Y].append((X, U))
        nUs[X-Y].append((X, U))
        xUs[X].append((Y, U))
    else:  # U == 'D'
        PDs[X+Y].append((X, U))
        nDs[X-Y].append((X, U))
        xDs[X].append((Y, U))

def func(P1s, P2s, dir1, dir2):
    dist = INF
    for z in range(M):
        Ps = sorted(P1s[z] + P2s[z])
        for i in range(len(Ps)-1):
            if Ps[i][1] == dir1 and Ps[i+1][1] == dir2:
                d = Ps[i+1][0] - Ps[i][0]
                if d < dist:
                    dist = d
    return dist

ans = INF
dists = []
dists += [func(PRs, PUs, 'R', 'U') * 2]
dists += [func(PDs, PLs, 'D', 'L') * 2]
dists += [func(nRs, nDs, 'R', 'D') * 2]
dists += [func(nUs, nLs, 'U', 'L') * 2]
dists += [func(yRs, yLs, 'R', 'L')]
dists += [func(xUs, xDs, 'U', 'D')]

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

Submission status: Time Limit Exceeded

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

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 = []
yls = [[] for i in range(4*10**5+1)]
yrs = [[] for i in range(4*10**5+1)]
ylsa = [[] for i in range(4*10**5+1)]
yrsa = [[] for i in range(4*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)
    yls[x+y].append(x)
    ylsa[x-y+2*10**5].append(x)
  if u == 'R':
    YR[y].append(x)
    yrs[x+y].append(x)
    yrsa[x-y+2*10**5].append(x)

for x,y in xu: #上
  if yrs[x+y] != []:
    yrs[x+y].sort()
    ind = bisect(yrs[x+y],x)
    if ind > 0:
      ans = min(ans,abs(x-yrs[x+y][ind-1])*10)
  if ylsa[x-y+2*10**5] != []:
    ylsa[x-y+2*10**5].append(10**9)
    ylsa[x-y+2*10**5].sort()
    ind = bisect(ylsa[x-y+2*10**5],x)
    if ylsa[x-y+2*10**5][ind] != 10**9:
      ans = min(ans,abs(ylsa[x-y+2*10**5][ind]-x)*10)
  
for x,y in xd: #下
  if yls[x+y] != []:
    yls[x+y].append(10**9)
    yls[x+y].sort()
    ind = bisect(yls[x+y],x)
    if yls[x+y][ind] != 10**9:
      ans = min(ans,abs(x-yls[x+y][ind])*10)
  if yrsa[x-y+2*10**5] != []:
    yrsa[x-y+2*10**5].sort()
    ind = bisect(yrsa[x-y+2*10**5],x)
    if ind != 0:
      ans = min(ans,abs(yrsa[x-y+2*10**5][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 collections
import itertools
N = int(input())
#cnt[UDLR][x y x+y x-y][value]=set()
#U(0)とD(1)がx(0)が一緒:d-u(>=0)の最小値
#L(2)とR(3)がy(1)が一緒:l-r(>=0)の最小値
#UとRがx+y(2)が一緒:(x-y)のu-r(>=0)の最小値
#LとDがx+y(2)が一緒:(x-y)のl-d(>=0)の最小値
#UとLがx-y(3)が一緒:(x+y)の(l-u)(>=0)の最小値
#RとDがx-y(3)が一緒:(x+y)の(d-r)(>=0)の最小値
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 = x + y
    q = x - y
    if u == 'U':
        i = 0
    elif u == 'D':
        i = 1
    elif u == 'L':
        i = 2
    else:
        i = 3
    cnt[i][0][x].add(y)
    cnt[i][1][y].add(x)
    cnt[i][2][p].add(q)
    cnt[i][3][q].add(p)
ans = 10**10
for v in cnt[0][0]:
    ans = min([ans] + [
        d - u
        for u, d in itertools.product(cnt[0][0][v], cnt[1][0][v]) if d >= u
    ])
for v in cnt[2][1]:
    ans = min([ans] + [
        l - r
        for l, r in itertools.product(cnt[2][1][v], cnt[3][1][v]) if l >= r
    ])
for v in cnt[0][2]:
    ans = min([ans] + [
        u - r
        for u, r in itertools.product(cnt[0][2][v], cnt[3][2][v]) if u >= r
    ])
for v in cnt[2][2]:
    ans = min([ans] + [
        l - d
        for l, d in itertools.product(cnt[2][2][v], cnt[1][2][v]) if l >= d
    ])
for v in cnt[0][3]:
    ans = min([ans] + [
        l - u
        for l, u in itertools.product(cnt[2][3][v], cnt[0][3][v]) if l >= u
    ])
for v in cnt[3][3]:
    ans = min([ans] + [
        d - r
        for r, d in itertools.product(cnt[3][3][v], cnt[1][3][v]) if d >= r
    ])
print('SAFE' if ans == 10**10 else ans * 5)

Submission status: Time Limit Exceeded

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

# sys.setrecursionlimit(5000)

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

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

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

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

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


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

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

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

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

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

print(ans)