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
import collections


sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N = int(input())
    XYU = [[x for x in input().split()] for _ in range(N)]

    ans = float("inf")

    c1 = collections.defaultdict(list)
    c2 = collections.defaultdict(list)

    for x, y, u in XYU:
        x = int(x)
        y = int(y)
        if u in ("U", "D"):
            c1[x].append([y, u])
        if u in ("U", "R"):
            c2[x + y].append([y, u])

    for k in c1.keys():
        c1[k].sort()
        tmp = -float("inf")
        for y, u in c1[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.2)
                    break

    for k in c2.keys():
        c2[k].sort()
        tmp = -float("inf")
        for y, u in c2[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.1)
                    break

    XYU2 = []
    for x, y, u in XYU:
        x = int(x)
        y = int(y)
        if u == "R":
            XYU2.append([y, -x, "D"])
        elif u == "L":
            XYU2.append([y, -x, "U"])
        elif u == "D":
            XYU2.append([y, -x, "L"])
        else:
            XYU2.append([y, -x, "R"])

    c1 = collections.defaultdict(list)
    c2 = collections.defaultdict(list)
    for x, y, u in XYU2:
        x = int(x)
        y = int(y)
        if u in ("U", "D"):
            c1[x].append([y, u])
        if u in ("U", "R"):
            c2[x + y].append([y, u])

    for k in c1.keys():
        c1[k].sort()
        tmp = -float("inf")
        for y, u in c1[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.2)
                    break

    for k in c2.keys():
        c2[k].sort()
        tmp = -float("inf")
        for y, u in c2[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.1)
                    break

    XYU3 = []
    for x, y, u in XYU2:
        x = int(x)
        y = int(y)
        if u == "R":
            XYU3.append([y, -x, "D"])
        elif u == "L":
            XYU3.append([y, -x, "U"])
        elif u == "D":
            XYU3.append([y, -x, "L"])
        else:
            XYU3.append([y, -x, "R"])

    c1 = collections.defaultdict(list)
    c2 = collections.defaultdict(list)
    for x, y, u in XYU3:
        x = int(x)
        y = int(y)
        if u in ("U", "D"):
            c1[x].append([y, u])
        if u in ("U", "R"):
            c2[x + y].append([y, u])

    for k in c1.keys():
        c1[k].sort()
        tmp = -float("inf")
        for y, u in c1[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.2)
                    break

    for k in c2.keys():
        c2[k].sort()
        tmp = -float("inf")
        for y, u in c2[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.1)
                    break

    XYU4 = []
    for x, y, u in XYU3:
        x = int(x)
        y = int(y)
        if u == "R":
            XYU4.append([y, -x, "D"])
        elif u == "L":
            XYU4.append([y, -x, "U"])
        elif u == "D":
            XYU4.append([y, -x, "L"])
        else:
            XYU4.append([y, -x, "R"])

    c1 = collections.defaultdict(list)
    c2 = collections.defaultdict(list)
    for x, y, u in XYU4:
        x = int(x)
        y = int(y)
        if u in ("U", "D"):
            c1[x].append([y, u])
        if u in ("U", "R"):
            c2[x + y].append([y, u])

    for k in c1.keys():
        c1[k].sort()
        tmp = -float("inf")
        for y, u in c1[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.2)
                    break

    for k in c2.keys():
        c2[k].sort()
        tmp = -float("inf")
        for y, u in c2[k]:
            if u == "U":
                tmp = y
            else:
                if tmp != -float("inf"):
                    ans = min(ans, (y - tmp) / 0.1)
                    break

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





    

if __name__ == '__main__':
    main()

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

du = {}
dd = {}
dr = {}
dl = {}
n = int(input())

p = {'U': {}, 'D': {}, 'R': {}, 'L': {}}
m = {'U': {}, 'D': {}, 'R': {}, 'L': {}}

