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())
plane = [0] * N
houkou = ["U", "D", "R", "L"]
up = []
down = []
right = []
left =[]
for i in range(N):
  x, y, p = list(map(str, input().split()))
  x = int(x)
  y = int(y)
  p2 = houkou.index(p)
  plane[i] = [x, y, x + y, x - y, p2]
  

plane = sorted(plane, key=lambda x:x[1])
plane = sorted(plane, key=lambda x:x[0])

time = 10 ** 10
for k in range(1, N):
    if plane[k][0] == plane[k - 1][0]:
      if plane[k][1] > plane[k - 1][1]:
        if (plane[k][4] == 1) and (plane[k - 1][4] == 0):
          time2 = (plane[k][1] - plane[k - 1][1]) / 0.2
          time = min(time, time2)
      else:
        if (plane[k][4] == 0) and (plane[k - 1][4] == 1):
          time2 = (plane[k - 1][1] - plane[k][1]) / 0.2
          time = min(time, time2)
        

plane = sorted(plane, key=lambda x:x[0])
plane = sorted(plane, key=lambda x:x[1])
for k in range(1, N):
    if plane[k][1] == plane[k - 1][1]:
      if plane[k][0] > plane[k - 1][0]:
        if (plane[k][4] == 3) and (plane[k - 1][4] == 2):
          time2 = (plane[k][0] - plane[k - 1][0]) / 0.2
          time = min(time, time2)
      else:
        if (plane[k][4] == 2) and (plane[k - 1][4] == 3):
          time2 = (plane[k - 1][0] - plane[k][0]) / 0.2
          time = min(time, time2)

def go(x, y, u, t):
  if u == 0:
    return x, int(y + t * 0.1)
  elif u== 1:
    return x, int(y - t * 0.1)
  elif u == 2:
    return int(x + t * 0.1), y
  else:
    return int(x - t * 0.1), y
  
          

plane = sorted(plane, key=lambda x:x[2])
for k in range(1, N):
    one = plane[k]
    two = plane[k - 1]
                
    if plane[k][2] == plane[k - 1][2]:
      time2 = abs(one[0] - two[0]) / 0.1
      max_x = max(one[0],two[0])
      min_x = min(one[0], two[0])
      max_y = max(one[1], two[1])
      min_y = min(one[1], two[1])
      L = [[max_x, max_y], [min_x, min_y]]
      
      k_x, k_y = go(one[0], one[1], one[4], time2)
      
      k2_x, k2_y = go(two[0], two[1], two[4], time2)
      if [k_x, k_y] in L:
        if [k2_x, k2_y] in L:
          if [k_x, k_y] == [k2_x, k2_y]:
            time = min(time, time2)
          

plane = sorted(plane, key=lambda x:x[3])

for k in range(1, N):
    one = plane[k]
    two = plane[k - 1]
                
    if plane[k][3] == plane[k - 1][3]:
      time2 = abs(one[0] - two[0]) / 0.1
      max_x = max(one[0],two[0])
      min_x = min(one[0], two[0])
      max_y = max(one[1], two[1])
      min_y = min(one[1], two[1])
      L = [[max_x, min_y], [min_x, max_y]]
      
      k_x, k_y = go(one[0], one[1], one[4], time2)
      
      k2_x, k2_y = go(two[0], two[1], two[4], time2)
      if [k_x, k_y] in L:
        if [k2_x, k2_y] in L:
          if [k_x, k_y] == [k2_x, k2_y]:
            time = min(time, time2)          
            
if time == 10 ** 10:
  print("SAFE")
else:
  print(int(time))

Solution (Python):
N = int(input())

MAX = 200000;
NEVER_T = (MAX + 1) * 10;

planesH = [[] for _ in range(MAX + 1)]
planesV = [[] for _ in range(MAX + 1)]
planes45 = [[] for _ in range(MAX * 2 + 1)]
planes135 = [[] for _ in range(MAX * 2 + 1)]

for _ in range(N):
	X, Y, U = input().strip().split()
	X = int(X)
	Y = int(Y)
	planes45[MAX + X - Y].append((X, U));
	planes135[X + Y].append((X, U));
	if U == 'U' or U == 'D':
		planesV[X].append((Y, U));
	else:
		planesH[Y].append((X, U));

def search(group, U1, U2, minT, t):
	last = -1;
	for plane in group:
		U = plane[1]
		if U == U1:
			last = plane[0]
		elif U == U2:
			if last >= 0:
				T = (plane[0] - last) * t
				if minT > T:
					minT = T
	return minT

