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

Submission status: Accepted

Solution code:
from bisect import bisect
from collections import defaultdict

n = int(input())
up = [defaultdict(list), defaultdict(list), defaultdict(list)]
dp = [defaultdict(list), defaultdict(list), defaultdict(list)]
lp = [defaultdict(list), defaultdict(list), defaultdict(list)]
rp = [defaultdict(list), defaultdict(list), defaultdict(list)]

for _ in range(n):
    x, y, u = input().split()
    x = int(x)
    y = int(y)
    if u == 'U':
        up[0][x].append(y)
        up[1][x + y].append(x)
        up[2][x - y].append(x)
    elif u == 'D':
        dp[0][x].append(y)
        dp[1][x + y].append(x)
        dp[2][x - y].append(x)
    elif u == 'L':
        lp[0][y].append(x)
        lp[1][x + y].append(x)
        lp[2][x - y].append(x)
    else:
        rp[0][y].append(x)
        rp[1][x + y].append(x)
        rp[2][x - y].append(x)


def crush_time(planes1, planes2, idx):
    result = INF
    for xy in planes1[idx]:
        if xy not in planes2[idx]:
            continue
        s = planes1[idx][xy]
        s.sort()
        for x in planes2[idx][xy]:
            i = bisect(s, x)
            if i > 0:
                result = min(result, x - s[i - 1])
    return result


INF = 10 ** 18

ans = min(
    crush_time(up, dp, 0) * 5,
    crush_time(rp, lp, 0) * 5,
    crush_time(rp, up, 1) * 10,
    crush_time(dp, lp, 1) * 10,
    crush_time(up, lp, 2) * 10,
    crush_time(rp, dp, 2) * 10,
)

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

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

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):
    A.sort()
    n = -10**10
    p = -10**10
    for k, c, a in A:
        if k != n:
            if a == 1:
                n = k
                p = c
                continue
            else:
                continue
        if a == 1:
            p = c
            continue
        if (c - p)*5 < ans[0]:
            ans[0] = (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[0] == 10**9 else ans[0])

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):
    A.sort()
    n = -10**10
    p = -10**10
    for k, c, a in A:
        if k != n:
            if a == 1:
                n = k
                p = c
                continue
            else:
                continue
        if a == 1:
            p = c
            continue
        if (c - p)*5 < ans[0]:
            ans[0] = (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])
if ans[0] < 10**9:
    print(ans[0])
else:
    print("SAFE")

