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

Solution (Python):
n = int(input())
b = 2000001
u = []; r = []; d = []; l = []
for i in range(n):
    A = list(input().split())
    a = [int(A[0]), int(A[1])]
    if A[2] == "U":
        u.append(a)
    elif A[2] == "R":
        r.append(a)
    elif A[2] == "D":
        d.append(a)
    else:
        l.append(a)

u1 = {}; d1 = {}
for i in range(len(u)):
    if u[i][0] not in u1:
        u1[u[i][0]] = []
    u1[u[i][0]].append(u[i][1])
for i in range(len(d)):
    if d[i][0] not in d1:
        d1[d[i][0]] = []
    d1[d[i][0]].append(d[i][1])
for i in range(200001):
    if i in u1 and i in d1:
        u1[i].sort(reverse=True)
        d1[i].sort(reverse=True)
        for j in range(len(u1[i])):
            for k in range(len(d1[i])):
                if u1[i][-1] < d1[i][-1]:
                    b = min(b, (d1[i][-1]-u1[i][-1])*5)
                    break
                else:
                    d1[i].pop()
            u1[i].pop()


r1 = {}; l1 = {}
for i in range(len(r)):
    if r[i][1] not in r1:
        r1[r[i][1]] = []
    r1[r[i][1]].append(r[i][0])
for i in range(len(l)):
    if l[i][1] not in l1:
        l1[l[i][1]] = []
    l1[l[i][1]].append(l[i][0])
for i in range(200001):
    if i in r1 and i in l1:
        r1[i].sort(reverse=True)
        l1[i].sort(reverse=True)
        for j in range(len(r1[i])):
            for k in range(len(l1[i])):
                if r1[i][-1] < l1[i][-1]:
                    b = min(b, (l1[i][-1]-r1[i][-1])*5)
                    break
                else:
                    l1[i].pop()
            r1[i].pop()
u2 = {}; r2 = {}
for i in range(len(u)):
    if u[i][0]+u[i][1] not in u2:
        u2[u[i][0]+u[i][1]] = []
    u2[u[i][0]+u[i][1]].append(u[i][0])
for i in range(len(r)):
    if r[i][0]+r[i][1] not in r2:
        r2[r[i][0]+r[i][1]] = []
    r2[r[i][0]+r[i][1]].append(r[i][0])
for i in range(400001):
    if i in u2 and i in r2:
        u2[i].sort(reverse=True)
        r2[i].sort(reverse=True)
        for j in range(len(r2[i])):
            for k in range(len(u2[i])):
                if r2[i][-1] < u2[i][-1]:
                    b = min(b, (u2[i][-1]-r2[i][-1])*10)
                    break
                else:
                    u2[i].pop()
            r2[i].pop()
l2 = {}; d2 = {}
for i in range(len(l)):
    if l[i][0]+l[i][1] not in l2:
        l2[l[i][0]+l[i][1]] = []
    l2[l[i][0]+l[i][1]].append(l[i][0])
for i in range(len(d)):
    if d[i][0]+d[i][1] not in d2:
        d2[d[i][0]+d[i][1]] = []
    d2[d[i][0]+d[i][1]].append(d[i][0])
for i in range(400001):
    if i in l2 and i in d2:
        l2[i].sort(reverse=True)
        d2[i].sort(reverse=True)
        for j in range(len(d2[i])):
            for k in range(len(l2[i])):
                if d2[i][-1] < l2[i][-1]:
                    b = min(b, (l2[i][-1]-d2[i][-1])*10)
                    break
                else:
                    l2[i].pop()
            d2[i].pop()
l3 = {}; u3 = {}
for i in range(len(l)):
    if l[i][0]-l[i][1] not in l3:
        l3[l[i][0]-l[i][1]] = []
    l3[l[i][0]-l[i][1]].append(l[i][0])
for i in range(len(u)):
    if u[i][0]-u[i][1] not in u3:
        u3[u[i][0]-u[i][1]] = []
    u3[u[i][0]-u[i][1]].append(u[i][0])
