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):
import sys
input = sys.stdin.readline
from collections import defaultdict
n = int(input())
UR = defaultdict(list)
UD = defaultdict(list)
UL = defaultdict(list)
DR = defaultdict(list)
DL = defaultdict(list)
RL = defaultdict(list)

for i in range(n):
    x,y,u = input().split()
    x,y = int(x), int(y)
    if u == "U":    
        UD[x].append((y,1))
        UR[x+y].append((x-y,0))
        UL[y-x].append((x+y,1))
    elif u == "D":    
        UD[x].append((y,0))
        DR[y-x].append((x+y,0))
        DL[x+y].append((x-y,1))
    elif u == "R":   
        RL[y].append((x,1))
        DR[y-x].append((x+y,1))
        UR[x+y].append((x-y,1))
        
    else:
        RL[y].append((x,0))
        UL[y-x].append((x+y,0))
        DL[x+y].append((x-y,0))

ans = float("INF")

for x in [UD, UL, UR, DR, DL, RL]:
    for v in x.values():
        V = sorted(v)

        for i in range(len(V)-1):
            if V[i][1] and not V[i+1][1]:
                ans = min(ans,V[i+1][0]-V[i][0])


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

Solution (Python):
import sys
input = sys.stdin.readline
from collections import defaultdict
n = int(input())
UR = defaultdict(list)
UD = defaultdict(list)
UL = defaultdict(list)
DR = defaultdict(list)
DL = defaultdict(list)
RL = defaultdict(list)

for i in range(n):
    x,y,u = input().split()
    x,y = int(x), int(y)
    if u == "U":    
        UD[x].append((y,1))
        UR[x+y].append((x-y,0))
        UL[y-x].append((x+y,1))
    elif u == "D":    
        UD[x].append((y,0))
        DR[y-x].append((x+y,0))
        DL[x+y].append((x-y,1))
    elif u == "R":   
        RL[y].append((x,1))
        DR[y-x].append((x+y,1))
        UR[x+y].append((x-y,1))
        
    else:
        RL[y].append((x,0))
        UL[y-x].append((x+y,0))
        DL[x+y].append((x-y,0))

ans = float("INF")

for x in [UD, UL, UR, DR, DL, RL]:
    for v in x.values():
        V = sorted(v)

        for i in range(len(V)-1):
            if V[i][1] and not V[i+1][1]:
                ans = min(ans,V[i+1][0]-V[i][0])


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

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 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):
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('%s+=[*map(int,z)],'%u)
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):
P,M,*d='x+y,','x-y,',[],[],[],[]
for t in[*open(0)][1:]:*z,u=t.split();d[ord(u)%5]+=[*map(int,z)],
I=N=9**9
for*A,S in(3,0,'x,y,'),(1,2,'y,x,'),(0,2,P+M),(1,3,P+M),(1,0,M+P),(3,2,M+P):
 n=p=-I
 for x,y,r in eval('sorted((%sQ)for Q,P in enumerate(A)for x,y in d[P])'%S):
  if r:n,p=x,y
  elif x==n:N=min(N,y-p)
print(N%I*5or'SAFE')

