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:
# from #15490827
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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import collections
import itertools
N = int(input())
#cnt[URLD][x y y+x y-x][value]=set()
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)


#U(0)とD(3)がx(0)が一緒:d-u(>=0)の最小値
#R(1)とL(2)がy(1)が一緒:l-r(>=0)の最小値
#U(0)とR(1)がx+y(2)が一緒:(y-x)のr-u(>=0)の最小値
#L(2)とD(3)がx+y(2)が一緒:(y-x)のd-l(>=0)の最小値
#U(0)とL(2)がy-x(3)が一緒:(y+x)のl-u(>=0)の最小値
#R(1)とD(3)がy-x(3)が一緒:(y+x)のd-r(>=0)の最小値
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)

Submission status: Accepted

Solution code:
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)
#UとR
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)
#DとR
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)
#DとL
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)
#最後UL
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)

Submission status: Accepted

Solution code:
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)
#UとR
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)
#DとR
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)
#DとL
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)
#最後UL
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)

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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)

Submission status: Accepted

Solution code:
#写経
#https://atcoder.jp/contests/m-solutions2020/submissions/15437687

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):
    # x1,y1 から y が増える側に移動 vs x2,y2 から y が減る側に移動
    ret = 10**18
    key1 = (X1 << 32) + Y1
    key2 = (X2 << 32) + Y2
    ind = key1.argsort()
    X1, Y1, key1 = X1[ind], Y1[ind], key1[ind]      # X，Yの大きさ順
    ind = key2.argsort()
    X2, Y2, key2 = X2[ind], Y2[ind], key2[ind]
    js = np.searchsorted(key2, key1)                # 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')       # 長さ1のstrを保存
 
i_u = U == b'U'             # [True False False]など該当する部分のみTrueになる
i_r = U == b'R'
i_d = U == b'D'
i_l = U == b'L'
 
Xu, Yu = X[i_u], Y[i_u]     # Upのみ反映される
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()

Submission status: Accepted

Solution code:
N = int(input())
plane = [0] * N
houkou = ["U", "D", "R", "L"]
up = []
down = []
right = []
left =[]
for i in range(N):
  x, y, p = list(map(str, input().split()))
  x = int(x)
  y = int(y)
  p2 = houkou.index(p)
  plane[i] = [x, y, x + y, x - y, p2]
  
#x座標が同じでぶつかる
plane = sorted(plane, key=lambda x:x[1])
plane = sorted(plane, key=lambda x:x[0])
#print(plane)
time = 10 ** 10
for k in range(1, N):
    if plane[k][0] == plane[k - 1][0]:
      if plane[k][1] > plane[k - 1][1]:
        if (plane[k][4] == 1) and (plane[k - 1][4] == 0):
          time2 = (plane[k][1] - plane[k - 1][1]) / 0.2
          time = min(time, time2)
      else:
        if (plane[k][4] == 0) and (plane[k - 1][4] == 1):
          time2 = (plane[k - 1][1] - plane[k][1]) / 0.2
          time = min(time, time2)
        
#y座標が同じでぶつかる
plane = sorted(plane, key=lambda x:x[0])
plane = sorted(plane, key=lambda x:x[1])
for k in range(1, N):
    if plane[k][1] == plane[k - 1][1]:
      if plane[k][0] > plane[k - 1][0]:
        if (plane[k][4] == 3) and (plane[k - 1][4] == 2):
          time2 = (plane[k][0] - plane[k - 1][0]) / 0.2
          time = min(time, time2)
      else:
        if (plane[k][4] == 2) and (plane[k - 1][4] == 3):
          time2 = (plane[k - 1][0] - plane[k][0]) / 0.2
          time = min(time, time2)

def go(x, y, u, t):
  if u == 0:
    return x, int(y + t * 0.1)
  elif u== 1:
    return x, int(y - t * 0.1)
  elif u == 2:
    return int(x + t * 0.1), y
  else:
    return int(x - t * 0.1), y
  
          
#和が同じでぶつかる
plane = sorted(plane, key=lambda x:x[2])
for k in range(1, N):
    one = plane[k]
    two = plane[k - 1]
                
    if plane[k][2] == plane[k - 1][2]:
      time2 = abs(one[0] - two[0]) / 0.1
      max_x = max(one[0],two[0])
      min_x = min(one[0], two[0])
      max_y = max(one[1], two[1])
      min_y = min(one[1], two[1])
      L = [[max_x, max_y], [min_x, min_y]]
      #k
      k_x, k_y = go(one[0], one[1], one[4], time2)
      #k - 1
      k2_x, k2_y = go(two[0], two[1], two[4], time2)
      if [k_x, k_y] in L:
        if [k2_x, k2_y] in L:
          if [k_x, k_y] == [k2_x, k2_y]:
            time = min(time, time2)
          
#差が同じでぶつかる
plane = sorted(plane, key=lambda x:x[3])
#print(plane)
for k in range(1, N):
    one = plane[k]
    two = plane[k - 1]
                
    if plane[k][3] == plane[k - 1][3]:
      time2 = abs(one[0] - two[0]) / 0.1
      max_x = max(one[0],two[0])
      min_x = min(one[0], two[0])
      max_y = max(one[1], two[1])
      min_y = min(one[1], two[1])
      L = [[max_x, min_y], [min_x, max_y]]
      #k
      k_x, k_y = go(one[0], one[1], one[4], time2)
      #k - 1
      k2_x, k2_y = go(two[0], two[1], two[4], time2)
      if [k_x, k_y] in L:
        if [k2_x, k2_y] in L:
          if [k_x, k_y] == [k2_x, k2_y]:
            time = min(time, time2)          
            
if time == 10 ** 10:
  print("SAFE")
else:
  print(int(time))
#print(plane)

Submission status: Accepted

Solution code:
N = int(input())

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

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

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

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

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

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

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

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


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

Submission status: Accepted

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

from collections import defaultdict

N = int(input())

S = 'RULD'

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

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

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

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

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

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

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

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

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

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

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

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

Submission status: Accepted

Solution code:
import numpy as np
import sys
from collections import defaultdict

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

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


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


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


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

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

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

    return ret


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

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

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

    return ret


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


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

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

Submission status: Accepted

Solution code:
import numpy as np
import sys
from collections import defaultdict

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

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


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


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


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

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

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

    return ret


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

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

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

    return ret


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


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

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

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

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

d1U = {} # 右上、x+y UR
d1R = {} # 右上、x+y UR
d2U = {} # 左上、x-y UL
d2L = {} # 左上、x-y UL
d3L = {} # 左下、x+y LD
d3D = {} # 左下、x+y LD
d4D = {} # 右下、x-y DR
d4R = {} # 右下、x-y DR

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

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

INF = 1<<30
ans = INF

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

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

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:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

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

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

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

d1U = {} # 右上、x+y UR
d1R = {} # 右上、x+y UR
d2U = {} # 左上、x-y UL
d2L = {} # 左上、x-y UL
d3L = {} # 左下、x+y LD
d3D = {} # 左下、x+y LD
d4D = {} # 右下、x-y DR
d4R = {} # 右下、x-y DR

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

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

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

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

INF = 1<<30
ans = INF

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

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

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