for i in range(-200000, 200001):
    if i in l3 and i in u3:
        l3[i].sort(reverse=True)
        u3[i].sort(reverse=True)
        for j in range(len(u3[i])):
            for k in range(len(l3[i])):
                if u3[i][-1] < l3[i][-1]:
                    b = min(b, (l3[i][-1]-u3[i][-1])*10)
                    break
                else:
                    l3[i].pop()
            u3[i].pop()
d3 = {}; r3 = {}
for i in range(len(d)):
    if d[i][0]-d[i][1] not in d3:
        d3[d[i][0]-d[i][1]] = []
    d3[d[i][0]-d[i][1]].append(d[i][0])
for i in range(len(r)):
    if r[i][0]-r[i][1] not in r3:
        r3[r[i][0]-r[i][1]] = []
    r3[r[i][0]-r[i][1]].append(r[i][0])
for i in range(-200000, 200001):
    if i in d3 and i in r3:
        d3[i].sort(reverse=True)
        r3[i].sort(reverse=True)
        for j in range(len(r3[i])):
            for k in range(len(d3[i])):
                if r3[i][-1] < d3[i][-1]:
                    b = min(b, (d3[i][-1]-r3[i][-1])*10)
                    break
                else:
                    d3[i].pop()
            r3[i].pop()
print("SAFE") if b == 2000001 else print(b)

Solution (Python):
import sys

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
    n = ni()
    s = 'UDLR'
    g = [list() for _ in range(4)]
    for _ in range(n):
        x, y, u = input().split()
        g[s.index(u)].append((int(x), int(y)))


    def calc(a, b):
        a.sort()
        b.sort()
        idx = 0
        m = len(b)
        res = 10 ** 9
        for x, y in a:
            while idx < m and (b[idx][0] < x or b[idx][0] == x and b[idx][1] < y):
                idx += 1
            if idx >= m:
                break
            if b[idx][0] == x and b[idx][1] >= y:
                res = min(res, b[idx][1] - y)
        return res * 5

    res1 = calc(g[0], g[1])
    res2 = calc([(y, x) for x, y in g[3]], [(y, x) for x, y in g[2]])
    res3 = calc([(x+y, x-y) for x, y in g[3]], [(x+y, x-y) for x, y in g[0]])
    res4 = calc([(x+y, x-y) for x, y in g[1]], [(x+y, x-y) for x, y in g[2]])
    res5 = calc([(x-y, x+y) for x, y in g[0]], [(x-y, x+y) for x, y in g[2]])
    res6 = calc([(x-y, x+y) for x, y in g[3]], [(x-y, x+y) for x, y in g[1]])
    ans = min(res1, res2, res3, res4, res5, res6)
    if ans > 10**9:
        print('SAFE')
    else:
        print(ans)
    return

solve()

Solution (Python):
n=int(input())
ver=[]
hor=[]
diagr=[]
diagl=[]
INF=10**9
for i in range(200001):
  ver.append([[],[]])
  hor.append([[],[]])
for i in range(-200000,200001):
  diagr.append([[],[],[],[]])
  diagl.append([[],[],[],[]])
for i in range(n):
  x,y,u=map(str,input().split())
  x=int(x)
  y=int(y)
  if u=='U':
    ver[x][0].append(y)
    diagr[x-y+200000][0].append(x)
    diagl[x+y][0].append(x)
  if u=='D':
    ver[x][1].append(y)
    diagr[x-y+200000][1].append(x)
    diagl[x+y][1].append(x)
  if u=='R':
    hor[y][0].append(x)
    diagr[x-y+200000][2].append(x)
    diagl[x+y][2].append(x)
  if u=='L':
    hor[y][1].append(x)
    diagr[x-y+200000][3].append(x)
    diagl[x+y][3].append(x)
ans=INF
for i in range(200001):
  if len(ver[i][0])>0 and len(ver[i][1])>0:
    ver[i][0].sort()
    ver[i][1].sort()
    if ver[i][0][0]>ver[i][1][-1]:
      continue
    pointer1=0
    pointer=0
    s=len(ver[i][1])
    t=len(ver[i][0])
    while pointer1<t:
      while pointer<s and pointer1<t and ver[i][1][pointer]<ver[i][0][pointer1]:
        pointer+=1
      if pointer==s:
        break
      ans=min(ans,(ver[i][1][pointer]-ver[i][0][pointer1])*5)
      pointer1+=1