Submission status: Accepted

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  N = int(input())
  XYU = [list(map(str,input().split())) for _ in range(N)]
  from collections import deque
  INF = float('inf')

  UD = [0] * 200001
  LR = [0] * 200001
  UR = [0] * 400001
  DL = [0] * 400001
  DR = [0] * 400001
  UL = [0] * 400001


  for X,Y,u in XYU:
    X = int(X)
    Y = int(Y)
    if u=='R':
      if type(LR[Y])==int:
        LR[Y] = deque()
      if type(UR[X+Y])==int:
        UR[X+Y] = deque()
      if type(DR[X-Y+200000])==int:
        DR[X-Y+200000] = deque()

      LR[Y].append((X,u))
      UR[X+Y].append((Y,u))
      DR[X-Y+200000].append((Y,u))
    elif u=='L':
      if type(LR[Y])==int:
        LR[Y] = deque()
      if type(DL[X+Y])==int:
        DL[X+Y] = deque()
      if type(UL[X-Y+200000])==int:
        UL[X-Y+200000] = deque()
      LR[Y].append((X,u))
      DL[X+Y].append((Y,u))
      UL[X-Y+200000].append((Y,u))
    elif u=='U':
      if type(UD[X])==int:
        UD[X] = deque()
      if type(UR[X+Y])==int:
        UR[X+Y] = deque()
      if type(UL[X-Y+200000])==int:
        UL[X-Y+200000] = deque()
      UD[X].append((Y,u))
      UR[X+Y].append((Y,u))
      UL[X-Y+200000].append((Y,u))
    else:
      if type(UD[X])==int:
        UD[X] = deque()
      if type(DL[X+Y])==int:
        DL[X+Y] = deque()
      if type(DR[X-Y+200000])==int:
        DR[X-Y+200000] = deque()
      UD[X].append((Y,u))
      DL[X+Y].append((Y,u))
      DR[X-Y+200000].append((Y,u))

  safe = True
  ans = INF
  for l in UD:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='U')and(b[1]=='D'):
            safe = False
            ans = min(ans,(b[0] - a[0])*5)

  for l in LR:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='R')and(b[1]=='L'):
            safe = False
            ans = min(ans,(b[0] - a[0])*5)


  for l in UR:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='U')and(b[1]=='R'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  for l in DL:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='L')and(b[1]=='D'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  for l in UL:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='U')and(b[1]=='L'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  for l in DR:
    if type(l)!=int:
      length = len(l)
      if length>=2:
        l = sorted(l)
        for i in range(length - 1):
          a = l[i]
          b = l[i+1]
          if (a[1]=='R')and(b[1]=='D'):
            safe = False
            ans = min(ans,(b[0] - a[0]) * 10)

  if safe:
    print('SAFE')
  else:
    print(ans)
    
main()

Submission status: Accepted

Solution code:
def get_collision(A,ans):
    A.sort()
    nowkey = -10**10
    prevcoor = -10**10
    ret = ans[0]
    for key, coor, a in A:
        if key != nowkey:
            if a == 1:
                nowkey = key
                prevcoor = coor
                continue
            else:
                continue
        if a == 1:
            prevcoor = coor
            continue
        if (coor - prevcoor)*5 < ret:
            ret = (coor - prevcoor)*5
    ans[0] = ret

def main():
    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**10]

    UD = [(x,y,1) for x, y in U] + [(x,y,-1) for x, y in D]
    get_collision(UD, ans)
    LR = [(y,x,1) for x, y in R] + [(y,x,-1) for x, y in L]
    get_collision(LR, ans)
    RU = [(x+y,x-y,1) for x, y in R] + [(x+y,x-y,-1) for x,y in U]
    get_collision(RU, ans)
    LD = [(x+y,x-y,1) for x, y in D] + [(x+y,x-y,-1) for x,y in L]
    get_collision(LD,ans)
    LU = [(x-y,x+y,1) for x,y in U] + [(x-y,x+y,-1) for x,y in L]
    get_collision(LU,ans)
    RD = [(x-y,x+y,1) for x,y in R] + [(x-y,x+y,-1) for x,y in D]
    get_collision(RD,ans)
    if ans[0] < 10**10:
        print(ans[0])
    else:
        print("SAFE")
        
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    def calc(v, w, i, j, ans):
        if v > 0:
            i[0] += 1
        elif v < 0:
            j[0] += 1
        else:
            if w > 0:
                ans[0] = min(ans[0], w)
                i[0] += 1
            else:
                j[0] += 1

    n = int(input())
    inf = 10**10
    ans = [inf]
    u_list, d_list, l_list, r_list = [], [], [], []
    for _ in range(n):
        x, y, d = input().split()
        x, y = int(x), int(y)
        if d == "D":
            d_list.append((x, y))
        elif d == "R":
            r_list.append((x, y))
        elif d == "L":
            l_list.append((x, y))
        else:
            u_list.append((x, y))
    ld, lr, ll, lu = len(d_list), len(r_list), len(l_list), len(u_list)
    # 1→u,d
    u_list.sort(key=lambda x: (x[0], x[1]))
    d_list.sort(key=lambda x: (x[0], x[1]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < ld):
        x, y = u_list[i[0]]
        p, q = d_list[j[0]]
        v = p-x
        w = (q-y)*5
        calc(v, w, i, j, ans)
    # 2→r,l
    r_list.sort(key=lambda x: (x[1], x[0]))
    l_list.sort(key=lambda x: (x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < lr and j[0] < ll):
        x, y = r_list[i[0]]
        p, q = l_list[j[0]]
        v = q-y
        w = (p-x)*5
        calc(v, w, i, j, ans)
    # 3→u,l
    u_list.sort(key=lambda x: (x[0]-x[1], x[0]))
    l_list.sort(key=lambda x: (x[0]-x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < ll):
        x, y = u_list[i[0]]
        p, q = l_list[j[0]]
        v = (p-q)-(x-y)
        w = (p-x)*10
        calc(v, w, i, j, ans)
    # 4→d,l
    d_list.sort(key=lambda x: (x[0]+x[1], x[0]))
    l_list.sort(key=lambda x: (x[0]+x[1], x[0]))
    i, j = [0], [0]
    while(i[0] < ld and j[0] < ll):
        x, y = d_list[i[0]]
        p, q = l_list[j[0]]
        v = (p+q)-(x+y)
        w = (p-x)*10
        calc(v, w, i, j, ans)
    # 5→u,r
    u_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]+x[1], -x[0]))
    i, j = [0], [0]
    while(i[0] < lu and j[0] < lr):
        x, y = u_list[i[0]]
        p, q = r_list[j[0]]
        v = (p+q)-(x+y)
        w = (x-p)*10
        calc(v, w, i, j, ans)
    # 6→d,r
    d_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    r_list.sort(key=lambda x: (x[0]-x[1], -x[0]))
    i, j = [0], [0]
    while(i[0] < ld and j[0] < lr):
        x, y = d_list[i[0]]
        p, q = r_list[j[0]]
        v = (p-q)-(x-y)
        w = (x-p)*10
        calc(v, w, i, j, ans)
    if ans == [inf]:
        print("SAFE")
    else:
        print(ans[0])