for i in range(n):
    x, y, u = input().rstrip('\n').split()
    x = int(x)
    y = int(y)
    if x + y in p[u]:
        p[u][x+y].append(x)
    else:
        p[u][x+y] = [x]

    if x - y in m[u]:
        m[u][x-y].append(x)
    else:
        m[u][x-y] = [x]
    
    if u == 'U':
        if x in du:
            du[x].append(y)
        else:
            du[x] = [y]
    if u == 'D':
        if x in dd:
            dd[x].append(y)
        else:
            dd[x] = [y]
    if u == 'R':
        if y in dr:
            dr[y].append(x)
        else:
            dr[y] = [x]
    if u == 'L':
        if y in dl:
            dl[y].append(x)
        else:
            dl[y] = [x]

for key in p:
    for key2 in p[key]:
        if key == 'U' or key == 'R':
            p[key][key2].sort(reverse=True)
        else:
            p[key][key2].sort()

for key in m:
    for key2 in m[key]:
        if key == 'D' or key == 'R':
            m[key][key2].sort(reverse=True)
        else:
            m[key][key2].sort()

ans = 10 ** 7

for key in p['U']:
    if key not in p['R']:
        continue
    num = len(p['R'][key])
    i = 0
    for x in p['U'][key]:
        while x < p['R'][key][i]:
            if i == num - 1:
                break
            i += 1
        if x > p['R'][key][i]:
            ans = min(ans, (x - p['R'][key][i]) * 10)

for key in m['D']:
    if key not in m['R']:
        continue
    num = len(m['R'][key])
    i = 0
    for x in m['D'][key]:
        while x < m['R'][key][i]:
            if i == num - 1:
                break
            i += 1
        if x > m['R'][key][i]:
            ans = min(ans, (x - m['R'][key][i]) * 10)

for key in m['U']:
    if key not in m['L']:
        continue
    num = len(m['L'][key])
    i = 0
    for x in m['U'][key]:
        while x > m['L'][key][i]:
            if i == num - 1:
                break
            i += 1
        if x < m['L'][key][i]:
            ans = min(ans, (m['L'][key][i] - x) * 10)

for key in p['D']:
    if key not in p['L']:
        continue
    num = len(p['L'][key])
    i = 0
    for x in p['D'][key]:
        while x > p['L'][key][i]:
            if i == num - 1:
                break
            i += 1
        if x < p['L'][key][i]:
            ans = min(ans, (p['L'][key][i] - x) * 10)

for x in du:
    if x in dd:
        du[x].sort()
        dd[x].sort()
        m = len(dd[x])
        i = 0
        for yi in du[x]:
            while yi > dd[x][i]:
                if i == m - 1:
                    break
                i += 1
            if yi <= dd[x][i]:
                ans = min(ans, (dd[x][i] - yi) * 5)

for y in dr:
    if y in dl:
        dr[y].sort()
        dl[y].sort()
        m = len(dl[y])
        i = 0
        for xi in dr[y]:
            while xi > dl[y][i]:
                if i == m - 1:
                    break
                i += 1
            if xi <= dl[y][i]:
                ans = min(ans, (dl[y][i] - xi) * 5)

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

Solution (Python):
import sys
input = sys.stdin.readline
N = int(input())
XYU = [input().split() for i in range(N)]

from collections import defaultdict
udlists = defaultdict(lambda: [])
rllists = defaultdict(lambda: [])
urlists = defaultdict(lambda: [])
dllists = defaultdict(lambda: [])
ullists = defaultdict(lambda: [])
drlists = defaultdict(lambda: [])

for x,y,u in XYU:
    x,y = int(x),int(y)
    z,v = x+y,x-y
    if u in 'UD':
        udlists[x].append((y,u))
    else:
        rllists[y].append((x,u))
    if u in 'UR':
        urlists[z].append((v,u))
    else:
        dllists[z].append((v,u))
    if u in 'UL':
        ullists[v].append((z,u))
    else:
        drlists[v].append((z,u))