for i in range(200001):
  if len(hor[i][0])>0 and len(hor[i][1])>0:
    hor[i][0].sort()
    hor[i][1].sort()
    if hor[i][0][0]>hor[i][1][-1]:
      continue
    pointer1=0
    pointer=0
    s=len(hor[i][1])
    t=len(hor[i][0])
    while pointer1<t:
      while pointer<s and pointer1<t and hor[i][1][pointer]<hor[i][0][pointer1]:
        pointer+=1
      if pointer==s:
        break
      ans=min(ans,(hor[i][1][pointer]-hor[i][0][pointer1])*5)
      pointer1+=1
for i in range(400001):
  if len(diagl[i][0])>0 and len(diagl[i][2])>0:
    diagl[i][0].sort()
    diagl[i][2].sort()
    if diagl[i][2][0]>diagl[i][0][-1]:
      continue
    pointer1=0
    pointer=0
    s=len(diagl[i][0])
    t=len(diagl[i][2])
    while pointer1<t:
      while pointer<s and pointer1<t and diagl[i][0][pointer]<diagl[i][2][pointer1]:
        pointer+=1
      if pointer==s:
        break
      ans=min(ans,(diagl[i][0][pointer]-diagl[i][2][pointer1])*10)
      pointer1+=1
  if len(diagl[i][1])>0 and len(diagl[i][3])>0:
    diagl[i][1].sort()
    diagl[i][3].sort()
    if diagl[i][1][0]>diagl[i][3][-1]:
      continue
    pointer1=0
    pointer=0
    s=len(diagl[i][3])
    t=len(diagl[i][1])
    while pointer1<t:
      while pointer<s and pointer1<t and diagl[i][3][pointer]<diagl[i][1][pointer1]:
        pointer+=1
      if pointer==s:
        break
      ans=min(ans,(diagl[i][3][pointer]-diagl[i][1][pointer1])*10)
      pointer1+=1
for i in range(400001):
  if len(diagr[i][0])>0 and len(diagr[i][3])>0:
    diagr[i][0].sort()
    diagr[i][3].sort()
    if diagr[i][0][0]>diagr[i][3][-1]:
      continue
    pointer1=0
    pointer=0
    s=len(diagr[i][3])
    t=len(diagr[i][0])
    while pointer1<t:
      while pointer<s and pointer1<t and diagr[i][3][pointer]<diagr[i][0][pointer1]:
        pointer+=1
      if pointer==s:
        break
      ans=min(ans,(diagr[i][3][pointer]-diagr[i][0][pointer1])*10)
      pointer1+=1
  if len(diagr[i][1])>0 and len(diagr[i][2])>0:
    diagr[i][1].sort()
    diagr[i][2].sort()
    if diagr[i][2][0]>diagr[i][1][-1]:
      continue
    pointer1=0
    pointer=0
    s=len(diagr[i][1])
    t=len(diagr[i][2])
    while pointer1<t:
      while pointer<s and pointer1<t and diagr[i][1][pointer]<diagr[i][2][pointer1]:
        pointer+=1
      if pointer==s:
        break
      ans=min(ans,(diagr[i][1][pointer]-diagr[i][2][pointer1])*10)
      pointer1+=1
if ans==INF:
  print('SAFE')
else:
  print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from collections import defaultdict
from bisect import bisect_right
n = int(input())
a = [list(input().split()) for i in range(n)]
for i in range(n):
    if a[i][2] == "R":
        a[i][2] = 1
    elif a[i][2] == "L":
        a[i][2] = 2
    elif a[i][2] == "U" :
        a[i][2] = 3
    else:
        a[i][2] = 4
    a[i][0] = int(a[i][0])
    a[i][1] = int(a[i][1])
a.sort(key=lambda x: x[2])
R1 = defaultdict(list)
R2 = defaultdict(list)
L1 = defaultdict(list)
L2 = defaultdict(list)
U = defaultdict(list)
R = defaultdict(list)

