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:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N = II()
    #positions = defaultdict(defaultdict(int))
    #planes = []
    #1:U 2:R 3: D 4:L
    U = 0
    R = 1
    D = 2
    L = 3
    direction = {'U':U,'R':R,'D':D,'L':L}
    
    x_axis = defaultdict(list)
    y_axis = defaultdict(list)
    ru = defaultdict(list)
    dr = defaultdict(list)
    ld = defaultdict(list)
    ul = defaultdict(list)
    

    for i in range(N):
        line = input().split()
        x = int(line[0])
        y = int(line[1])
        d = direction[line[2]]

        #planes.append((x,y,d))

        #positions[y][x] = d
        
        
        sum_cordinate = x+y
        dif_cordinate = x-y
        if d == U:
            y_axis[x].append((y,d))
            ul[dif_cordinate].append((x,y,d))#(x1,y1)(x2,y2)y2-y1=x2-x1, y2-x2=y1-x1
            ru[sum_cordinate].append((x,y,d))
        elif d == R:
            x_axis[y].append((x,d))
            ru[sum_cordinate].append((x,y,d))
            dr[dif_cordinate].append((x,y,d))
        elif d == D:
            y_axis[x].append((y,d))
            dr[dif_cordinate].append((x,y,d))
            ld[sum_cordinate].append((x,y,d))
        else:
            x_axis[y].append((x,d))
            ld[sum_cordinate].append((x,y,d))
            ul[dif_cordinate].append((x,y,d))

    

    min_time = 10**20
    for v in x_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  R:
                j = i+1
                while j < len(v):
                    if v[j][1] == L:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1

    for v in y_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  U:
                j = i+1
                while j < len(v):
                    if v[j][1] == D:
                        min_time = min(min_time, (v[j][0]-v[i][0])*5)#ここ、v[j][0]-v[j-1][0]にすべき
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ru.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == U:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in dr.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == D:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ld.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == D:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ul.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == U:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1


    print(min_time if min_time < 10**20 else 'SAFE')
    

    

    



    
main()

Submission status: Accepted

Solution code:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N = II()
    #positions = defaultdict(defaultdict(int))
    #planes = []
    #1:U 2:R 3: D 4:L
    U = 0
    R = 1
    D = 2
    L = 3
    direction = {'U':U,'R':R,'D':D,'L':L}
    
    x_axis = defaultdict(list)
    y_axis = defaultdict(list)
    ru = defaultdict(list)
    dr = defaultdict(list)
    ld = defaultdict(list)
    ul = defaultdict(list)
    

    for i in range(N):
        line = input().split()
        x = int(line[0])
        y = int(line[1])
        d = direction[line[2]]

        #planes.append((x,y,d))

        #positions[y][x] = d
        
        
        sum_cordinate = x+y
        dif_cordinate = x-y
        if d == U:
            y_axis[x].append((y,d))
            ul[dif_cordinate].append((x,y,d))#(x1,y1)(x2,y2)y2-y1=x2-x1, y2-x2=y1-x1
            ru[sum_cordinate].append((x,y,d))
        elif d == R:
            x_axis[y].append((x,d))
            ru[sum_cordinate].append((x,y,d))
            dr[dif_cordinate].append((x,y,d))
        elif d == D:
            y_axis[x].append((y,d))
            dr[dif_cordinate].append((x,y,d))
            ld[sum_cordinate].append((x,y,d))
        else:
            x_axis[y].append((x,d))
            ld[sum_cordinate].append((x,y,d))
            ul[dif_cordinate].append((x,y,d))

    

    min_time = 10**20
    for v in x_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  R:
                j = i+1
                while j < len(v):
                    if v[j][1] == L:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1

    for v in y_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  U:
                j = i+1
                while j < len(v):
                    if v[j][1] == D:
                        min_time = min(min_time, (v[j][0]-v[i][0])*5)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ru.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == U:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in dr.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == D:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ld.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == D:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ul.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == U:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1


    print(min_time if min_time < 10**20 else 'SAFE')
    

    

    



    
main()

Submission status: Accepted