INF = float('inf')
ans = INF
for li in udlists.values():
    li.sort(key=lambda x:x[0])
    for (y1,u1),(y2,u2) in zip(li,li[1:]):
        if u1=='U' and u2=='D':
            ans = min(ans, (y2-y1)*5)
for li in rllists.values():
    li.sort(key=lambda x:x[0])
    for (x1,u1),(x2,u2) in zip(li,li[1:]):
        if u1=='R' and u2=='L':
            ans = min(ans, (x2-x1)*5)
for li in urlists.values():
    li.sort(key=lambda x:x[0])
    for (v1,u1),(v2,u2) in zip(li,li[1:]):
        if u1=='R' and u2=='U':
            ans = min(ans, (v2-v1)*5)
for li in dllists.values():
    li.sort(key=lambda x:x[0])
    for (v1,u1),(v2,u2) in zip(li,li[1:]):
        if u1=='D' and u2=='L':
            ans = min(ans, (v2-v1)*5)
for li in ullists.values():
    li.sort(key=lambda x:x[0])
    for (z1,u1),(z2,u2) in zip(li,li[1:]):
        if u1=='U' and u2=='L':
            ans = min(ans, (z2-z1)*5)
for li in drlists.values():
    li.sort(key=lambda x:x[0])
    for (z1,u1),(z2,u2) in zip(li,li[1:]):
        if u1=='R' and u2=='D':
            ans = min(ans, (z2-z1)*5)

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

Solution (Python):

import bisect

def solve(deg1, deg2, lis, magnification):
    tmpAns = 10 ** 10
    for dx in lis[deg1].keys():
        if dx not in lis[deg2].keys():
            continue
        for dy in lis[deg1][dx]:
            t = bisect.bisect_left(lis[deg2][dx], dy)
            if t < len(lis[deg2][dx]):
                tmpAns = min(tmpAns, (lis[deg2][dx][t] - dy) * magnification)
    return tmpAns

N = int(input())
fTof = {"U": {}, "D": {}, "R": {}, "L": {}}
urld = {"U": {}, "D": {}, "R": {}, "L": {}}
ulrd = {"U": {}, "D": {}, "R": {}, "L": {}}
for _ in range(N):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U" or u == "D":
        if x in fTof[u]:
            fTof[u][x].append(y)
        else:
            fTof[u][x] = [y]
    else:
        if y in fTof[u]:
            fTof[u][y].append(x)
        else:
            fTof[u][y] = [x]
    if x+y in urld[u]:
        urld[u][x + y].append(y)
    else:
        urld[u][x + y] = [y]
    if x - y in ulrd[u]:
        ulrd[u][x - y].append(y)
    else:
        ulrd[u][x - y] = [y]

for i in fTof:
    for j in fTof[i]:
        fTof[i][j].sort()
for i in urld:
    for j in urld[i]:
        urld[i][j].sort()
for i in ulrd:
    for j in ulrd[i]:
        ulrd[i][j].sort()
ans = 10**10
ans = min(ans, solve("R", "L", fTof, 5))
ans = min(ans, solve("U", "D", fTof, 5))
ans = min(ans, solve("U", "R", urld, 10))
ans = min(ans, solve("L", "D", urld, 10))
ans = min(ans, solve("U", "L", ulrd, 10))
ans = min(ans, solve("R", "D", ulrd, 10))
print("SAFE" if ans == 10**10 else ans)

Solution (Python):

import bisect


def solve(deg1, deg2, lis, magnification):
    tmpAns = 10**10
    for dx in lis[deg1]:
        if dx not in lis[deg2]:
            continue
        for dy in lis[deg1][dx]:
            t = bisect.bisect_left(lis[deg2][dx], dy)
            if t < len(lis[deg2][dx]):
                tmpAns = min(tmpAns, (lis[deg2][dx][t] - dy) * magnification)
    return tmpAns