minT = NEVER_T
for group in planes45:
	if len(group) > 0:
		group.sort()
		minT = search(group, 'U', 'L', minT, 10);
		minT = search(group, 'R', 'D', minT, 10);

for group in planes135:
	if len(group) > 0:
		group.sort()
		minT = search(group, 'D', 'L', minT, 10);
		minT = search(group, 'R', 'U', minT, 10);

for group in planesH:
	if len(group) > 0:
		group.sort()
		minT = search(group, 'R', 'L', minT, 5);

for group in planesV:
	if len(group) > 0:
		group.sort()
		minT = search(group, 'U', 'D', minT, 5);


if minT < NEVER_T:
	print(minT)
else:
	print("SAFE")

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

from collections import defaultdict

N = int(input())

S = 'RULD'

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

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

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

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

P = []
for _ in range(N):
	x, y, d = input().split()
	P.append((int(x), int(y), d))

def rotate(s):
	return (-s[1], s[0], S[(S.index(s[2])+1)%4])

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

for trial in range(4):
	P.sort(key=lambda v: v[0])

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

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

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

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

Solution (Python):
import numpy as np
import sys
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

d = {b"U": 0, b"R": 1, b"D": 2, b"L": 3}


def f(x):
    if x in d.keys():
        return d[x]
    return int(x) - 100000


INF = 10 ** 18
n = int(readline())
inp = np.array(list(map(f, read().split())), np.int64)
x = inp[::3]
y = inp[1::3]
u = inp[2::3]


def ur(x, y, u):
    UX = x[u == 0]
    UY = y[u == 0]
    RX = x[u == 1]
    RY = y[u == 1]

    dct = defaultdict(list)
    for ex, ey in zip(UX, UY):
        dct[ex+ey].append([ey, 0])
    for ex, ey in zip(RX, RY):
        dct[ex+ey].append([ey, 1])

    ret = INF
    for v in dct.values():
        vv = sorted(v)
        for (e1, d1), (e2, d2) in zip(vv, vv[1:]):
            if d1 == 0 and d2 == 1:
                ret = min(ret, (e2 - e1) * 10)

    return ret


def ud(x, y, u):
    UX = x[u == 0]
    UY = y[u == 0]
    DX = x[u == 2]
    DY = y[u == 2]

    dct = defaultdict(list)
    for ex, ey in zip(UX, UY):
        dct[ex].append([ey, 0])
    for ex, ey in zip(DX, DY):
        dct[ex].append([ey, 2])

    ret = INF
    for v in dct.values():
        vv = sorted(v)
        for (e1, d1), (e2, d2) in zip(vv, vv[1:]):
            if d1 == 0 and d2 == 2:
                ret = min(ret, (e2 - e1) * 5)

    return ret


def rotate(x, y, u):
    x, y = y, -x
    u = (u + 1) % 4
    return x, y, u


ans = INF
for _ in range(4):
    ans = min(ans, ur(x, y, u), ud(x, y, u))
    x, y, u = rotate(x, y, u)

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

Solution (Python):
import numpy as np
import sys
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

d = {b"U": 0, b"R": 1, b"D": 2, b"L": 3}


def f(x):
    if x in d.keys():
        return d[x]
    return int(x) - 100000


INF = 10 ** 18
n = int(readline())
inp = np.array(list(map(f, read().split())), np.int64)
x = inp[::3]
y = inp[1::3]
u = inp[2::3]


def ur(x, y, u):
    UX = x[u == 0]
    UY = y[u == 0]
    RX = x[u == 1]
    RY = y[u == 1]

    dct = defaultdict(list)
    for ex, ey in zip(UX, UY):
        dct[ex+ey].append([ey, 0])
    for ex, ey in zip(RX, RY):
        dct[ex+ey].append([ey, 1])

    ret = INF
    for v in dct.values():
        vv = sorted(v)
        for (e1, d1), (e2, d2) in zip(vv, vv[1:]):
            if d1 == 0 and d2 == 1:
                ret = min(ret, (e2 - e1) * 10)

    return ret