main()

Submission status: Accepted

Solution code:
from collections import defaultdict


def solve():
    N = int(input())
    X, Y = defaultdict(list), defaultdict(list)
    dx, dy = defaultdict(list), defaultdict(list)
    for i in range(N):
        x, y, U = list(input().split())
        x, y = int(x), int(y)
        X[x].append((y, U))
        Y[y].append((x, U))
        dy[x+y].append((x-y, U))
        dx[x-y].append((x+y, U))
    ans = float("inf")
    for key in X.keys():
        X[key].sort()
        for i in range(1, len(X[key])):
            y1, dir1 = X[key][i-1]
            y2, dir2 = X[key][i]
            if dir1 == "U" and dir2 == "D":
                ans = min(ans, 5*y2-5*y1)
    for key in Y.keys():
        Y[key].sort()
        for i in range(1, len(Y[key])):
            y1, dir1 = Y[key][i-1]
            y2, dir2 = Y[key][i]
            if dir1 == "R" and dir2 == "L":
                ans = min(ans, 5*y2-5*y1)
    for key in dx.keys():
        dx[key].sort()
        for i in range(1, len(dx[key])):
            y1, dir1 = dx[key][i-1]
            y2, dir2 = dx[key][i]
            if (dir1 == "U" and dir2 == "L") or (dir1 == "R" and dir2 == "D"):
                ans = min(ans, 5*y2-5*y1)
    for key in dy.keys():
        dy[key].sort()
        for i in range(1, len(dy[key])):
            y1, dir1 = dy[key][i-1]
            y2, dir2 = dy[key][i]
            if (dir1 == "R" and dir2 == "U") or(dir1 == "D" and dir2 == "L"):
                ans = min(ans, 5*y2-5*y1)
    if ans == float("inf"):
        print("SAFE")
    else:
        print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