N = int(input())
fTof = {"U": {}, "D": {}, "R": {}, "L": {}}
urld = {"U": {}, "D": {}, "R": {}, "L": {}}
ulrd = {"U": {}, "D": {}, "R": {}, "L": {}}
for _ in range(N):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U" or u == "D":
        if x in fTof[u]:
            fTof[u][x].append(y)
        else:
            fTof[u][x] = [y]
    else:
        if y in fTof[u]:
            fTof[u][y].append(x)
        else:
            fTof[u][y] = [x]
    if x+y in urld[u]:
        urld[u][x + y].append(y)
    else:
        urld[u][x + y] = [y]
    if x - y in ulrd[u]:
        ulrd[u][x - y].append(y)
    else:
        ulrd[u][x - y] = [y]

for i in fTof:
    for j in fTof[i]:
        fTof[i][j].sort()
for i in urld:
    for j in urld[i]:
        urld[i][j].sort()
for i in ulrd:
    for j in ulrd[i]:
        ulrd[i][j].sort()
ans = 10**10
ans = min(ans, solve("R", "L", fTof, 5))
ans = min(ans, solve("U", "D", fTof, 5))
ans = min(ans, solve("U", "R", urld, 10))
ans = min(ans, solve("L", "D", urld, 10))
ans = min(ans, solve("U", "L", ulrd, 10))
ans = min(ans, solve("R", "D", ulrd, 10))
print("SAFE" if ans == 10**10 else ans)

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

dic={'U':'R','R':'D','D':'L','L':'U'}
def turn(arr):
  for i in range(len(arr)):
    arr[i][0],arr[i][1],arr[i][2]=[arr[i][1],200000-arr[i][0],dic[arr[i][2]]]
  return arr

n=int(input())
arr=[list(input().split()) for _ in range(n)]
for i in range(n):
  arr[i][0]=int(arr[i][0])
  arr[i][1]=int(arr[i][1])
ds=[[] for _ in range(200001)]
ls=[[] for _ in range(200001)]
arr=sorted(arr,key=lambda x:x[1])
arr=sorted(arr,key=lambda x:x[0])
for x,y,d in arr:
  if d=='D':
    ds[x].append(y)
  elif d=='L':
    ls[y].append(x)
ans=10**18
for x,y,d in arr:
  if d=='U':
    pos=bisect.bisect_left(ds[x],y)
    if pos==len(ds[x]):
      continue
    else:
      ans=min(ans,abs(ds[x][pos]-y)*5)
  elif d=='R':
    pos=bisect.bisect_left(ls[y],x)
    if pos==len(ls[y]):
      continue
    else:
      ans=min(ans,abs(ls[y][pos]-x)*5)
for _ in range(4):
  rs=[[] for _ in range(400001)]
  for x,y,d in arr:
    if d=='R':
      rs[x+y].append(y)
  for x,y,d in arr:
    if d=='U':
      pos=bisect.bisect_left(rs[x+y],y)
      if pos==len(rs[x+y]):
        continue
      else:
        ans=min(ans,abs(rs[x+y][pos]-y)*10)
  arr=turn(arr)
  arr=sorted(arr,key=lambda x:x[1])
if ans==10**18:
  print('SAFE')
else:
  print(ans)

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

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 19
MOD = 10 ** 9 + 7
EPS = 10 ** -10

N = INT()
XYD = []
for _ in range(N):
    x, y, d = input().split()
    x = int(x)
    y = int(y)
    if d == 'U':
        XYD.append([x, y, 0])
    elif d == 'R':
        XYD.append([x, y, 1])
    elif d == 'D':
        XYD.append([x, y, 2])
    else:
        XYD.append([x, y, 3])

DX = defaultdict(list)
DY = defaultdict(list)
for x, y, d in XYD:
    if d == 0:
        DX[x].append((y, 0))
    elif d == 1:
        DY[y].append((x, 0))
    elif d == 2:
        DX[x].append((y, 1))
    else:
        DY[y].append((x, 1))