R1u = defaultdict(bool)
R2u = defaultdict(bool)
L1u = defaultdict(bool)
L2u = defaultdict(bool)
Uu = defaultdict(bool)
Ru = defaultdict(bool)


M = 10000000
for x, y, u in a:
    if u == 1:
        R1[y - x].append(x)
        R2[x + y].append(x)
        R[y].append(x)
    elif u == 2:
        L1[x + y].append(x)
        L2[y - x].append(x)
        if not Ru[y]:
            R[y].sort()
            Ru[y] = True
        k = bisect_right(R[y], x)
        if k > 0:
            M = min((x - R[y][k-1]) * 5, M)

    elif u == 3:
        if not L2u[y - x]:
            L2[y - x].sort()
            L2u[y - x] = True
        k = bisect_right(L2[y - x], x)
        if k < len(L2[y - x]):
            M = min(M, (L2[y - x][k] - x) * 10)
        
        if not R2[x + y]:
            R2[x + y].sort()
            R2u[x + y] = True
        k = bisect_right(R2[x + y], x)
        if k > 0:
            M = min(M, (x - R2[x + y][k-1]) * 10)
        
        U[x].append(y)
    else:
        if not L1u[x + y]:
            L1[x + y].sort()
            L1u[x + y] = True
        k = bisect_right(L1[x + y], x)
        if k < len(L1[x + y]):
            M = min(M, (L1[x + y][k] - x) * 10)

        if not R1u[y - x]:
            R1[y - x].sort()
            R1u[y - x] = True
        k = bisect_right(R1[y - x], x)
        if k > 0:
            M = min(M, (x - R1[y - x][k-1]) * 10)

        if not Uu[x]:
            U[y].sort()
            Uu[y] = True
        k = bisect_right(U[x], y)
        if k > 0 :
            M = min((y - U[x][k-1]) * 5, M)
print(M if M < 10000000 else "SAFE")

Solution (Python):
import sys
input = sys.stdin.readline
from operator import itemgetter

ANS=1<<100

N=int(input())
L=[]
R=[]
U=[]
D=[]

for i in range(N):
    x,y,c=input().split()
    if c=="L":
        L.append((int(x),int(y)))

    if c=="R":
        R.append((int(x),int(y)))

    if c=="U":
        U.append((int(x),int(y)))

    if c=="D":
        D.append((int(x),int(y)))

L.sort(key=itemgetter(0))
R.sort(key=itemgetter(0))
L.sort(key=itemgetter(1))
R.sort(key=itemgetter(1))

indr=0
for indl in range(len(L)):
    while indr<len(R) and R[indr][1]<L[indl][1]:
        indr+=1

    while indr<len(R) and R[indr][1]==L[indl][1] and R[indr][0]<L[indl][0]:
        ANS=min(ANS,(L[indl][0]-R[indr][0])*5)
        indr+=1
        
U.sort(key=itemgetter(1),reverse=True)
D.sort(key=itemgetter(1),reverse=True)
U.sort(key=itemgetter(0))
D.sort(key=itemgetter(0))

indd=0
for indu in range(len(U)):
    while indd<len(D) and D[indd][0]<U[indu][0]:
        indd+=1
        
    while indd<len(D) and U[indu][0]==D[indd][0] and U[indu][1]<D[indd][1]:
        ANS=min(ANS,(D[indd][1]-U[indu][1])*5)
        indd+=1

U.sort(key=itemgetter(0))
R.sort(key=itemgetter(0))
U.sort(key=lambda x:x[0]+x[1])
R.sort(key=lambda x:x[0]+x[1])

indr=0
for indu in range(len(U)):
    while indr<len(R) and R[indr][0]+R[indr][1]<U[indu][0]+U[indu][1]:
        indr+=1
    while indr<len(R) and R[indr][0]+R[indr][1]==U[indu][0]+U[indu][1] and R[indr][0]<U[indu][0]:
        ANS=min(ANS,(U[indu][0]-R[indr][0])*10)
        indr+=1

U.sort(key=itemgetter(0),reverse=True)
L.sort(key=itemgetter(0),reverse=True)
U.sort(key=lambda x:x[0]-x[1])
L.sort(key=lambda x:x[0]-x[1])

