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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#

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

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

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

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

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

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

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

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

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

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

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

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


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

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline

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

ans=10**9
import bisect

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

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

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

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

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

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
XYU = []
from bisect import bisect_left
from collections import defaultdict
UR = defaultdict(list)
UL = defaultdict(list)
DR = defaultdict(list)
DL = defaultdict(list)
LR = defaultdict(list)
UD = defaultdict(list)
for _ in range(N):
    x, y, u = input().split()
    x, y = int(x), int(y)
    XYU.append((x, y, u))
XYU.sort()
for x, y, u in XYU:
    if u=='U':
        UL[(x-y)].append((x, y))
    if u=='R':
        LR[y].append((x, y))
    if u=='D':
        DL[(x+y)].append((x, y))
    if u=='U':
        UR[(x+y)].append((x, y))
        UD[x].append((x, y))
    if u=='R':
        DR[(x-y)].append((x, y))

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

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

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

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

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

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
from collections import defaultdict
import bisect
xd0=defaultdict(list)
xd90=defaultdict(list)
xd180=defaultdict(list)
xd270=defaultdict(list)
xyd0=defaultdict(list)
xyd90=defaultdict(list)
xyd180=defaultdict(list)
xyd270=defaultdict(list)

def rotate(x,y,u):
    if u=='U': u0='R'
    elif u=='R': u0='D'
    elif u=='D': u0='L'
    else: u0='U'
    x0=y
    y0=200000-x
    return x0,y0,u0

for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=='U' or u=='D':
        xd0[x].append((y,u))
    x90,y90,u90=rotate(x,y,u)
    if u90=='U' or u90=='D':
        xd90[x90].append((y90,u90))
    x180,y180,u180=rotate(x90,y90,u90)
    if u180=='U' or u180=='D':
        xd180[x180].append((y180,u180))
    x270,y270,u270=rotate(x180,y180,u180)
    if u270=='U' or u270=='D':
        xd270[x270].append((y270,u270))
    if u=='U' or u=='R':
        xyd0[x+y].append((y,u))
    if u90=='U' or u90=='R':
        xyd90[x90+y90].append((y90,u90))
    if u180=='U' or u180=='R':
        xyd180[x180+y180].append((y180,u180))
    if u270=='U' or u270=='R':
        xyd270[x270+y270].append((y270,u270))

ans=float('inf')
for i in range(4):
    if i==0:
        xd=xd0
        xyd=xyd0
    elif i==1:
        xd=xd90
        xyd=xyd90        
    elif i==2:
        xd=xd180
        xyd=xyd180
    elif i==3:
        xd=xd270
        xyd=xyd270
    for j in range(200001):
        xl=xd[j]
        nxl=len(xl)
        if nxl<=1: continue
        elif nxl>1:
            xl=sorted(xl)
            for i in range(1,nxl):
                if xl[i][1]=='D' and xl[i-1][1]=='U':
                    ans=min(ans, (xl[i][0]-xl[i-1][0])*5)
    for j in range(400001):
        xyl=xyd[j]
        nxyl=len(xyl)
        if nxyl<=1: continue
        elif nxyl>1:
            xyl=sorted(xyl)
            for i in range(1,nxyl):
                if xyl[i][1]=='R' and xyl[i-1][1]=='U':
                    ans=min(ans, (xyl[i][0]-xyl[i-1][0])*10)            

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

Submission status: Accepted

Solution code:
n = int(input())
from collections import defaultdict
import bisect
xd0=defaultdict(list)
xd90=defaultdict(list)
xd180=defaultdict(list)
xd270=defaultdict(list)
xyd0=defaultdict(list)
xyd90=defaultdict(list)
xyd180=defaultdict(list)
xyd270=defaultdict(list)

def rotate(x,y,u):
    if u=='U': u0='R'
    elif u=='R': u0='D'
    elif u=='D': u0='L'
    else: u0='U'
    x0=y
    y0=200000-x
    return x0,y0,u0

for _ in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=='U' or u=='D':
        xd0[x].append((y,u))
    x90,y90,u90=rotate(x,y,u)
    if u90=='U' or u90=='D':
        xd90[x90].append((y90,u90))
    x180,y180,u180=rotate(x90,y90,u90)
    if u180=='U' or u180=='D':
        xd180[x180].append((y180,u180))
    x270,y270,u270=rotate(x180,y180,u180)
    if u270=='U' or u270=='D':
        xd270[x270].append((y270,u270))
    if u=='U' or u=='R':
        xyd0[x+y].append((y,u))
    if u90=='U' or u90=='R':
        xyd90[x90+y90].append((y90,u90))
    if u180=='U' or u180=='R':
        xyd180[x180+y180].append((y180,u180))
    if u270=='U' or u270=='R':
        xyd270[x270+y270].append((y270,u270))