Solution code:
def main():
    from sys import setrecursionlimit, stdin, stderr
    from os import environ
    from collections import defaultdict, deque, Counter
    from math import ceil, floor
    from itertools import accumulate, combinations, combinations_with_replacement
    setrecursionlimit(10**6)
    dbg = (lambda *something: stderr.write("\033[92m{}\033[0m".format(str(something)+'\n'))) if 'TERM_PROGRAM' in environ else lambda *x: 0
    input = lambda: stdin.readline().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    P = 10**9+7
    INF = 10**18+10
    N = II()
    #positions = defaultdict(defaultdict(int))
    #planes = []
    #1:U 2:R 3: D 4:L
    U = 0
    R = 1
    D = 2
    L = 3
    direction = {'U':U,'R':R,'D':D,'L':L}
    
    x_axis = defaultdict(list)
    y_axis = defaultdict(list)
    ru = defaultdict(list)
    dr = defaultdict(list)
    ld = defaultdict(list)
    ul = defaultdict(list)
    

    for i in range(N):
        line = input().split()
        x = int(line[0])
        y = int(line[1])
        d = direction[line[2]]

        #planes.append((x,y,d))

        #positions[y][x] = d
        
        
        sum_cordinate = x+y
        dif_cordinate = x-y
        if d == U:
            y_axis[x].append((y,d))
            ul[dif_cordinate].append((x,y,d))#(x1,y1)(x2,y2)y2-y1=x2-x1, y2-x2=y1-x1
            ru[sum_cordinate].append((x,y,d))
        elif d == R:
            x_axis[y].append((x,d))
            ru[sum_cordinate].append((x,y,d))
            dr[dif_cordinate].append((x,y,d))
        elif d == D:
            y_axis[x].append((y,d))
            dr[dif_cordinate].append((x,y,d))
            ld[sum_cordinate].append((x,y,d))
        else:
            x_axis[y].append((x,d))
            ld[sum_cordinate].append((x,y,d))
            ul[dif_cordinate].append((x,y,d))

    

    min_time = 10**20
    for v in x_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  R:
                j = i+1
                while j < len(v):
                    if v[j][1] == L:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1

    for v in y_axis.values():
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][1] ==  U:
                j = i+1
                while j < len(v):
                    if v[j][1] == D:
                        min_time = min(min_time, (v[j][0]-v[j-1][0])*5)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ru.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == U:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in dr.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == R:
                j = i+1
                while j < len(v):
                    if v[j][2] == D:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ld.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == D:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1
    
    for v in ul.values():
        #x座標でソート
        v.sort()
        i = 0
        while i < len(v)-1:
            if v[i][2] == U:
                j = i+1
                while j < len(v):
                    if v[j][2] == L:
                        min_time = min(min_time,(v[j][0]-v[j-1][0])*10)
                        break
                    j += 1
                i = j
            i += 1


    print(min_time if min_time < 10**20 else 'SAFE')
    

    

    



    
main()

Submission status: Accepted

Solution code:
import sys
# from collections import Counter


def main():
    N = int(sys.stdin.readline().rstrip())
    X = [[] for _ in range(200005)]
    Y = [[] for _ in range(200005)]
    A = [[] for _ in range(200005 * 2 + 1)]
    B = [[] for _ in range(200005 * 2 + 1)]

    for i in range(N):
        x, y, u = sys.stdin.readline().rstrip().split()
        x = int(x)
        y = int(y)
        X[x].append((y, u))  # 同一X に含まれるもの
        Y[y].append((x, u))
        A[x + y].append((x, u))
        B[x - y + 200005].append((x, u))

    # 正面衝突
    length = 10000000
    for xs in X:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "D":
                    length = min(abs(y - tmp_y) * 5, length)
                    is_count = False
                if u == "U":
                    tmp_y = y
                    is_count = True

    # 正面衝突
    for xs in Y:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "L":
                    length = min(abs(y - tmp_y) * 5, length)
                    is_count = False
                if u == "R":
                    tmp_y = y
                    is_count = True

    # 正面衝突
    for xs in A:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "U":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "R":
                    tmp_y = y
                    is_count = True

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "L":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "D":
                    tmp_y = y
                    is_count = True

    # 正面衝突
    for xs in B:
        if len(xs) >= 2:
            xs.sort()

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "L":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "U":
                    tmp_y = y
                    is_count = True

            is_count = False
            tmp_y = 0
            for y, u in xs:
                if is_count and u == "D":
                    length = min(abs(y - tmp_y) * 10, length)
                    is_count = False
                if u == "R":
                    tmp_y = y
                    is_count = True

    if length == 10000000:
        print("SAFE")
    else:
        print(length)