indl=0
for indu in range(len(U)):
    while indl<len(L) and L[indl][0]-L[indl][1]<U[indu][0]-U[indu][1]:
        indl+=1
    while indl<len(L) and L[indl][0]-L[indl][1]==U[indu][0]-U[indu][1] and L[indl][0]>U[indu][0]:
        ANS=min(ANS,(L[indl][0]-U[indu][0])*10)
        indl+=1

D.sort(key=itemgetter(0))
R.sort(key=itemgetter(0))
D.sort(key=lambda x:x[0]-x[1])
R.sort(key=lambda x:x[0]-x[1])

indr=0
for indd in range(len(D)):
    while indr<len(R) and R[indr][0]-R[indr][1]<D[indd][0]-D[indd][1]:
        indr+=1
    while indr<len(R) and R[indr][0]-R[indr][1]==D[indd][0]-D[indd][1] and R[indr][0]<D[indd][0]:
        ANS=min(ANS,(D[indd][0]-R[indr][0])*10)
        indr+=1

D.sort(key=itemgetter(0),reverse=True)
L.sort(key=itemgetter(0),reverse=True)
D.sort(key=lambda x:x[0]+x[1])
L.sort(key=lambda x:x[0]+x[1])

indl=0
for indd in range(len(D)):
    while indl<len(L) and L[indl][0]+L[indl][1]<D[indd][0]+D[indd][1]:
        indl+=1
    while indl<len(L) and L[indl][0]+L[indl][1]==D[indd][0]+D[indd][1] and L[indl][0]>D[indd][0]:
        ANS=min(ANS,(L[indl][0]-D[indd][0])*10)
        indl+=1


if ANS==1<<100:
    print("SAFE")
else:
    print(ANS)

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

Solution (Python):
from bisect import bisect
from collections import defaultdict

n = int(input())
up = [defaultdict(list), defaultdict(list), defaultdict(list)]
dp = [defaultdict(list), defaultdict(list), defaultdict(list)]
lp = [defaultdict(list), defaultdict(list), defaultdict(list)]
rp = [defaultdict(list), defaultdict(list), defaultdict(list)]

for _ in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == 'U':
        up[0][x].append(y)
        up[1][x + y].append(x)
        up[2][x - y].append(x)
    elif u == 'D':
        dp[0][x].append(y)
        dp[1][x + y].append(x)
        dp[2][x - y].append(x)
    elif u == 'L':
        lp[0][y].append(x)
        lp[1][x + y].append(x)
        lp[2][x - y].append(x)
    else:
        rp[0][y].append(x)
        rp[1][x + y].append(x)
        rp[2][x - y].append(x)


def crush_time(planes1, planes2, idx):
    result = INF
    for xy in planes1[idx]:
        if xy not in planes2[idx]:
            continue
        s = planes1[idx][xy]
        s.sort()
        for x in planes2[idx][xy]:
            i = bisect(s, x)
            if i > 0:
                result = min(result, x - s[i - 1])
    return result


INF = 10 ** 18

ans = min(
    crush_time(up, dp, 0) * 5,
    crush_time(rp, lp, 0) * 5,
    crush_time(rp, up, 1) * 10,
    crush_time(dp, lp, 1) * 10,
    crush_time(up, lp, 2) * 10,
    crush_time(rp, dp, 2) * 10,
)

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

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

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

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