Solution (Python):
d=[[],[],[],[]]
for t in[*open(0)][1:]:*z,u=t.split();d[ord(u)%5]+=[*map(int,z)],
I=N=9**9
P,M='x+y,','x-y,'
for*A,S in(3,0,'x,y,'),(1,2,'y,x,'),(0,2,P+M),(1,3,P+M),(1,0,M+P),(3,2,M+P):
 n=p=-I
 for x,y,r in eval('sorted((%sQ)for Q,P in enumerate(A)for x,y in d[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
INF = 1 << 60
MOD = 10**9 + 7 
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect_left
def resolve():
    n = int(input())
    direction = {'U' : 0, 'R' : 1, 'D' : 2, 'L' : 3}
    X = defaultdict(lambda:[[] for _ in range(4)])
    Y = defaultdict(lambda:[[] for _ in range(4)])
    YminusX = defaultdict(lambda:[[] for _ in range(4)])
    XplusY = defaultdict(lambda:[[] for _ in range(4)])

    for _ in range(n):
        x, y, u = input().split()
        x = int(x)
        y = int(y)
        u = direction[u]
        X[x][u].append(y)
        Y[y][u].append(x)
        YminusX[y - x][u].append(x)
        XplusY[x + y][u].append(x)

    ans = INF

    for x in X:
        up = sorted(X[x][direction['U']])
        down = sorted(X[x][direction['D']])
        for u in up:
            idx = bisect_left(down, u)
            if idx == len(down):
                continue
            ans = min(ans, 5 * (down[idx] - u))

    for y in Y:
        right = sorted(Y[y][direction['R']])
        left = sorted(Y[y][direction['L']])
        for r in right:
            idx = bisect_left(left, r)
            if idx == len(left):
                continue
            ans = min(ans, 5 * (left[idx] - r))

    for c in YminusX:
        right = sorted(YminusX[c][direction['R']])
        down = sorted(YminusX[c][direction['D']])
        for r in right:
            idx = bisect_left(down, r)
            if idx == len(down):
                continue
            ans = min(ans, 10 * (down[idx] - r))
        up = sorted(YminusX[c][direction['U']])
        left = sorted(YminusX[c][direction['L']])
        for u in up:
            idx = bisect_left(left, u)
            if idx == len(left):
                continue
            ans = min(ans, 10 * (left[idx] - u))

    for c in XplusY:
        right = sorted(XplusY[c][direction['R']])
        up = sorted(XplusY[c][direction['U']])
        for r in right:
            idx = bisect_left(up, r)
            if idx == len(up):
                continue
            ans = min(ans, 10 * (up[idx] - r))
        down = sorted(XplusY[c][direction['D']])
        left = sorted(XplusY[c][direction['L']])
        for d in down:
            idx = bisect_left(left, d)
            if idx == len(left):
                continue
            ans = min(ans, 10 * (left[idx] - d))

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

Solution (Python):
import sys
sys.setrecursionlimit(10**6)

INF = 1e8

UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3


def f(l):
    result = INF
    for v in l.values():
        v.sort()
        for i in range(1, len(v)):
            if(v[i-1][1] == UP and v[i][1] != UP):
                result = min(result, v[i][0]-v[i-1][0])
    return result


def main(input, print):
    N = int(input())

    table = [[0 for _ in range(3)] for _ in range(N)]
    for i in range(N):
        X, Y, U = map(str, input().split())
        table[i][0] = int(X)
        table[i][1] = int(Y)
        if U == 'U':
            table[i][2] = UP
        elif U == 'R':
            table[i][2] = RIGHT
        elif U == 'D':
            table[i][2] = DOWN
        elif U == 'L':
            table[i][2] = LEFT
    ans = INF
    for u in range(4):
        
        l = {}
        for i in range(N):
            if table[i][2] != UP and table[i][2] != DOWN:
                continue
            key = table[i][0]
            if key not in l:
                l[key] = []
            l[key].append((table[i][1], table[i][2]))
        ans = min(ans, f(l)*5)
        
        l = {}
        for i in range(N):
            if table[i][2] != UP and table[i][2] != RIGHT:
                continue
            key = table[i][0]+table[i][1]
            if key not in l:
                l[key] = []
            l[key].append((table[i][1], table[i][2]))
        ans = min(ans, f(l)*10)
        
        for i in range(N):
            temp = table[i][0]
            table[i][0] = table[i][1]
            table[i][1] = -temp
            table[i][2] = (table[i][2]+1) % 4
    if ans == INF:
        print('SAFE')
    else:
        print(ans)


if __name__ == '__main__':
    main(sys.stdin.readline, print)

Solution (Python):
from collections import defaultdict
from collections import deque
from collections import Counter
import itertools
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

n = readInt()
xyu = [readChars() for i in range(n)]

class mydict:
	def __init__(self):
		self.d = {}
	def add(self,key,value):
		if key in self.d:
			self.d[key].append(value)
		else:
			self.d[key]=[value]
	def p(self):
		print("{")
		for key in self.d:
			print(key,self.d[key])
		print("}")
	def mysort(self):
		for i in self.d:
			self.d[i].sort()
	def getDict(self):
		return self.d;

ud = mydict()
rl = mydict()
for x,y,u in xyu:
	if u=="U" or u=="D":
		ud.add(int(x),[int(y),u])
	else:
		rl.add(int(y),[int(x),u])
ud.mysort()
rl.mysort()


ans = float("inf")

tar = ud.getDict()
for key in tar:
	beu = "-1"
	bev = "-1"
	for v in tar[key]:
		if beu=="U" and v[1]=="D":
			ans = min(ans,(int(v[0])-int(bev))*5)
		beu = v[1]
		bev = v[0]
tar = rl.getDict()
for key in tar:
	s = ""
	beu = "-1"
	bev = "-1"
	for v in tar[key]:
		if beu=="R" and v[1]=="L":
			ans = min(ans,(int(v[0])-int(bev))*5)
		beu = v[1]
		bev = v[0]

xy = mydict()
for x,y,u in xyu:
	xy.add(int(x)+int(y),[int(x),u])

xy.mysort()
d = xy.getDict()
for key in d:
	beu = "-1"
	bex = -1
	for arr in d[key]:
		if beu=="R" and arr[1]=="U":
			ans = min(ans,(arr[0]-bex)*10)
		if beu=="D" and arr[1]=="L":
			ans = min(ans,(arr[0]-bex)*10)
		beu = arr[1]
		bex = arr[0]
mxy = mydict()
for x,y,u in xyu:
	mxy.add(int(y)-int(x),[int(x),u])
mxy.mysort()

d = mxy.getDict()
for key in d:
	beu = "-1"
	bex = -1
	for arr in d[key]:
		if beu=="R" and arr[1]=="D":
			ans = min(ans,(arr[0]-bex)*10)
		if beu=="U" and arr[1]=="L":
			ans = min(ans,(arr[0]-bex)*10)
		beu = arr[1]
		bex = arr[0]

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

Solution (Python):
s="URDL";d={i:[]for i in s}
_,*a=map(str.split,open(0))
for*z,u in a:d[u]+=[*map(int,z)],
I=N=9e9;P,M="x+y,","x-y,"
for*F,S in(2,0,"x,y,"),(3,1,"y,x,"),(0,1,P+M),(3,2,P+M),(3,0,M+P),(2,1,M+P):
 n=p=-I
 for x,y,r in sorted(eval(f"(({S}Q)for Q,P in enumerate(F)for x,y in d[s[P]])")):
  if r:n,p=x,y
  elif x==n:N=min(N,y-p)
print(["SAFE",N*5][N<I])

Solution (Python):
U,R,D,L="URDL"
d={i:[]for i in"URDL"}
_,*a=map(str.split,open(0))
for*z,u in a:d[u]+=[*map(int,z)],
I=N=9e9;P,M="x+y,","x-y,"
for*F,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 sorted(eval(f"[({S}Q)for Q,P in enumerate(F)for x,y in d[P]]")):
  if r:n,p=x,y
  elif x==n:N=min(N,y-p)
print(["SAFE",N*5][N<I])

Solution (Python):
U,R,D,L="URDL"
d={i:[]for i in"URDL"}
_,*a=map(str.split,open(0))
for*z,u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for*F,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=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for Q,P in enumerate(F)for x,y in d[P]]")):
  if r:n,p=x,y
  elif x==n:N=min(N,y-p)