n = int(input())
big = 800001
sml = 400000
pp = [[[] for _ in range(big)] for _ in range(8)]
mm = [[[] for _ in range(big)] for _ in range(4)]
for _ in range(n):
  x,y,d = input().split()
  x = int(x)
  y = int(y)
  if d == 'R':
    pp[0][+x+y].append(+y)
    pp[2][+x-y].append(-y)
    mm[0][y].append(x)
  if d == 'L':
    pp[4][-x+y].append(+y)
    pp[6][-x-y].append(-y)
    mm[1][y].append(x)
  if d == 'U':
    pp[1][+x+y].append(+x)
    pp[5][-x+y].append(-x)
    mm[2][x].append(y)
  if d == 'D':
    pp[3][+x-y].append(+x)
    pp[7][-x-y].append(-x)
    mm[3][x].append(y)
import bisect
inf = 10**10
ans = inf
def ser(lx,ly,su):
  global ans
  for xx in lx:
    b = bisect.bisect_left(ly,su-xx)
    try:
      ans = min(ans,(xx+ly[b]-su)*10)
    except:
      pass
for d in range(4):
  xd = 2*d
  yd = 2*d+1
  for sun in range(-sml,sml+1):
    if pp[xd][sun] and pp[yd][sun]:
      pp[xd][sun].sort()
      pp[yd][sun].sort()
      #print(pp[xd][sun],pp[yd][sun],sun,xd,yd)
      ser(pp[xd][sun],pp[yd][sun],sun)
for sun in range(0,sml+1):
  if mm[0][sun] and mm[1][sun]:
    mm[0][sun].sort()
    mm[1][sun].sort()
    for xx in mm[0][sun]:
      b = bisect.bisect_left(mm[1][sun],xx)
      try:
        ans = min(ans,(mm[1][sun][b]-xx)*5)
      except:
        pass
for sun in range(0,sml+1):
  if mm[2][sun] and mm[3][sun]:
    mm[2][sun].sort()
    mm[3][sun].sort()
    for yy in mm[2][sun]:
      b = bisect.bisect_left(mm[3][sun],yy)
      try:
        ans = min(ans,(mm[3][sun][b]-yy)*5)
      except:
        pass
#print(ans)
if ans == inf:
  print('SAFE')
else:
  print(ans)

Submission status: Accepted

Solution code:
n = int(input())
nmx = 200000
sml = 2*nmx
big = 4*nmx
pp = [[[] for _ in range(big+1)] for _ in range(8)]
mm = [[[] for _ in range(nmx+1)] for _ in range(4)]
for _ in range(n):
  x,y,d = input().split()
  x = int(x)
  y = int(y)
  if d == 'R':
    pp[0][+x+y].append(+y)
    pp[2][+x-y].append(-y)
    mm[0][y].append(x)
  if d == 'L':
    pp[4][-x+y].append(+y)
    pp[6][-x-y].append(-y)
    mm[1][y].append(x)
  if d == 'U':
    pp[1][+x+y].append(+x)
    pp[5][-x+y].append(-x)
    mm[2][x].append(y)
  if d == 'D':
    pp[3][+x-y].append(+x)
    pp[7][-x-y].append(-x)
    mm[3][x].append(y)
import bisect
inf = 10**10
ans = inf
def ser(lx,ly,su):
  global ans
  lly = len(ly)
  for xx in lx:
    b = bisect.bisect_left(ly,su-xx)
    if b != lly:
      ans = min(ans,(xx+ly[b]-su)*10)
    else:
      pass
for d in range(4):
  xd = 2*d
  yd = 2*d+1
  for sun in range(-sml,sml+1):
    if pp[xd][sun] and pp[yd][sun]:
      pp[xd][sun].sort()
      pp[yd][sun].sort()
      #print(pp[xd][sun],pp[yd][sun],sun,xd,yd)
      ser(pp[xd][sun],pp[yd][sun],sun)
for sun in range(0,nmx+1):
  if mm[0][sun] and mm[1][sun]:
    llm = len(mm[1][sun])
    mm[0][sun].sort()
    mm[1][sun].sort()
    for xx in mm[0][sun]:
      b = bisect.bisect_left(mm[1][sun],xx)
      if b != llm:
        ans = min(ans,(mm[1][sun][b]-xx)*5)
      else:
        pass
