Problem:


Score: 600 points

Problem Statement

M-kun is a brilliant air traffic controller.

On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude.

Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the direction of the airplane is as follows:

if U_i is U, it flies in the positive y direction;

if U_i is R, it flies in the positive x direction;

if U_i is D, it flies in the negative y direction;

if U_i is L, it flies in the negative x direction.

To help M-kun in his work, determine whether there is a pair of airplanes that will collide with each other if they keep flying as they are now.

If there is such a pair, find the number of seconds after which the first collision will happen.

We assume that the airplanes are negligibly small so that two airplanes only collide when they reach the same coordinates simultaneously.

Constraints

1 \leq N \leq 200000

0 \leq X_i, Y_i \leq 200000

U_i is U, R, D, or L.

The current positions of the N airplanes, (X_i, Y_i), are all distinct.

N, X_i, and Y_i are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 U_1
X_2 Y_2 U_2
X_3 Y_3 U_3
:
X_N Y_N U_N

Output

If there is a pair of airplanes that will collide with each other if they keep flying as they are now, print an integer representing the number of seconds after which the first collision will happen.

If there is no such pair, print SAFE.

Sample Input 1

2
11 1 U
11 47 D

Sample Output 1

230

If the airplanes keep flying as they are now, two airplanes numbered 1 and 2 will reach the coordinates (11, 24) simultaneously and collide.  

Sample Input 2

4
20 30 U
30 20 R
20 10 D
10 20 L

Sample Output 2

SAFE

No pair of airplanes will collide.

Sample Input 3

8
168 224 U
130 175 R
111 198 D
121 188 L
201 116 U
112 121 R
145 239 D
185 107 L

Sample Output 3

100



Sample input:
2
11 1 U
11 47 D


Sample output:
230

Submission status: Accepted

Solution code:
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")
#print(a, c)
if res == float("inf"): print("SAFE")
else: print(res)

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
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))

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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())

Submission status: Accepted

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

INF = 1e18
#URDL = 0123

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)

Submission status: Accepted

Solution code:
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)
    ###SHOUMEN SHOTOTSU
    # U and D
    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)
    # L and R
    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)
    ###KOUSA
    # D and R
    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)
    # L and U
    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)
    # U and R
    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)
    # L and D
    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')

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

Solution code:
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
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()

Submission status: Accepted

Solution code:
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):
        # UD
        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)
        # UR
        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)
        # rotate
        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)

Submission status: Accepted

Solution code:
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()
#ud.p()
#rl.p()
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.p()
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()
#mxy.p()
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)

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
_,*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])##

Submission status: Accepted

Solution code:
_,*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])

Submission status: Accepted

Solution code:
_,*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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
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])

Submission status: Accepted

Solution code:
_,*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])