def ud(x, y, u):
    UX = x[u == 0]
    UY = y[u == 0]
    DX = x[u == 2]
    DY = y[u == 2]

    dct = defaultdict(list)
    for ex, ey in zip(UX, UY):
        dct[ex].append([ey, 0])
    for ex, ey in zip(DX, DY):
        dct[ex].append([ey, 2])

    ret = INF
    for v in dct.values():
        vv = sorted(v)
        for (e1, d1), (e2, d2) in zip(vv, vv[1:]):
            if d1 == 0 and d2 == 2:
                ret = min(ret, (e2 - e1) * 5)

    return ret


def transpose(x, y, u):
    x, y = y, -x
    u = (u + 1) % 4
    return x, y, u


ans = INF
for _ in range(4):
    ans = min(ans, ur(x, y, u), ud(x, y, u))
    x, y, u = transpose(x, y, u)

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

Solution (Python):


import sys
read = sys.stdin.read
readline = sys.stdin.readline

n, = map(int, readline().split())

M = 2*10**5+2
Uy = {}
Dy = {}
Rx = {}
Lx = {}

d1U = {} 
d1R = {} 
d2U = {} 
d2L = {} 
d3L = {} 
d3D = {} 
d4D = {} 
d4R = {} 

for _ in range(n):
    x,y,z = readline().split()
    x = int(x); y = int(y)
    if z=="U":
        ss,dp,dn = Uy,d1U,d2U
    elif z=="D":
        ss,dp,dn = Dy,d3D,d4D
    elif z=="R":
        ss,dp,dn = Rx,d1R,d4R
    elif z=="L":
        ss,dp,dn = Lx,d3L,d2L
    
    v = x+y
    if v in dp: dp[v].append(x)
    else: dp[v] = [x]

    v = x-y
    if v in dn: dn[v].append(x)
    else: dn[v] = [x]
    
    if z=="U" or z=="D": x,y = y,x
    if y in ss: ss[y].append(x)
    else: ss[y] = [x]
    
def get(a,b,r):
    a.sort()
    b.sort()
    v = INF
    lb = len(b)
    j = 0
    for ai in a:
        while j < lb and b[j] < ai:
            j += 1
        if j < lb:
            v = min(v,b[j]-ai)
    return v*r

INF = 1<<30
ans = INF

for D1,D2,r in [(Uy,Dy,5),(Rx,Lx,5),(d1R,d1U,10),(d2U,d2L,10),(d3D,d3L,10),(d4R,d4D,10)]:
    for k,lst in D1.items():
        if k in D2:
            ans = min(ans,get(lst,D2[k],r))

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

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

Solution (Python):


import sys
read = sys.stdin.read
readline = sys.stdin.readline

n, = map(int, readline().split())

M = 2*10**5+2
Uy = [[] for _ in range(M)]
Dy = [[] for _ in range(M)]

Rx = [[] for _ in range(M)]
Lx = [[] for _ in range(M)]

d1U = {} 
d1R = {} 
d2U = {} 
d2L = {} 
d3L = {} 
d3D = {} 
d4D = {} 
d4R = {} 

for _ in range(n):
    x,y,z = readline().split()
    x = int(x); y = int(y)
    if z=="U":
        Uy[x].append(y)
        dp,dn = d1U,d2U
    elif z=="D":
        Dy[x].append(y)
        dp,dn = d3D,d4D
    elif z=="R":
        Rx[y].append(x)
        dp,dn = d1R,d4R
    elif z=="L":
        Lx[y].append(x)
        dp,dn = d3L,d2L
    
    v = x+y
    if v in dp: dp[v].append(x)
    else: dp[v] = [x]
    v = x-y
    if v in dn: dn[v].append(x)
    else: dn[v] = [x]

def get(a,b):
    v = INF
    lb = len(b)
    j = 0
    for ai in a:
        while j < lb and b[j] < ai:
            j += 1
        if j < lb:
            v = min(v,b[j]-ai)
    return v

def syoumen(lst1,lst2):
    v = INF
    for i in range(M):
        if lst1[i] and lst2[i]:
            lst1[i].sort()
            lst2[i].sort()
            v = min(v,get(lst1[i],lst2[i]))
    return v*5

def naname(d1,d2):
    v = INF
    for i in range(-2*M,2*M):
        if i in d1 and i in d2:
            d1[i].sort()
            d2[i].sort()
            v = min(v,get(d1[i],d2[i]))
    return v*10

INF = 1<<30
ans = INF

ans = min(ans,syoumen(Uy,Dy))
ans = min(ans,syoumen(Rx,Lx))