Solution (Python):
def main():
  import sys
  input = sys.stdin.readline
  N = int(input())
  XYU = [list(map(str,input().split())) for _ in range(N)]
  from collections import deque
  INF = float('inf')

  UD = [0] * 200001
  LR = [0] * 200001
  UR = [0] * 400001
  DL = [0] * 400001
  DR = [0] * 400001
  UL = [0] * 400001


  for X,Y,u in XYU:
    X = int(X)
    Y = int(Y)
    if u=='R':
      if type(LR[Y])==int:
        LR[Y] = deque()
      if type(UR[X+Y])==int:
        UR[X+Y] = deque()
      if type(DR[X-Y+200000])==int:
        DR[X-Y+200000] = deque()

      LR[Y].append((X,u))
      UR[X+Y].append((Y,u))
      DR[X-Y+200000].append((Y,u))
    elif u=='L':
      if type(LR[Y])==int:
        LR[Y] = deque()
      if type(DL[X+Y])==int:
        DL[X+Y] = deque()
      if type(UL[X-Y+200000])==int:
        UL[X-Y+200000] = deque()
      LR[Y].append((X,u))
      DL[X+Y].append((Y,u))
      UL[X-Y+200000].append((Y,u))
    elif u=='U':
      if type(UD[X])==int:
        UD[X] = deque()
      if type(UR[X+Y])==int:
        UR[X+Y] = deque()
      if type(UL[X-Y+200000])==int:
        UL[X-Y+200000] = deque()
      UD[X].append((Y,u))
      UR[X+Y].append((Y,u))
      UL[X-Y+200000].append((Y,u))
    else:
      if type(UD[X])==int:
        UD[X] = deque()
      if type(DL[X+Y])==int:
        DL[X+Y] = deque()
      if type(DR[X-Y+200000])==int:
        DR[X-Y+200000] = deque()
      UD[X].append((Y,u))
      DL[X+Y].append((Y,u))
      DR[X-Y+200000].append((Y,u))

  safe = True
  ans = INF
  for l in UD:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='U')and(b[1]=='D'):
            safe = False
            ans = min(ans,(b[0] - a[0])*5)

  for l in LR:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='R')and(b[1]=='L'):
            safe = False
            ans = min(ans,(b[0] - a[0])*5)


  for l in UR:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='U')and(b[1]=='R'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  for l in DL:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='L')and(b[1]=='D'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  for l in UL:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='U')and(b[1]=='L'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  for l in DR:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='R')and(b[1]=='D'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  if safe:
    print('SAFE')
  else:
    print(ans)
    
main()

Solution (Python):
def get_collision(A,ans):
    A.sort()
    nowkey = -10**10
    prevcoor = -10**10
    ret = ans[0]
    for key, coor, a in A:
        if key != nowkey:
            if a == 1:
                nowkey = key
                prevcoor = coor
                continue
            else:
                continue
        if a == 1:
            prevcoor = coor
            continue
        if (coor - prevcoor)*5 < ret:
            ret = (coor - prevcoor)*5
    ans[0] = ret

def main():
    N = int( input())
    XYU = [ tuple( input().split()) for _ in range(N)]
    U = []
    R = []
    D = []
    L = []
    for x, y, u in XYU:
        x, y = int(x), int(y)
        if u == "U":
            U.append((x,y))
        elif u == "D":
            D.append((x,y))
        elif u == "L":
            L.append((x,y))
        else:
            R.append((x,y))
    ans = [10**10]

    UD = [(x,y,1) for x, y in U] + [(x,y,-1) for x, y in D]
    get_collision(UD, ans)
    LR = [(y,x,1) for x, y in R] + [(y,x,-1) for x, y in L]
    get_collision(LR, ans)
    RU = [(x+y,x-y,1) for x, y in R] + [(x+y,x-y,-1) for x,y in U]
    get_collision(RU, ans)
    LD = [(x+y,x-y,1) for x, y in D] + [(x+y,x-y,-1) for x,y in L]
    get_collision(LD,ans)
    LU = [(x-y,x+y,1) for x,y in U] + [(x-y,x+y,-1) for x,y in L]
    get_collision(LU,ans)
    RD = [(x-y,x+y,1) for x,y in R] + [(x-y,x+y,-1) for x,y in D]
    get_collision(RD,ans)
    if ans[0] < 10**10:
        print(ans[0])
    else:
        print("SAFE")
        
if __name__ == '__main__':
    main()

Solution (Python):
def main():
    def calc(v, w, i, j, ans):
        if v > 0:
            i[0] += 1
        elif v < 0:
            j[0] += 1
        else:
            if w > 0:
                ans[0] = min(ans[0], w)
                i[0] += 1
            else:
                j[0] += 1

    n = int(input())
    inf = 10**10
    ans = [inf]
    u_list, d_list, l_list, r_list = [], [], [], []
    for _ in range(n):
        x, y, d = input().split()
        x, y = int(x), int(y)
        if d == "D":
            d_list.append((x, y))
        elif d == "R":
            r_list.append((x, y))
        elif d == "L":
            l_list.append((x, y))
        else:
            u_list.append((x, y))
    ld, lr, ll, lu = len(d_list), len(r_list), len(l_list), len(u_list)
    
    u_list.sort(key=lambda x: (x[0], x[1]))
    d_list.sort(key=lambda x: (x[0], x[1]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < ld):
        x, y = u_list[i[0]]
        p, q = d_list[j[0]]
        v = p-x
        w = (q-y)*5
        calc(v, w, i, j, ans)
    
    r_list.sort(key=lambda x: (x[1], x[0]))
    l_list.sort(key=lambda x: (x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < lr and j[0] < ll):
        x, y = r_list[i[0]]
        p, q = l_list[j[0]]
        v = q-y
        w = (p-x)*5
        calc(v, w, i, j, ans)
    
    u_list.sort(key=lambda x: (x[0]-x[1], x[0]))
    l_list.sort(key=lambda x: (x[0]-x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < ll):
        x, y = u_list[i[0]]
        p, q = l_list[j[0]]
        v = (p-q)-(x-y)
        w = (p-x)*10
        calc(v, w, i, j, ans)
    
    d_list.sort(key=lambda x: (x[0]+x[1], x[0]))
    l_list.sort(key=lambda x: (x[0]+x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < ld and j[0] < ll):
        x, y = d_list[i[0]]
        p, q = l_list[j[0]]
        v = (p+q)-(x+y)
        w = (p-x)*10
        calc(v, w, i, j, ans)
    
    u_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < lr):
        x, y = u_list[i[0]]
        p, q = r_list[j[0]]
        v = (p+q)-(x+y)
        w = (x-p)*10
        calc(v, w, i, j, ans)
    
    d_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    i, j = [0], [0]
    while(i[0] < ld and j[0] < lr):
        x, y = d_list[i[0]]
        p, q = r_list[j[0]]
        v = (p-q)-(x-y)
        w = (x-p)*10
        calc(v, w, i, j, ans)
    if ans == [inf]:
        print("SAFE")
    else:
        print(ans[0])


main()

Solution (Python):
from collections import defaultdict


def solve():
    N = int(input())
    X, Y = defaultdict(list), defaultdict(list)
    dx, dy = defaultdict(list), defaultdict(list)
    for i in range(N):
        x, y, U = list(input().split())
        x, y = int(x), int(y)
        X[x].append((y, U))
        Y[y].append((x, U))
        dy[x+y].append((x-y, U))
        dx[x-y].append((x+y, U))
    ans = float("inf")
    for key in X.keys():
        X[key].sort()
        for i in range(1, len(X[key])):
            y1, dir1 = X[key][i-1]
            y2, dir2 = X[key][i]
            if dir1 == "U" and dir2 == "D":
                ans = min(ans, 5*y2-5*y1)
    for key in Y.keys():
        Y[key].sort()
        for i in range(1, len(Y[key])):
            y1, dir1 = Y[key][i-1]
            y2, dir2 = Y[key][i]
            if dir1 == "R" and dir2 == "L":
                ans = min(ans, 5*y2-5*y1)
    for key in dx.keys():
        dx[key].sort()
        for i in range(1, len(dx[key])):
            y1, dir1 = dx[key][i-1]
            y2, dir2 = dx[key][i]
            if (dir1 == "U" and dir2 == "L") or (dir1 == "R" and dir2 == "D"):
                ans = min(ans, 5*y2-5*y1)
    for key in dy.keys():
        dy[key].sort()
        for i in range(1, len(dy[key])):
            y1, dir1 = dy[key][i-1]
            y2, dir2 = dy[key][i]
            if (dir1 == "R" and dir2 == "U") or(dir1 == "D" and dir2 == "L"):
                ans = min(ans, 5*y2-5*y1)
    if ans == float("inf"):
        print("SAFE")
    else:
        print(ans)


if __name__ == "__main__":
    solve()