print(["SAFE",N*5][N<9e9])

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L=S="URDL"
d={i:[]for i in S}
for*z,u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for*F,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=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for Q,P in enumerate(F)for x,y in d[P]]")):
  if r:n,p=x,y
  elif x==n:N=min(N,y-p)
print(["SAFE",N*5][N<9e9])

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L=S="URDL"
d={i:[]for i in S}
for*z,u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if r:n,p=x,y
  elif x==n:N=min(N,(y-p)*5)
print(["SAFE",N][N<9e9])

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L=S="URDL"
d={i:[]for i in S}
for*z,u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if r:n,p=x,y
  elif x==n:N=min(N,(y-p)*5)
print(["SAFE",N][N<9e9])

Solution (Python):
U,R,D,L="URDL"
d={i:[]for i in"URDL"}
_,*a=map(str.split,open(0))
for*z,u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for*F,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=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for Q,P in enumerate(F)for x,y in d[P]]")):
  if x-n:
   if r:n,p=x,y
  elif r:p=y
  else:N=min(N,y-p)
print(["SAFE",N*5][N<9e9])

Solution (Python):
U,R,D,L="URDL"
d={i:[]for i in"URDL"}
_,*a=map(str.split,open(0))
for*z,u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if x-n:
   if r:n,p=x,y
  elif r:p=y
  else:N=min(N,y-p)