for sun in range(0,nmx+1):
  if mm[2][sun] and mm[3][sun]:
    llm = len(mm[3][sun])
    mm[2][sun].sort()
    mm[3][sun].sort()
    for yy in mm[2][sun]:
      b = bisect.bisect_left(mm[3][sun],yy)
      if b != llm:
        ans = min(ans,(mm[3][sun][b]-yy)*5)
      else:
        pass
#print(ans)
if ans == inf:
  print('SAFE')
else:
  print(ans)

Submission status: Accepted

Solution code:
import sys
def input():return sys.stdin.readline()[:-1]
def N(): return int(input())
def NM():return map(int,input().split())
def L():return list(NM())
n=N()
import collections
from bisect import bisect, bisect_left, bisect_right

sei=[collections.defaultdict(list) for i in range(4)]
hu=[collections.defaultdict(list) for i in range(4)]
ziku=[collections.defaultdict(list) for i in range(4)]
s={"U":0 ,"R":1,"D":2,"L":3}
for i in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    t=s[u]
    
    sei[t][x-y].append(x)
    hu[t][x+y].append(x)
    if t%2==1:
        ziku[t][y].append(x)
    else:
        ziku[t][x].append(y)
def f(l,x):
    for i in l[x].keys():
        l[x][i].sort()
f(ziku,2)
f(ziku,3)
INF=float("inf")
ans=INF
def solve(l,x):
    ans=INF
    for k,v in l[x].items():
        if k in l[x^2]:
            for j in v:
                tmp=bisect(l[x^2][k],j)
                if tmp!=len(l[x^2][k]):
                    ans=min(ans,(l[x^2][k][tmp]-j)*5)
    return ans

ans=min(ans,solve(ziku,0))
ans=min(ans,solve(ziku,1))
f(sei,2)
f(sei,3)
def solve2(l,x):
    ans=INF
    for k,v in l[x].items():
        if k in l[3-x]:
            for j in v:
                tmp=bisect(l[3-x][k],j)
                if tmp!=len(l[3-x][k]):
                    ans=min(ans,(l[3-x][k][tmp]-j)*10)
    return ans
ans=min(ans,solve2(sei,0))
ans=min(ans,solve2(sei,1))
def solve3(l,x):
    ans=INF
    for k,v in l[x].items():
        if k in l[x^1]:
            for j in v:
                tmp=bisect(l[x^1][k],j)
                if tmp!=len(l[x^1][k]):
                    ans=min(ans,(l[x^1][k][tmp]-j)*10)
    return ans
f(hu,0)
f(hu,3)
ans=min(ans,solve3(hu,1))
ans=min(ans,solve3(hu,2))
if ans==INF:
    print("SAFE")
else:
    print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

from operator import itemgetter

n = readint()

ans = 10**10

only = [[[]for i in range(2*10**5+1)]for j in range(4)]
plus = [[[]for i in range(4*10**5+1)]for j in range(4)]
minus = [[[]for i in range(4*10**5+1)]for j in range(4)]
a = ['D','U','L','R']
for i in range(n):
    x,y,z = readstrs()
    x = int(x)
    y = int(y)
    b = a.index(z)
    if b<2:
        only[b][x].append(y)
    else:
        only[b][y].append(x)
    plus[b][x+y].append(x)
    minus[b][x-y].append(x)

def keisan(a,b,ans):
    a.sort()
    b.sort()
    k = 0
    j = 0
    while k<len(a) and j<len(b):
        if a[k]>b[j]:
            ans = min(ans,a[k]-b[j])
            j += 1
        else:
            k += 1
    return ans

for m in [0,2]:
    for i in range(2*10**5+1):
        a = only[m][i]
        b = only[m+1][i]
        if a and b:
            ans = keisan(a,b,ans)

if ans != 10**10:
    ans/=2

for p,q in [[2,1],[0,3]]:
    for i in range(4*10**5+1):
        a = minus[p][i]
        b = minus[q][i]
        if a and b:
            ans = keisan(a,b,ans)