ans=float('inf')
for i in range(4):
    if i==0:
        xd=xd0
        xyd=xyd0
    elif i==1:
        xd=xd90
        xyd=xyd90        
    elif i==2:
        xd=xd180
        xyd=xyd180
    elif i==3:
        xd=xd270
        xyd=xyd270
    for j in range(200001):
        xl=xd[j]
        nxl=len(xl)
        if nxl<=1: continue
        elif nxl>1:
            xl=sorted(xl)
            for i in range(1,nxl):
                if xl[i][1]=='D' and xl[i-1][1]=='U':
                    ans=min(ans, (xl[i][0]-xl[i-1][0])*5)
    for j in range(400001):
        xyl=xyd[j]
        nxyl=len(xyl)
        if nxyl<=1: continue
        elif nxyl>1:
            xyl=sorted(xyl)
            for i in range(1,nxyl):
                if xyl[i][1]=='R' and xyl[i-1][1]=='U':
                    ans=min(ans, (xyl[i][0]-xyl[i-1][0])*10)            

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

Submission status: Accepted

Solution code:
n = int(input())
x = []
y = []
d = []
for i in range(n):
  s = input().split()
  x.append(int(s[0]))
  y.append(int(s[1]))
  if s[2] == 'U':
    d.append(0)
  elif s[2] == 'L':
    d.append(1)
  elif s[2] == 'D':
    d.append(2)
  else:
    d.append(3)

INF = float('inf')

def calc(p):
  #print(p)
  res = INF
  for k,v in p.items():
    v.sort()
    for i in range(1,len(v)):
      if v[i-1][1] == 0 and v[i][1] != 0:
        res = min(v[i][0]-v[i-1][0],res)
  return res

ans = INF
for r in range(4):
  #UD
  p = {}
  for i in range(n):
    if d[i] != 0 and d[i] != 2:
      continue
    if x[i] in p:
      p[x[i]].append((y[i],d[i]))
    else:
      p[x[i]] = [(y[i],d[i])]
  ans = min(calc(p)*5,ans)
  #UR
  p = {}
  for i in range(n):
    if d[i] != 0 and d[i] != 3:
      continue
    if x[i]+y[i] in p:
      p[x[i]+y[i]].append((y[i],d[i]))
    else:
      p[x[i]+y[i]] = [(y[i],d[i])]
  ans = min(calc(p)*10,ans)
  #rotate
  for i in range(n):
    x[i],y[i] = -y[i],x[i]
    d[i] = (d[i]+1)%4

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

Submission status: Accepted

Solution code:
N = int(input())

planes = {
  'U': [],
  'R': [],
  'D': [],
  'L': []
}

for _ in range(N):
  x, y, t = input().split()
  x, y = int(x), int(y)
  planes[t].append((x, y))
  
BIG = 10**18
  
def time(ps):
  ps.sort()
  ans = BIG
  for i in range(len(ps)-1):
    y1, x1, t1 = ps[i]
    y2, x2, t2 = ps[i+1]
    
    if y1 != y2:
      continue
    
    if t1 == 1 and t2 == -1:
      ans = min(ans, x2 - x1)
  return 5*ans


ud = [(x, y, 1) for x, y in planes['U']] + [(x, y, -1) for x, y in planes['D']]
lr = [(y, x, 1) for x, y in planes['R']] + [(y, x, -1) for x, y in planes['L']]

ur = [(x+y, y-x, 1) for x, y in planes['U']] + [(x+y, y-x, -1) for x, y in planes['R']]
ul = [(x-y, y+x, 1) for x, y in planes['U']] + [(x-y, y+x, -1) for x, y in planes['L']]
rd = [(x-y, y+x, 1) for x, y in planes['R']] + [(x-y, y+x, -1) for x, y in planes['D']]
ld = [(x+y, y-x, 1) for x, y in planes['L']] + [(x+y, y-x, -1) for x, y in planes['D']]

ans = min(time(ud), time(lr), time(ur), time(ul), time(rd), time(ld))
if ans >= BIG:
  print("SAFE")
else:
  print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
n = int(input())
x = [0] * n
y = [0] * n
dir = [0] * n
INF = 10**8


def g(v):
    v.sort(key=lambda x: x[0])
    ret = INF
    for i in range(1, len(v)):
        if v[i - 1][1] == 0 and v[i][1] != 0:
            ret = min(ret, v[i][0] - v[i - 1][0])
    return ret


def f(d):
    ret = INF
    for k, v in d.items():
        ret = min(ret, g(v))
    return ret


for i in range(n):
    # x[i], y[i], c = map(int, input().split())
    sx, sy, c = input().split()
    x[i] = int(sx)
    y[i] = int(sy)
    if c == 'U':
        dir[i] = 0
    if c == 'R':
        dir[i] = 1
    if c == 'D':
        dir[i] = 2
    if c == 'L':
        dir[i] = 3