print(["SAFE",N*5][N<9e9])

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L=S="URDL"
d={i:[]for i in S}
for *z,u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if r:n,p=x,y
  elif x==n:N=min(N,(y-p)*5)
print(["SAFE",N][N<9e9])

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L=S="URDL"
d={i:[]for i in S}
for *z, u in a:d[u]+=[*map(int,z)],
N,P,M=9e9,"x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if r:n,p=x,y
  elif x==n:N=min(N,(y-p)*5)
print(["SAFE",N][N<9e9])

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L="URDL"
d={i:[]for i in"URDL"}
for *z,u in a:d[u]+=[*map(int,z)],
N=9e9
P,M="x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if x-n:
   if r:n,p=x,y
  elif r:p=y
  else:N=min(N,y-p)
print(["SAFE",N*5][N<9e9])

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L="URDL"
d={i:[]for i in"URDL"}
for *z,u in a:d[u]+=[*map(int,z)],
N=9e9
P,M="x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if x-n:
   if r:n,p=x,y
  elif r:p=y
  else:N=min(N,y-p)
print(["SAFE",N*5][N!=9e9])

Solution (Python):
_, *a = map(str.split, open(0))
U, R, D, L = "URDL"
d = {}
for *z, u in a:d.setdefault(u, []).append([*map(int, z)])
N = 1e9
for A, B, S in [(U, D, "x, y"), (R, L, "y, x"), (R, U, "x+y, x-y"), (D, L, "x+y, x-y"), (U, L, "x-y, x+y"), (R, D, "x-y, x+y")]:
  n = p = -1e9
  L = eval(f"[({S}, Q) for P, Q in [(A, 1), (B, 0)] for x, y in d.get(P, [])]")
  for x, y, r in sorted(L):
    if r:n,p = x,y
    elif x==n:N = min(N, (y - p)*5)
print(N if N < 1e9 else "SAFE")

Solution (Python):
_,*a=map(str.split,open(0))
U,R,D,L="URDL"
d={i:[]for i in"URDL"}
for *z, u in a:d[u]+=[*map(int, z)],
N=9e9
P,M="x+y,","x-y,"
for A,B,S in(U,D,"x,y,"),(R,L,"y,x,"),(R,U,P+M),(D,L,P+M),(U,L,M+P),(R,D,M+P):
 n=p=-9e9
 for x,y,r in sorted(eval(f"[({S}Q)for P,Q in[(A,1),(B,0)]for x,y in d[P]]")):
  if x!=n:
   if r:n,p=x,y
  elif r:p=y
  else:N=min(N,(y-p)*5)
print(["SAFE",N][N!=9e9])

Solution (Python):
_, *a = map(str.split, open(0))
U, R, D, L = "URDL"
INF = float("inf")
d = {}
for *z, u in a:
  d.setdefault(u, []).append([*map(int, z)])
N = INF
for A, B, S in [(U, D, "x, y"), (R, L, "y, x"), 
                (R, U, "x+y, x-y"), (D, L, "x+y, x-y"), 
                (U, L, "x-y, x+y"), (R, D, "x-y, x+y")]:
  n = p = -INF
  L = eval(f"[({S}, Q) for P, Q in [(A, 1), (B, 0)] for x, y in d.get(P, [])]")
  for x, y, r in sorted(L):
    if r:n = x;p = y
    elif x==n :N = min(N, (y - p)*5)
print("SAFE" if N == INF else N)

Solution (Python):
_, *a = map(str.split, open(0))
U, R, D, L = "URDL"
INF = float("inf")
d = {}
for *z, u in a:
  d.setdefault(u, []).append([*map(int, z)])
N = INF
for A, B, S in [(U, D, "x, y"), (R, L, "y, x"), 
                (R, U, "x+y, x-y"), (D, L, "x+y, x-y"), 
                (U, L, "x-y, x+y"), (R, D, "x-y, x+y")]:
  n = p = -INF
  L = eval(f"[({S}, Q) for P, Q in [(A, 1), (B, 0)] for x, y in d.get(P, [])]")
  for x, y, r in sorted(L):
    if x != n:
      if r:n = x;p = y
    elif r:p = y
    else:N = min(N, (y - p)*5)
print("SAFE" if N == INF else N)

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