ans = INF
for li in DX.values():
    li.sort()
    mxl = -1
    for y, d in li:
        if d == 0:
            mxl = y
        elif d == 1 and mxl != -1:
            ans = min(ans, (y-mxl) * 10 // 2)
for li in DY.values():
    li.sort()
    mxl = -1
    for x, d in li:
        if d == 0:
            mxl = x
        elif d == 1 and mxl != -1:
            ans = min(ans, (x-mxl) * 10 // 2)

for d1 in range(4):
    d2 = (d1+1) % 4
    D = defaultdict(list)
    for x, y, d in XYD:
        if d == d1:
            D[x+y].append(y)
    for k in D.keys():
        D[k].append(-INF)
        D[k].sort()
    for x, y, d in XYD:
        if d == d2:
            xy = x + y
            if xy in D:
                idx = bisect_right(D[xy], y) - 1
                if D[xy][idx] != -INF:
                    y2 = D[xy][idx]
                    x2 = xy - y2
                    ans = min(ans, (abs(x-x2)+abs(y-y2)) * 10 // 2)
    if d1 % 2 == 0:
        for i in range(N):
            XYD[i][0] *= -1
    else:
        for i in range(N):
            XYD[i][1] *= -1
if ans == INF:
    print('SAFE')
else:
    print(ans)

Solution (Python):
import bisect
from collections import defaultdict as dd
def check(A, B, d, coef):
    M = 10**50
    for x in d[A]:
        if x not in d[B]:
            continue
        for y in d[A][x]:
            yi = bisect.bisect_left(d[B][x], y)
            if yi < len(d[B][x]):
                M = min((d[B][x][yi] - y)*coef, M)
    return M
def main():
    N = int(input())
    dx = {"U":dd(list), "D":dd(list), "R":dd(list), "L":dd(list)}
    dy = {"U":dd(list), "D":dd(list), "R":dd(list), "L":dd(list)}
    dxpy = {"U":dd(list), "D":dd(list), "R":dd(list), "L":dd(list)}
    dxmy = {"U":dd(list), "D":dd(list), "R":dd(list), "L":dd(list)}
    for _ in range(N):
        x, y, u = input().split()
        x = int(x)
        y = int(y)
        dx[u][x].append(y)
        dy[u][y].append(x)
        dxpy[u][x+y].append(y)
        dxmy[u][x-y].append(y)
    for d in [dx, dy, dxpy, dxmy]:
        for j in d:
            for k in d[j]:
                d[j][k].sort()
    M = 10 ** 50
    M = min(M, check("U", "D", dx, 5))
    M = min(M, check("R", "L", dy, 5))
    M = min(M, check("R", "D", dxmy, 10))
    M = min(M, check("U", "L", dxmy, 10))
    M = min(M, check("U", "R", dxpy, 10))
    M = min(M, check("L", "D", dxpy, 10))
    print('SAFE' if M == 10** 50 else M)
main()

Solution (Python):
import bisect
def addto(a, b, d):
    if a in d:
        d[a].append(b)
    else:
        d[a] = [b]

def check(A, B, d, coef):
    M = 10**50
    for x in d[A]:
        if x not in d[B]:
            continue
        for y in d[A][x]:
            yi = bisect.bisect_left(d[B][x], y)
            if yi < len(d[B][x]):
                M = min((d[B][x][yi] - y)*coef, M)
    return M
def main():
    N = int(input())
    dx = {"U":{}, "D":{}, "R":{}, "L":{}}
    dy = {"U":{}, "D":{}, "R":{}, "L":{}}
    dxpy = {"U":{}, "D":{}, "R":{}, "L":{}}
    dxmy = {"U":{}, "D":{}, "R":{}, "L":{}}
    for _ in range(N):
        x, y, u = input().split()
        x = int(x)
        y = int(y)
        addto(x, y, dx[u])
        addto(y, x, dy[u])
        addto(x+y, y, dxpy[u])
        addto(x-y, y, dxmy[u])
    for d in [dx, dy, dxpy, dxmy]:
        for j in d:
            for k in d[j]:
                d[j][k].sort()
    M = 10 ** 50
    M = min(M, check("U", "D", dx, 5))
    M = min(M, check("R", "L", dy, 5))
    M = min(M, check("R", "D", dxmy, 10))
    M = min(M, check("U", "L", dxmy, 10))
    M = min(M, check("U", "R", dxpy, 10))
    M = min(M, check("L", "D", dxpy, 10))
    return M
x = main()
if x < 10 ** 50:
    print(x)
else:
    print('SAFE')

Solution (Python):
import collections
import itertools
N = int(input())

cnt = [[collections.defaultdict(set) for _ in range(4)] for _ in range(4)]
for _ in range(N):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    p = y + x
    q = y - x
    i = 'URLD'.index(u)
    cnt[i][0][x].add(y)
    cnt[i][1][y].add(x)
    cnt[i][2][p].add(q)
    cnt[i][3][q].add(p)

INF = float('inf')


def calc(up, down):
    ret = [INF]
    for c in up.keys() & down.keys():
        ua = sorted(up[c])
        da = sorted(down[c])
        i = j = 0
        for i in range(len(ua)):
            for j in range(j, len(da)):
                if ua[i] < da[j]:
                    ret += [da[j] - ua[i]]
                    break
            i += 1
    return min(ret)








ans = min(
    calc(cnt[0][0], cnt[3][0]), calc(cnt[1][1], cnt[2][1]),
    calc(cnt[0][2], cnt[1][2]), calc(cnt[2][2], cnt[3][2]),
    calc(cnt[0][3], cnt[2][3]), calc(cnt[1][3], cnt[3][3]))
print('SAFE' if ans == INF else ans * 5)

Solution (Python):
N=int(input())
U,R,D,L=[],[],[],[]
for i in range(N):
  x,y,a=input().split()
  x,y=int(x),int(y)
  if a=='U':
    U.append((x,y))
  elif a=='R':
    R.append((x,y))
  elif a=='D':
    D.append((x,y))
  elif a=='L':
    L.append((x,y))

G={}
for x,y in U:
  if x not in G:
    G[x]=[(y,'U')]
  else:
    G[x].append((y,'U'))
for x,y in D:
  if x not in G:
    G[x]=[(y,'D')]
  else:
    G[x].append((y,'D'))  

time=10**10
for i in G.values():
  a=len(i)
  i=sorted(i)
  for j in range(a-1):
    if i[j][1]=='U' and i[j+1][1]=='D':
      t=(i[j+1][0]-i[j][0])*5
      time=min(t,time)
G={}
for x,y in R:
  if y not in G:
    G[y]=[(x,'R')]
  else:
    G[y].append((x,'R'))
for x,y in L:
  if y not in G:
    G[y]=[(x,'L')]
  else:
    G[y].append((x,'L'))  

for i in G.values():
  a=len(i)
  i=sorted(i)
  for j in range(a-1):
    if i[j][1]=='R' and i[j+1][1]=='L':
      t=(i[j+1][0]-i[j][0])*5
      time=min(t,time)

G={}
for x,y in U:
  if x+y not in G:
    G[x+y]=[(y,'R')]
  else:
    G[x+y].append((y,'R'))
for x,y in R:
  if x+y not in G:
    G[x+y]=[(y,'U')]
  else:
    G[x+y].append((y,'U'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='R' and i[j+1][1]=='U':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)

G={}
for x,y in D:
  if x-y not in G:
    G[x-y]=[(y,'D')]
  else:
    G[x-y].append((y,'D'))
for x,y in R:
  if x-y not in G:
    G[x-y]=[(y,'R')]
  else:
    G[x-y].append((y,'R'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='R' and i[j+1][1]=='D':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)

G={}
for x,y in D:
  if x+y not in G:
    G[x+y]=[(y,'D')]
  else:
    G[x+y].append((y,'D'))
for x,y in L:
  if x+y not in G:
    G[x+y]=[(y,'L')]
  else:
    G[x+y].append((y,'L'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='L' and i[j+1][1]=='D':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)

G={}
for x,y in U:
  if x-y not in G:
    G[x-y]=[(y,'U')]
  else:
    G[x-y].append((y,'U'))
for x,y in L:
  if x-y not in G:
    G[x-y]=[(y,'L')]
  else:
    G[x-y].append((y,'L'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='U' and i[j+1][1]=='L':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)
if time==10**10:
  print('SAFE')
else:
  print(time)

Solution (Python):
N=int(input())
U,R,D,L=[],[],[],[]
for i in range(N):
  x,y,a=input().split()
  x,y=int(x),int(y)
  if a=='U':
    U.append((x,y))
  elif a=='R':
    R.append((x,y))
  elif a=='D':
    D.append((x,y))
  elif a=='L':
    L.append((x,y))

G={}
for x,y in U:
  if x not in G:
    G[x]=[(y,'U')]
  else:
    G[x].append((y,'U'))
for x,y in D:
  if x not in G:
    G[x]=[(y,'D')]
  else:
    G[x].append((y,'D'))  

time=10**10
for i in G.values():
  a=len(i)
  i=sorted(i)
  for j in range(a-1):
    if i[j][1]=='U' and i[j+1][1]=='D':
      t=(i[j+1][0]-i[j][0])*5
      time=min(t,time)
G={}
for x,y in R:
  if y not in G:
    G[y]=[(x,'R')]
  else:
    G[y].append((x,'R'))
for x,y in L:
  if y not in G:
    G[y]=[(x,'L')]
  else:
    G[y].append((x,'L'))  

for i in G.values():
  a=len(i)
  i=sorted(i)
  for j in range(a-1):
    if i[j][1]=='R' and i[j+1][1]=='L':
      t=(i[j+1][0]-i[j][0])*5
      time=min(t,time)

G={}
for x,y in U:
  if x+y not in G:
    G[x+y]=[(y,'R')]
  else:
    G[x+y].append((y,'R'))
for x,y in R:
  if x+y not in G:
    G[x+y]=[(y,'U')]
  else:
    G[x+y].append((y,'U'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='R' and i[j+1][1]=='U':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)

G={}
for x,y in D:
  if x-y not in G:
    G[x-y]=[(y,'D')]
  else:
    G[x-y].append((y,'D'))
for x,y in R:
  if x-y not in G:
    G[x-y]=[(y,'R')]
  else:
    G[x-y].append((y,'R'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='R' and i[j+1][1]=='D':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)

G={}
for x,y in D:
  if x+y not in G:
    G[x+y]=[(y,'D')]
  else:
    G[x+y].append((y,'D'))
for x,y in L:
  if x+y not in G:
    G[x+y]=[(y,'L')]
  else:
    G[x+y].append((y,'L'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='L' and i[j+1][1]=='D':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)

G={}
for x,y in U:
  if x-y not in G:
    G[x-y]=[(y,'U')]
  else:
    G[x-y].append((y,'U'))
for x,y in L:
  if x-y not in G:
    G[x-y]=[(y,'L')]
  else:
    G[x-y].append((y,'L'))
for i in G.values():
  a=len(i)
  i=sorted(i) 
  for j in range(a-1):
    if i[j][1]=='U' and i[j+1][1]=='L':
      t=(i[j+1][0]-i[j][0])*10
      time=min(t,time)
if time==10**10:
  print('SAFE')
else:
  print(time)

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):
 for x,y,r in eval('sorted((%sQ)for Q,P in enumerate(A)for x,y in P)'%S):
  if r:S,p=x,y
  elif x==S:N=min(N,y-p)
print(N%I*5or'SAFE')

Solution (Python):

import sys 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
M = 200000
UD = [[] for _ in range(2*M+10)]
RL = [[] for _ in range(2*M+10)]
RU = [[] for _ in range(2*M+10)]
RD = [[] for _ in range(2*M+10)]
LU = [[] for _ in range(2*M+10)]
LD = [[] for _ in range(2*M+10)]
for i in range(N):
    x, y, u = readline().decode().split()
    x = int(x); y = int(y)
    if u == 'R':
        RL[y].append((x,0))
        RU[x+y].append((x-y,0))
        RD[x-y+M].append((x+y,0))
    if u == 'L':
        RL[y].append((x,1))
        LU[x-y+M].append((x+y,1))
        LD[x+y].append((x-y,1))
    if u == 'U':
        UD[x].append((y,0))
        RU[x+y].append((x-y,1))
        LU[x-y+M].append((x+y,0))
    if u == 'D':
        UD[x].append((y,1))
        RD[x-y+M].append((x+y,1))
        LD[x+y].append((x-y,0))
        

def calc(X):
    dist = INF
    X = sorted(X)
    for i in range(len(X)-1):
        if X[i][1] == 0 and X[i+1][1] == 1:
            dist = min(dist,X[i+1][0]-X[i][0])
    return dist 
    
INF = 10**31 
dist = INF
for i in range(2*M+5):      
    dist = min(dist,calc(UD[i]))
    dist = min(dist,calc(RL[i]))
    dist = min(dist,calc(RU[i]))
    dist = min(dist,calc(RD[i]))
    dist = min(dist,calc(LU[i]))
    dist = min(dist,calc(LD[i]))

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

Solution (Python):



import sys
import numpy as np
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
def f(X1, Y1, X2, Y2):
    
    ret = 10**18
    key1 = (X1 << 32) + Y1
    key2 = (X2 << 32) + Y2
    ind = key1.argsort()
    X1, Y1, key1 = X1[ind], Y1[ind], key1[ind]      
    ind = key2.argsort()
    X2, Y2, key2 = X2[ind], Y2[ind], key2[ind]
    js = np.searchsorted(key2, key1)                
    for i in range(len(key1)):
        j = js[i]
        if j == len(key2):
            continue
        if X1[i] != X2[j]:
            continue
        ret = min(ret, Y2[j] - Y1[i])
    return ret
 
N = int(readline())
X = []
Y = []
U = []
for _ in range(N):
    x, y, u = readline().split()
    X.append(int(x))
    Y.append(int(y))
    U.append(u)
 
X = np.array(X, np.int64)
Y = np.array(Y, np.int64)
U = np.array(U, 'S1')       
 
i_u = U == b'U'             
i_r = U == b'R'
i_d = U == b'D'
i_l = U == b'L'
 
Xu, Yu = X[i_u], Y[i_u]     
Xr, Yr = X[i_r], Y[i_r]
Xd, Yd = X[i_d], Y[i_d]
Xl, Yl = X[i_l], Y[i_l]
 
def resolve():
    INF = 10**18
    ans = INF
    ans = min(ans, f(Xu, Yu, Xd, Yd))  
    ans = min(ans, f(Yr, Xr, Yl, Xl))  
    ans = min(ans, f(Xr + Yr, Xr - Yr, Xu + Yu, Xu - Yu))  
    ans = min(ans, f(Xu - Yu, Xu + Yu, Xl - Yl, Xl + Yl))  
    ans = min(ans, f(Xr - Yr, Xr + Yr, Xd - Yd, Xd + Yd))  
    ans = min(ans, f(Xd + Yd, Xd - Yd, Xl + Yl, Xl - Yl))  
    print('SAFE' if ans == INF else 5 * ans)
resolve()