ans = INF
for ri in range(4):
    # UD
    d = defaultdict(list)
    for i in range(n):
        if dir[i] != 0 and dir[i] != 2:
            continue
        d[x[i]].append((y[i], dir[i]))
    ans = min(ans, f(d) * 5)
    # UR
    d2 = defaultdict(list)
    for i in range(n):
        if dir[i] != 0 and dir[i] != 1:
            continue
        d2[x[i] + y[i]].append((y[i], dir[i]))
    ans = min(ans, f(d2) * 10)

    # rotate
    for i in range(n):
        px = x[i]
        py = y[i]
        x[i] = py
        y[i] = -px
        dir[i] = (dir[i] + 1) % 4
if ans >= INF:
    print('SAFE')
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

n = int(input())
line = defaultdict(list)  # R,L
row = defaultdict(list)  # U,D
A = defaultdict(list)  # U,R
B = defaultdict(list)  # L,D
C = defaultdict(list)  # U,L
D = defaultdict(list)  # R,D

for i in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U":
        row[x].append((y, u == "U"))
        A[y + x].append((y - x, u == "U"))
        C[y - x].append((y + x, u == "U"))
    elif u == "D":
        row[x].append((y, u == "U"))
        B[y + x].append((y - x, u == "L"))
        D[y - x].append((y + x, u == "R"))
    elif u == "L":
        line[y].append((x, u == "R"))
        B[y + x].append((y - x, u == "L"))
        C[y - x].append((y + x, u == "U"))
    else:
        line[y].append((x, u == "R"))
        A[y + x].append((y - x, u == "U"))
        D[y - x].append((y + x, u == "R"))

ans = 10**18
for Z in (line, row, A, B, C, D):
    for z_list in Z.values():
        z_list.sort()
        for (v1, flag1), (v2, flag2) in zip(z_list, z_list[1:]):
            if flag1 and not flag2:
                ans = min(ans, abs(v1 - v2) * 5)

if ans == 10**18:
    print("SAFE")
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

n = int(input())
line = defaultdict(list)
row = defaultdict(list)
A = defaultdict(list)  # U,R
B = defaultdict(list)  # L,D
C = defaultdict(list)  # U,L
D = defaultdict(list)  # R,D

for i in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == "U":
        row[x].append((y, True))
        A[y + x].append((y - x, True))
        C[y - x].append((y + x, True))
    elif u == "D":
        row[x].append((y, False))
        B[y + x].append((y - x, False))
        D[y - x].append((y + x, False))
    elif u == "L":
        line[y].append((x, False))
        B[y + x].append((y - x, True))
        C[y - x].append((y + x, False))
    else:
        line[y].append((x, True))
        A[y + x].append((y - x, False))
        D[y - x].append((y + x, True))

ans = 10**18
for Z in (line, row, A, B, C, D):
    for z_list in Z.values():
        z_list.sort()
        for i in range(len(z_list) - 1):
            if z_list[i][1] == True and z_list[i + 1][1] == False:
                ans = min(ans, abs(z_list[i][0] - z_list[i + 1][0]) * 5)

if ans >= 10**18:
    print("SAFE")
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


sys.setrecursionlimit(2147483647)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


D_sum = defaultdict(list)
D_diff = defaultdict(list)
DX = defaultdict(list)
DY = defaultdict(list)
n = I()
L = []
ans = INF
for i in range(n):
    x, y, u = LS()
    x = int(x)
    y = int(y)
    D_sum[x + y] += [(x, u)]
    D_diff[x - y] += [(x, u)]
    if u in "UD":
        DX[x] += [(y, u)]
    else:
        DY[y] += [(x, u)]


for _, co_list in D_sum.items():
    co_list.sort()
    r = d = -INF
    for co, direction in co_list:
        if direction == "R":
            r = co
        elif direction == "D":
            d = co
        elif direction == "U":
            ans = min(co - r, ans)
        else:
            ans = min(co - d, ans)

for _, co_list in D_diff.items():
    co_list.sort()
    u = r = -INF
    for co, direction in co_list:
        if direction == "U":
            u = co
        elif direction == "R":
            r = co
        elif direction == "D":
            ans = min(co - r, ans)
        else:
            ans = min(co - u, ans)


for _, co_list in DX.items():
    co_list.sort()
    u = -INF
    for co, direction in co_list:
        coo = co
        if direction == "U":
            u = co
        else:
            ans = min((co - u) / 2, ans)


for _, co_list in DY.items():
    co_list.sort()
    r = -INF
    for co, direction in co_list:
        if direction == "R":
            r = co
        else:
            ans = min((co - r) / 2, ans)


if ans > 10 ** 8:
    print("SAFE")
else:
    print(int(ans * 10))







"""
L1 = []
L2 = []
L3 = []
L4 = []
for xk, yk ,u in L:
    L1 += [(xk - yk)]
    L2 += [(- xk - yk)]
    L3 += [(xk + yk)]
    L4 += [(- xk + yk)]

print(L1)
print(L2)
print(L3)
print(L4)

"""