Solution (Python):
N=int(input())
W=[tuple(input().split()) for _ in range(N)]
U=[]
R=[]
D=[]
L=[]
for x,y,u in W:
 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))
r=10**9
def z(A):
 global r
 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<r:
   r=(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 r>=10**9 else r)

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))
r=10**9
def z(A):
 global r
 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<r:
   r=(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 r>=10**9 else r)

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):
 global ans
 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:
   ans=(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>=10**9 else ans)

Solution (Python):


import sys
from bisect import bisect_left, bisect_right
input=sys.stdin.readline

def main():
    N=int(input())
    
    ds=[[] for i in range(400001)] 
    rs=[[] for i in range(400001)]
    us=[[] for i in range(400001)]
    ls=[[] for i in range(400001)]
    db=[[] for i in range(400001)] 
    rb=[[] for i in range(400001)]
    ub=[[] for i in range(400001)]
    lb=[[] for i in range(400001)]
    dy=[[] for i in range(200001)] 
    uy=[[] for i in range(200001)]
    rx=[[] for i in range(200001)] 
    lx=[[] for i in range(200001)]
    
    sliset=set()
    bsiset=set()
    xset=set()
    yset=set()
    for i in range(N):
        x,y,u=input().split()
        x=int(x)
        y=int(y)
        sli=y-x+200000
        bsi=y+x
        sliset.add(sli)
        bsiset.add(bsi)
        if u=="U":
            us[sli].append(x)
            ub[bsi].append(x)
            uy[x].append(y)
            xset.add(x)
        elif u=="R":
            rs[sli].append(x)
            rb[bsi].append(x)
            rx[y].append(x)
            yset.add(y)
        elif u=="D":
            ds[sli].append(x)
            db[bsi].append(x)
            dy[x].append(y)
            xset.add(x)
        else:
            ls[sli].append(x)
            lb[bsi].append(x)
            lx[y].append(x)
            yset.add(y)
    for i in range(400001):
        ds[i].sort()
        rs[i].sort()
        us[i].sort()
        ls[i].sort()
        db[i].sort()
        rb[i].sort()
        ub[i].sort()
        lb[i].sort()
    for i in range(200001):
        dy[i].sort()
        uy[i].sort()
        rx[i].sort()
        lx[i].sort()
        
    mint=2*10**8
    for sli in sliset:
        for x in us[sli]:
            usi=bisect_left(ls[sli],x)
            if len(ls[sli])>0 and usi<len(ls[sli]):
                mint=min(mint, (ls[sli][usi]-x)*10)
        for x in rs[sli]:
            rsi=bisect_left(ds[sli],x)
            if len(ds[sli])>0 and rsi<len(ds[sli]):
                mint=min(mint, (ds[sli][rsi]-x)*10)
    for bsi in bsiset:
        for x in ub[bsi]:
            ubi=bisect_right(rb[bsi],x)
            if len(rb[bsi])>0 and ubi>0:
                mint=min(mint, (x-rb[bsi][ubi-1])*10)
        for x in db[bsi]:
            dbi=bisect_left(lb[bsi],x)
            if len(lb[bsi])>0 and dbi<len(lb[bsi]):
                mint=min(mint, (lb[bsi][dbi]-x)*10)
    for y in yset:
        for x in rx[y]:
            rxi=bisect_left(lx[y],x)
            if len(lx[y])>0 and rxi<len(lx[y]):
                mint=min(mint, (lx[y][rxi]-x)*5)
    for x in xset:
        for y in uy[x]:
            uyi=bisect_left(dy[x],y)
            if len(dy[x])>0 and uyi<len(dy[x]):
                mint=min(mint, (dy[x][uyi]-y)*5)

    if mint >= 2*10**8:
        print("SAFE")
    else:
        print(mint)
                
                
    
    
    
if __name__=="__main__":
    main()

Solution (Python):


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

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

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

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

for i in U_.values():
    i.sort(reverse=True)
for i in U__.values():
    i.sort(reverse=True)
for i in D_.values():
    i.sort(reverse=True)
for i in D__.values():
    i.sort(reverse=True)

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

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

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

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


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

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

n=int(input())
p=[]
for _ in range(n):
    x,y,u=input().split()
    p.append((int(x),int(y),u))

ans=10**9
import bisect