ans = min(ans,naname(d1R,d1U))
ans = min(ans,naname(d2U,d2L))
ans = min(ans,naname(d3D,d3L))
ans = min(ans,naname(d4R,d4D))

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

Solution (Python):
import sys
from collections import defaultdict as dd
input = sys.stdin.readline
N = int(input())
a = []
for _ in range(N):
  x, y, d = input().split()
  x, y = map(int, (x, y))
  a.append((x, y, d))
a.sort()
c = dd(lambda: -1)
res = float("inf")
for x, y, d in a:
  if d == "R": c[y] = x
  if d == "L":
    if c[y] >= 0:
      res = min(res, (x - c[y]) * 5)
      c[y] = -1
c = dd(lambda: -1)
a.sort(key = lambda x: x[1])
for x, y, d in a:
  if d == "U": c[x] = y
  if d == "D":
    if c[x] >= 0:
      res = min(res, (y - c[x]) * 5)
      c[x] = -1

for i in range(N):
  a[i] = (a[i][0] + a[i][1], a[i][0] - a[i][1], a[i][2])
a.sort()
c = dd(lambda: -float("inf"))
for x, y, d in a:
  if d == "R": c[y] = x
  if d == "D":
    if c[y] != -float("inf"):
      res = min(res, (x - c[y]) * 5)
      c[y] = -float("inf")
c = dd(lambda: -float("inf"))
for x, y, d in a:
  if d == "U": c[y] = x
  if d == "L":
    if c[y] != -float("inf"):
      res = min(res, (x - c[y]) * 5)
      c[y] = -float("inf")
a.sort(key = lambda x: x[1])
c = dd(lambda: -float("inf"))
for x, y, d in a:
  if d == "R": c[x] = y
  if d == "U":
    if c[x] != -float("inf"):
      res = min(res, (y - c[x]) * 5)
      c[x] = -float("inf")
c = dd(lambda: -float("inf"))
for x, y, d in a:
  if d == "D": c[x] = y
  if d == "L":
    if c[x] != -float("inf"):
      res = min(res, (y - c[x]) * 5)
      c[x] = -float("inf")

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

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

INF = 10**18

N = int(input())
X = [0] * N
Y = [0] * N
U = [''] * N
for i in range(N):
    x, y, u = input().split()
    X[i] = int(x)
    Y[i] = int(y)
    U[i] = u
M = 200000

def rotate():
    s = 'ULDR'
    for i in range(N):
        X[i], Y[i] = M - Y[i], X[i]
        U[i] = s[(s.index(U[i]) + 1) % 4]

def calc1():
    v = [[] for _ in range(M+1)]
    for x, y, u in zip(X, Y, U):
        if u in 'RL':
            v[y].append((x, u))
    ret = INF
    for y in range(M+1):
        v[y].sort(key=lambda p: p[0])
        for i in range(len(v[y])-1):
            if v[y][i][1] == 'R' and v[y][i+1][1] == 'L':
                ret = min(ret, (v[y][i+1][0] - v[y][i][0]) * 5)
    return ret

def calc2():
    v = [[] for _ in range(2*M+1)]
    for x, y, u in zip(X, Y, U):
        if u in 'UR':
            v[x+y].append((x, u))
    ret = INF
    for xy in range(2*M+1):
        v[xy].sort(key=lambda p: p[0])
        for i in range(len(v[xy])-1):
            if v[xy][i][1] == 'R' and v[xy][i+1][1] == 'U':
                ret = min(ret, (v[xy][i+1][0] - v[xy][i][0]) * 10)
    return ret

ans = INF
for i in range(4):
    ans = min(ans, calc1(), calc2())
    rotate()
print(ans if ans < INF else 'SAFE')

Solution (Python):


import math

import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd

import bisect
n=int(input())
arr=[list(input().split()) for _ in range(n)]
yaxis={}
xaxis={}
s1axis={}
s2axis={}
t1axis={}
t2axis={}

t=list()