main()

Submission status: Accepted

Solution code:
def f_calc1(u1, d1, ans):
  u1.sort()
  d1.sort()

  i=0
  for x1, y1 in u1:
    while i < len(d1):
      x2, y2 = d1[i]
      if x1 < x2:
        break
      if x1 == x2:
        if y1 < y2:
          ans = min(ans, (y2-y1)*5)
          break
        i += 1
      else:
        i += 1
  return ans

def f_calc2(u1, d1, ans):
  u1.sort()
  d1.sort()

  i=0
  for x1, y1 in u1:
    while i < len(d1):
      x2, y2 = d1[i]
      if x1 < x2:
        break
      if x1 == x2:
        if y1 < y2:
          ans = min(ans, (y2-y1)*10)
          break
        i += 1
      else:
        i += 1
  return ans

n = int(input())

u1 = []
u2 = []
u3 = []
d1 = []
d2 = []
d3 = []
r1 = []
r2 = []
r3 = []
l1 = []
l2 = []
l3 = []

for _ in range(n):
  x,y,u = input().split()
  x = int(x)
  y = int(y)
  if u == 'U':
    u1.append([x, y])
    u2.append([x+y, y])
    u3.append([x-y, y])
  elif u == 'D':
    d1.append([x, y])
    d2.append([x+y, x])
    d3.append([x-y, x])
  elif u == 'R':
    r1.append([y, x])
    r2.append([x+y, y])
    r3.append([x-y, x])
  else:
    l1.append([y, x])
    l2.append([x+y, x])
    l3.append([x-y, y])
  
ans = 10**8
ans = f_calc1(u1, d1, ans)
ans = f_calc1(r1, l1, ans)
ans = f_calc2(u2, r2, ans)
ans = f_calc2(d2, l2, ans)
ans = f_calc2(u3, l3, ans)
ans = f_calc2(r3, d3, ans)

print(ans if ans < 10**8 else "SAFE")

Submission status: Accepted

Solution code:
N = int(input())
L = {'U':[], 'R':[], 'D':[], 'L':[]}

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

ans = 10 ** 7

def solve(A):
    global ans
    A.sort()
    s = - 10 ** 6
    t = - 10 ** 6
    for p, q, r in A:
        if p != s:
            if r == 1:
                s = p
                t = q
        elif r == 1:
            t = q
        else:
            ans = min(ans, (q - t) * 5)

solve([(x, y, 1) for x, y in L['U']] + [(x, y, -1) for x, y in L['D']])
solve([(y, x, 1) for x, y in L['R']] + [(y, x, -1) for x, y in L['L']])
solve([(x + y, y - x, 1) for x, y in L['U']] + [(x + y, y - x, -1) for x, y in L['R']])
solve([(y - x, x + y, 1) for x, y in L['R']] + [(y - x, x + y, -1) for x, y in L['D']])
solve([(x + y, x - y, 1) for x, y in L['D']] + [(x + y, x - y, -1) for x, y in L['L']])
solve([(y - x, - x - y, 1) for x, y in L['L']] + [(y - x, - x - y, -1) for x, y in L['U']])

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

Submission status: Accepted

Solution code:
import sys
import collections


sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = float("inf")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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





    

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

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

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

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

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

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

ans = 10 ** 7

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

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

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

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

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

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

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

Submission status: Accepted

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

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

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

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

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

Submission status: Accepted

Solution code:
# from #15490827
import bisect

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

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

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