D={}
L={}
for i in p:
    if i[2]=='D':
        if i[0] in D:
            D[i[0]].append(i[1])
        else:
            D[i[0]]=[i[1]]
    elif i[2]=='L':
        if i[1] in L:
            L[i[1]].append(i[0])
        else:
            L[i[1]]=[i[0]]
for i in D.values():
    i.sort()
for i in L.values():
    i.sort()

for i in p:
    if i[2]=='U':
        if i[0] in D:
            j=bisect.bisect(D[i[0]],i[1])
            if j==len(D[i[0]]):
                continue
            temp=(D[i[0]][j]-i[1])*5
            ans=min(ans,temp)
    elif i[2]=='R':
        if i[1] in L:
            j=bisect.bisect(L[i[1]],i[0])
            if j==len(L[i[1]]):
                continue
            temp=(L[i[1]][j]-i[0])*5
            ans=min(ans,temp)

U={}
L={}
D={}
R={}
for i in p:
    if i[2]=='U':
        x=i[0]+i[1]
        if x in U:
            U[x].append(i[0])
        else:
            U[x]=[i[0]]
    elif i[2]=='L':
        x=i[0]-i[1]
        if x in L:
            L[x].append(i[0])
        else:
            L[x]=[i[0]]
    elif i[2]=='D':
        x=i[0]+i[1]
        if x in D:
            D[x].append(i[0])
        else:
            D[x]=[i[0]]
    elif i[2]=='R':
        x=i[0]-i[1]
        if x in R:
            R[x].append(i[0])
        else:
            R[x]=[i[0]]
for i in U.values():
    i.sort()
for i in L.values():
    i.sort()
for i in D.values():
    i.sort()
for i in R.values():
    i.sort()

for i in p:
    if i[2]=='U':
        x=i[0]-i[1]
        if x in L:
            j=bisect.bisect(L[x],i[0])
            if j==len(L[x]):
                continue
            temp=(L[x][j]-i[0])*10
            ans=min(ans,temp)
    elif i[2]=='L':
        x=i[0]+i[1]
        if x in D:
            j=bisect.bisect(D[x],i[0])
            if j==0:
                continue
            temp=(-D[x][j-1]+i[0])*10
            ans=min(ans,temp)
    elif i[2]=='D':
        x=i[0]-i[1]
        if x in R:
            j=bisect.bisect(R[x],i[0])
            if j ==0:
                continue
            temp=(-R[x][j-1]+i[0])*10
            ans=min(ans,temp)
    elif i[2]=='R':
        x=i[0]+i[1]
        if x in U:
            j=bisect.bisect(U[x],i[0])
            if j == len(U[x]):
                continue
            temp=(U[x][j]-i[0])*10
            ans=min(ans,temp)

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

Solution (Python):
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 bisect import bisect_left
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':
        UL[(x-y)].append((x, y))
    if u=='R':
        LR[y].append((x, y))
    if u=='D':
        DL[(x+y)].append((x, y))
    if u=='U':
        UR[(x+y)].append((x, y))
        UD[x].append((x, y))
    if u=='R':
        DR[(x-y)].append((x, y))

ans = 10**18
def check(x, y, u):
    global ans
    if u=='R':
        leng = len(UR[x+y])
        if leng:
            idx = bisect_left(UR[x+y], (x, y, u))
            if idx<leng:
                ans = min(ans, UR[x+y][idx][0]-x)

    if u=='L':
        leng = len(UL[x-y])
        if leng:
            idx = bisect_left(UL[x-y], (x, y, u))
            if idx>0:
                ans = min(ans, x-UL[x-y][idx-1][0])
        
        leng = len(DL[x+y])
        if leng:
            idx = bisect_left(DL[x+y], (x, y, u))
            if idx>0:
                ans = min(ans, x-DL[x+y][idx-1][0])
        
        leng = len(LR[y])
        if leng:
            idx = bisect_left(LR[y], (x, y, u))
            if idx>0:
                ans = min(ans, (x-LR[y][idx-1][0])/2)

    if u=='D':
        leng = len(UD[x])
        if leng:
            idx = bisect_left(UD[x], (x, y, u))
            if idx>0:
                ans = min(ans, (y-UD[x][idx-1][1])/2)

        leng = len(DR[x-y])
        if leng:
            idx = bisect_left(DR[x-y], (x, y, u))
            if idx>0:
                ans = min(ans, x-DR[x-y][idx-1][0])

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

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