for i in range(n):
    x,y,u=arr[i]
    x=int(x)
    y=int(y)
    if u=="U" or u=="R":
        if x+y not in s1axis:
            s1axis[x+y]=[[y,u]]
        else:
            s1axis[x+y].append([y,u])
    if u=="D" or u=="L":
        if x+y not in s2axis:
            s2axis[x+y]=[[y,u]]
        else:
            s2axis[x+y].append([y,u])
    if u=="U" or u=="L":
        if y-x not in t1axis:
            t1axis[y-x]=[[y,u]]
        else:
            t1axis[y-x].append([y,u])
    if u=="D" or u=="R":
        if y-x not in t2axis:
            t2axis[y-x]=[[y,u]]
        else:
            t2axis[y-x].append([y,u])
    if u=="U" or u=="D":
        if x in xaxis:
            xaxis[x].append([y,u])
        else:
            xaxis[x]=[[y,u]]
    else:
        if y in yaxis:
            yaxis[y].append([x,u])
        else:
            yaxis[y]=[[x,u]]

for s in xaxis:
    s=sorted(xaxis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="U" and s[k][1]=="D":
            time=(s[k][0]-s[k-1][0])*5
            heapq.heappush(t,time)
for s in yaxis:
    s=sorted(yaxis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="R" and s[k][1]=="L":
            time=(s[k][0]-s[k-1][0])*5
            heapq.heappush(t,time)
for s in s1axis:
    s=sorted(s1axis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="U" and (s[k][1]=="R" or s[k][1]=="L"):
            time=10*(s[k][0]-s[k-1][0])
            heapq.heappush(t,time)

for s in s2axis:
    s=sorted(s2axis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="L" and s[k][1]=="D":
            time=10*(s[k][0]-s[k-1][0])
            heapq.heappush(t,time)
 
for s in t1axis:
    s=sorted(t1axis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="U" and s[k][1]=="L":
            time=10*(s[k][0]-s[k-1][0])
            heapq.heappush(t,time)

for s in t2axis:
    s=sorted(t2axis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="R" and s[k][1]=="D":
            time=10*(s[k][0]-s[k-1][0])
            heapq.heappush(t,time)
if not t:
  print("SAFE")
else:
  print(heapq.heappop(t))

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

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

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

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

def into_dict(dics,x,y,u):
  x,y = int(x),int(y)
  insort(dics[u+'_x'][x],y)
  insort(dics[u+'_y'][y],x)
  insort(dics[u+'_xpy'][x+y],x)
  insort(dics[u+'_ymx'][y-x],x)
  return dics

def para(dics,dic1,dic2):
  ans = float('inf')
  for k,v in dics[dic1].items():
    for zahyou in v[1:-1]:
      ind = bisect_right(dics[dic2][k],zahyou)
      dis = zahyou-dics[dic2][k][ind-1]
      ans = min(ans,dis)
  return ans

import sys; input=sys.stdin.readline
def solve():
  ans = []
  N = int(input())
  dics = defaultdict(lambda: defaultdict(lambda: [-float('inf'),float('inf')]))
  for i in range(N):
    dics = into_dict(dics,*input().split())
  lis1 = [['L_y','R_y'],['D_x','U_x']]
  lis2 = [['L_ymx','U_ymx'],['U_xpy','R_xpy'],['L_xpy','D_xpy'],['D_ymx','R_ymx']]
  for arg in lis1:
    ans.append(para(dics,*arg)*5)
  for arg in lis2:
    ans.append(para(dics,*arg)*10)
  ans = min(ans)
  return ans if ans<float('inf') else 'SAFE'
print(solve())

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

def into_dict(dics,x,y,u):
  x,y = int(x),int(y)
  insort(dics[u+'_x'][x],y)
  insort(dics[u+'_y'][y],x)
  insort(dics[u+'_xpy'][x+y],x)
  insort(dics[u+'_ymx'][y-x],x)
  return dics

def para(dics,dic1,dic2):
  ans = float('inf')
  for k,v in dics[dic1].items():
    for zahyou in v[1:-1]:
      ind = bisect_right(dics[dic2][k],zahyou)
      dis = zahyou-dics[dic2][k][ind-1]
      ans = min(ans,dis)
  return ans

def solve():
  ans = []
  N = int(input())
  dics = defaultdict(lambda: defaultdict(lambda: [-float('inf'),float('inf')]))
  for i in range(N):
    dics = into_dict(dics,*input().split())
  lis1 = [['L_y','R_y'],['D_x','U_x']]
  lis2 = [['L_ymx','U_ymx'],['U_xpy','R_xpy'],['L_xpy','D_xpy'],['D_ymx','R_ymx']]
  for arg in lis1:
    ans.append(para(dics,*arg)*5)
  for arg in lis2:
    ans.append(para(dics,*arg)*10)
  ans = min(ans)
  return ans if ans<float('inf') else 'SAFE'
print(solve())

Solution (Python):
from collections import defaultdict
n = int(input())
x = []
y = []
p = []

INF = 1e18


def ff(p):
    pp = sorted(p, key= lambda x: x[0])
    res = INF
    for i in range(1,len(pp)):
        if (pp[i-1][1] == 0 and pp[i][1] !=0):
            res = min(res, pp[i][0] - pp[i-1][0])
    return res

def f(d):
    res = INF
    for k in d.values():
        res = min(res,ff(k))
    return res

for i in range(n):
    i1, i2, i3 = input().split()
    x.append(int(i1))
    y.append(int(i2))
    if (i3 == 'U'):
        p.append(0)
    elif (i3 == 'R'):
        p.append(1)        
    elif (i3 == 'D'):
        p.append(2)
    else:
        p.append(3) 

ans = INF

for _ in range(4):
    d = defaultdict(list)
    for i in range(n):
        if p[i] != 0 and p[i]!= 2:
            continue
        d[x[i]].append((y[i],p[i]))
    ans = min(ans,f(d)*5)

    d = defaultdict(list)
    for i in range(n):
        if p[i] != 0 and p[i]!= 1:
            continue
        d[x[i]+y[i]].append((y[i],p[i]))
    ans = min(ans,f(d)*10)

    for i in range(n):
        px, py = x[i], y[i]
        x[i], y[i] = py, -px
        p[i] = (p[i]+1)%4  

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

Solution (Python):
import bisect
def main():
    N = int(input())
    dx = {}
    dy = {}
    dxpy = {}
    dxmy = {}
    for _ in range(N):
        x, y, u = input().split()
        x = int(x)
        y = int(y)
        if u in dx:
            if x in dx[u]:
                dx[u][x].append(y)
            else:
                dx[u][x] = [y]
            if y in dy[u]:
                dy[u][y].append(x)
            else:
                dy[u][y] = [x]
            if x + y in dxpy[u]:
                dxpy[u][x+y].append(y)
            else:
                dxpy[u][x+y] = [y]
            if x - y in dxmy[u]:
                dxmy[u][x-y].append(y)
            else:
                dxmy[u][x-y] = [y]
        else:
            dx[u] = {}
            dx[u][x] = [y]
            dy[u] = {}
            dy[u][y] = [x]
            dxpy[u] = {}
            dxpy[u][x+y] = [y]
            dxmy[u] = {}
            dxmy[u][x-y] = [y]
    for d in [dx, dy, dxpy, dxmy]:
        for j in d:
            for k in d[j]:
                d[j][k].sort()
    M = 3 * (10**6)
    
    
    if "U" in dx and "D" in dx:
        for x in dx["U"]:
            if x not in dx["D"]:
                continue
            for y in dx["U"][x]:
                yi = bisect.bisect_left(dx["D"][x], y)
                if yi < len(dx["D"][x]):
                    M = min((dx["D"][x][yi] - y)*5, M)
    
    if "L" in dy and "R" in dy:
        for y in dy["R"]:
            if y not in dy["L"]:
                continue
            for x in dy["R"][y]:
                xi = bisect.bisect_left(dy["L"][y], x)
                if xi < len(dy["L"][y]):
                    M = min((dy["L"][y][xi] - x)*5, M)
    
    
    if "D" in dy and "R" in dy:
        for s in dxmy["R"]:
            if s not in dxmy["D"]:
                continue
            for p in dxmy["R"][s]:
                yi = bisect.bisect_left(dxmy["D"][s], p)
                if yi < len(dxmy["D"][s]):
                    M = min((dxmy["D"][s][yi] - p)*10, M)
    
    if "L" in dy and "U" in dy:
        for s in dxmy["U"]:
            if s not in dxmy["L"]:
                continue
            for p in dxmy["U"][s]:
                yi = bisect.bisect_left(dxmy["L"][s], p)
                if yi < len(dxmy["L"][s]):
                    M = min((dxmy["L"][s][yi] - p)*10, M)
    
    if "U" in dy and "R" in dy:
        for s in dxpy["U"]:
            if s not in dxpy["R"]:
                continue
            for p in dxpy["U"][s]:
                yi = bisect.bisect_left(dxpy["R"][s], p)
                if yi < len(dxpy["R"][s]):
                    M = min((dxpy["R"][s][yi] - p)*10, M)
    
    if "D" in dy and "L" in dy:
        for s in dxpy["L"]:
            if s not in dxpy["D"]:
                continue
            for p in dxpy["L"][s]:
                yi = bisect.bisect_left(dxpy["D"][s], p)
                if yi < len(dxpy["D"][s]):
                    M = min((dxpy["D"][s][yi] - p)*10, M)
    return M
x = main()
if x < 3 * (10**6):
    print(x)
else:
    print('SAFE')

Solution (Python):
n = int(input())
xx = [[] for _ in range(200001)]
yy = [[] for _ in range(200001)]
xy = [[] for _ in range(400001)]
yx = [[] for _ in range(200001)]
for _ in range(n):
    x, y, u = input().split()
    if u=='U' or u=='D':
        xx[int(x)].append((int(y), u))
    else:
        yy[int(y)].append((int(x), u))
    xy[int(x)+int(y)].append((int(x), u))
    yx[int(y)-int(x)].append((int(x), u))
ans = 10**10
for i in xx:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='U':
            d = j
        elif ans > (j-d)*5:
            ans = (j-d)*5
for i in yy:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='R':
            d = j
        elif ans > (j-d)*5:
            ans = (j-d)*5
for i in xy:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='R':
            d = j
        elif k=='U' and ans > (j-d)*10:
            ans = (j-d)*10
    d = -10**10
    for j, k in i:
        if k=='D':
            d = j
        elif k=='L' and ans > (j-d)*10:
            ans = (j-d)*10
for i in yx:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='U':
            d = j
        elif k=='L' and ans > (j-d)*10:
            ans = (j-d)*10
    d = -10**10
    for j, k in i:
        if k=='R':
            d = j
        elif k=='D' and ans > (j-d)*10:
            ans = (j-d)*10
if ans == 10**10:
    print('SAFE')
else:
    print(ans)

Solution (Python):
I=N=9**9
d=[[],[],[],[]]
for t in[*open(0)][1:]:
  *z,u=t.split()
  d[ord(u)%5]+=[*map(int,z)],
f=lambda x,y:x
g=lambda x,y:y
h=lambda x,y:x+y
i=lambda x,y:x-y
for*A,f,g in(3,0,f,g),(1,2,g,f),(0,2,h,i),(1,3,h,i),(1,0,i,h),(3,2,i,h):
  n=p=-I
  for x,y,r in sorted((f(x,y),g(x,y),Q)for Q,P in enumerate(A)for x,y in d[P]):
    if r:n,p=x,y
    elif x==n:N=min(N,y-p)
print(N%I*5or'SAFE')

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

Solution (Python):
I=N=9**9
L,R,U,*D=[],[],[]
for t in[*open(0)][1:]:*z,u=t.split();exec(u+'+=[*map(int,z)],')
def z(S,*A):
 global N;n=p=-I
 for x,y,r in eval('sorted((%s,Q)for Q,P in enumerate(A)for x,y in eval(P))'%S):
  if r:n,p=x,y
  elif x==n:N=min(N,y-p)
for A,B,*S in"DU,","UR+y,x-","LD+y,x-","LU-y,x+","DR-y,x+":z("x%sy"%"".join(S),A,B)
z("y,x","L","R")
print(N%I*5or'SAFE')

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

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

dis = 10 ** 19 


box = {"U":defaultdict(list),"D":defaultdict(list),"L":defaultdict(list),"R":defaultdict(list)}

for x, y, u in XYU:
  x = int(x)
  y = int(y)
  if u in ["U","D"]:
    box[u][x].append(y) 
  else:
    box[u][y].append(x)
    
for k1 in box.keys():
  for k2 in box[k1].keys():
    box[k1][k2] = sorted(box[k1][k2])
    
for k, v in box["U"].items():
  if k in box["D"]:
    for pos in v:
      if pos < box["D"][k][-1]:
        a = bisect_right(box["D"][k], pos)
        dis = min(dis, (box["D"][k][a] - pos) * 10 // 2)

for k, v in box["R"].items():
  if k in box["L"]:
    for pos in v:
      if pos < box["L"][k][-1]:  
        a = bisect_right(box["L"][k], pos)
        dis = min(dis, (box["L"][k][a] - pos) * 10 // 2)


cox = {"U":defaultdict(list),"D":defaultdict(list),"L":defaultdict(list),"R":defaultdict(list)}

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

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


dox = {"U":defaultdict(list),"D":defaultdict(list),"L":defaultdict(list),"R":defaultdict(list)}

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

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

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