for p,q in [[1,3],[2,0]]:
    for i in range(4*10**5+1):
        a = plus[p][i]
        b = plus[q][i]
        if a and b:
            ans = keisan(a,b,ans)

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

Submission status: Accepted

Solution code:
from collections import defaultdict
from bisect import bisect_left

INF = 10**18


def calc(data, p, q):

    ret = INF
    for k in data.keys():
        for i in range(len(data[k][p])):
            now = data[k][p][i]
            j = bisect_left(data[k][q], now)

            if j < len(data[k][q]):
                next = data[k][q][j]
                ret = min(ret, (next - now) * 10)

    return ret


def main():

    N = int(input())

    X = defaultdict(lambda: [[] for _ in range(4)])
    Y = defaultdict(lambda: [[] for _ in range(4)])
    XY_plus = defaultdict(lambda: [[] for _ in range(4)])
    XY_minus = defaultdict(lambda: [[] for _ in range(4)])
    URDL = ['U', 'R', 'D', 'L']

    for i in range(N):
        x, y, u = input().split()
        x, y = int(x), int(y)
        u = URDL.index(u)

        X[y][u].append(x)
        Y[x][u].append(y)
        XY_plus[x + y][u].append(x)
        XY_minus[x - y][u].append(x)

    for s in (X, Y, XY_plus, XY_minus):
        for k in s.keys():
            for i in range(4):
                s[k][i].sort()

    ans = INF
    ans = min(ans, calc(X, 1, 3) // 2)
    ans = min(ans, calc(Y, 0, 2) // 2)
    ans = min(ans, calc(XY_plus, 1, 0))
    ans = min(ans, calc(XY_plus, 2, 3))
    ans = min(ans, calc(XY_minus, 1, 2))
    ans = min(ans, calc(XY_minus, 0, 3))

    if ans >= 5000000:
        print('SAFE')
    else:
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
N=int(input())

uddic=defaultdict(list)
lrdic=defaultdict(list)
uldic=defaultdict(list)
urdic=defaultdict(list)
dldic=defaultdict(list)
drdic=defaultdict(list)

for _ in range(N):
  XS,YS,U=input().split()
  x=int(XS)
  y=int(YS)
  if U=="U":
    uddic[x].append((y,U))
    uldic[x-y].append((x,U))
    urdic[x+y].append((x,U))
  elif U=="D":
    uddic[x].append((y,U))
    dldic[x+y].append((x,U))
    drdic[x-y].append((x,U))
  elif U=="L":
    lrdic[y].append((x,U))
    uldic[x-y].append((x,U))
    dldic[x+y].append((x,U))
  else:
    lrdic[y].append((x,U))
    urdic[x+y].append((x,U))
    drdic[x-y].append((x,U))
    
answer=float("inf")
#UD
for x in uddic:
  ylist=sorted(uddic[x])
  for i in range(len(ylist)-1):
    y1,u1=ylist[i]
    y2,u2=ylist[i+1]
    if u1=="U" and u2=="D":
      answer=min(answer,(y2-y1)*5)
#LR
for y in lrdic:
  xlist=sorted(lrdic[y])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="R" and u2=="L":
      answer=min(answer,(x2-x1)*5)

#UL
for xmy in uldic:
  xlist=sorted(uldic[xmy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="U" and u2=="L":
      answer=min(answer,(x2-x1)*10)
#UR
for xpy in urdic:
  xlist=sorted(urdic[xpy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="R" and u2=="U":
      answer=min(answer,(x2-x1)*10)
#DL
for xpy in dldic:
  xlist=sorted(dldic[xpy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="D" and u2=="L":
      answer=min(answer,(x2-x1)*10)
#DR
for xmy in drdic:
  xlist=sorted(drdic[xmy])
  for i in range(len(xlist)-1):
    x1,u1=xlist[i]
    x2,u2=xlist[i+1]
    if u1=="R" and u2=="D":
      answer=min(answer,(x2-x1)*10)
  
if answer==float("inf"):
  print("SAFE")
else:
  print(answer)

Submission status: Accepted

Solution code:
import bisect
import copy
import heapq
import math
import sys
from collections import *
from functools import lru_cache
from itertools import accumulate, combinations, permutations, product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
sys.setrecursionlimit(500000)
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n=int(input())
xyu=[list(input().split()) for i in range(n)]
for i in range(n):
    x,y,u=xyu[i]
    xyu[i]=[int(x),int(y),u]

ans=mod

xyu.sort(lambda x: x[1])
tate=[-1]*200001
for i in range(n):
    x,y,u=xyu[i]
    if u=="D":
        if tate[x]!=-1:
            ans=min(ans,(y-tate[x])*5)
    elif u=="U":
        tate[x]=y

xyu.sort(lambda x: x[0])
yoko=[-1]*200001
for i in range(n):
    x,y,u=xyu[i]
    if u=="L":
        if yoko[y]!=-1:
            ans=min(ans,(x-yoko[y])*5)
    elif u=="R":
        yoko[y]=x



cnt=[[] for i in range(2*200001)]
for i in range(n):
    x,y,u=xyu[i]
    cnt[x+y].append(i)

for i in range(len(cnt)):
    ul=[-1]*2
    cnt[i].sort(lambda x: xyu[x][1])
    for j in range(len(cnt[i])):
        x,y,u=xyu[cnt[i][j]]
        if u=="U":
            ul[0]=y
        elif u=="L":
            ul[1]=y
        elif u=="D" and ul[1]!=-1:
            ans=min(ans,(y-ul[1])*10)
        elif u=="R" and ul[0]!=-1:
            ans=min(ans,(y-ul[0])*10)
    
cnt=[[] for i in range(2*200001)]
for i in range(n):
    x,y,u=xyu[i]
    cnt[200000-x+y].append(i)

for i in range(len(cnt)):
    ur=[-1]*2
    cnt[i].sort(lambda x: xyu[x][1])
    for j in range(len(cnt[i])):
        x,y,u=xyu[cnt[i][j]]
        if u=="U":
            ur[0]=y
        elif u=="R":
            ur[1]=y
        elif u=="D" and ur[1]!=-1:
            ans=min(ans,(y-ur[1])*10)
        elif u=="L" and ur[0]!=-1:
            ans=min(ans,(y-ur[0])*10)

if ans!=mod:
    print(ans)
else:
    print("SAFE")

Submission status: Accepted

Solution code:
from bisect import bisect_left
M = 200001
n = int(input())
l = [None] * n
ans = 10 ** 18
for i in range(n):
    x, y, u = input().split()
    u = ('R', 'U', 'L', 'D').index(u)
    l[i] = (int(x), int(y), u)
for _ in range(4):
    l.sort(key=lambda x: x[0])
    xy = [[] for _ in range(M * 2 - 1)]
    yx = [[] for _ in range(M * 2 - 1)]
    xs = [[] for _ in range(M)]
    k = []
    for i, t in enumerate(l):
        x, y, u = t
        u %= 4
        if u == 1:
            xy[x + y].append(x)
        elif u == 3:
            yx[x - y + M].append(x)
        elif u == 2:
            xs[y].append(x)
        else:
            k.append((x, y))
        l[i] = (-y + M - 1, x, u + 1)
    for x, y in k:
        idx = bisect_left(xs[y], x)
        if idx < len(xs[y]):
            ans = min(ans, (xs[y][idx] - x) * 5)
        idx = bisect_left(xy[x + y], x)
        if idx < len(xy[x + y]):
            ans = min(ans, (xy[x + y][idx] - x) * 10)
        idx = bisect_left(yx[x - y + M], x)
        if idx < len(yx[x - y + M]):
            ans = min(ans, (yx[x - y + M][idx] - x) * 10)
if ans == 10 ** 18:
    print('SAFE')
else:
    print(ans)