Problem:


Score: 600 points

Problem Statement

M-kun is a brilliant air traffic controller.

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

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

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

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

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

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

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

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

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

Constraints

1 \leq N \leq 200000

0 \leq X_i, Y_i \leq 200000

U_i is U, R, D, or L.

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

N, X_i, and Y_i are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

If there is no such pair, print SAFE.

Sample Input 1

2
11 1 U
11 47 D

Sample Output 1

230

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

Sample Input 2

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

Sample Output 2

SAFE

No pair of airplanes will collide.

Sample Input 3

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

Sample Output 3

100



Sample input:
2
11 1 U
11 47 D


Sample output:
230

Submission status: Accepted

Solution code:
from collections import defaultdict
from bisect import bisect,bisect_left
N = int(input())
XYU = [input().split() for _ in range(N)]
for i in range(N):
    XYU[i][0] = int(XYU[i][0])
    XYU[i][1] = int(XYU[i][1])
dp = defaultdict(lambda :defaultdict(list))
dn = defaultdict(lambda :defaultdict(list))
d1 = defaultdict(lambda :defaultdict(list))
d2 = defaultdict(lambda :defaultdict(list))

for i in range(N):
    x,y,u = XYU[i]
    dp[u][x+y].append(x)
    dn[u][x-y].append(x)
    d1[u][x].append(y)
    d2[u][y].append(x)

for u in ['U','R','D','L']:
    for z in dp[u]:
        dp[u][z].sort()
    for z in dn[u]:
        dn[u][z].sort()
    for z in d1[u]:
        d1[u][z].sort()
    for z in d2[u]:
        d2[u][z].sort()

ans = float('inf')
for i in range(N):
    x,y,u = XYU[i]
    if u=='U':
        j = bisect_left(dp['R'][x+y],x)-1
        if j>=0:
            ans = min(ans,10*(x-dp['R'][x+y][j]))
        j = bisect(dn['L'][x-y],x)
        if j<len(dn['L'][x-y]):
            ans = min(ans,10*(dn['L'][x-y][j]-x))
        j = bisect(d1['D'][x],y)
        if j<len(d1['D'][x]):
            ans = min(ans,5*(d1['D'][x][j]-y))
    elif u=='D':
        j = bisect_left(dn['R'][x-y],x)-1
        if j>=0:
            ans = min(ans,10*(x-dn['R'][x-y][j]))
        j = bisect(dp['L'][x+y],x)
        if j<len(dp['L'][x+y]):
            ans = min(ans,10*(dp['L'][x+y][j]-x))
        j = bisect_left(d1['U'][x],y)-1
        if j>=0:
            ans = min(ans,5*(y-d1['U'][x][j]))
    elif u=='R':
        j = bisect(dp['U'][x+y],x)
        if j<len(dp['U'][x+y]):
            ans = min(ans,10*(dp['U'][x+y][j]-x))
        j = bisect(dn['D'][x-y],x)
        if j<len(dn['D'][x-y]):
            ans = min(ans,10*(dn['D'][x-y][j]-x))
        j = bisect(d2['L'][y],x)
        if j<len(d2['L'][y]):
            ans = min(ans,5*(d2['L'][y][j]-x))
    elif u=='L':
        j = bisect_left(dp['D'][x+y],x)-1
        if j>=0:
            ans = min(ans,10*(x-dp['D'][x+y][j]))
        j = bisect_left(dn['U'][x-y],x)-1
        if j>=0:
            ans = min(ans,10*(x-dn['U'][x-y][j]))
        j = bisect_left(d2['R'][y],x)-1
        if j>=0:
            ans = min(ans,5*(x-d2['R'][y][j]))

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

Submission status: Accepted

Solution code:
from bisect import bisect_left
import sys
input = sys.stdin.readline
M = 200001
n = int(input())
l = [None] * n
ans = 10 ** 18
for i in range(n):
    x, y, u = input().split()
    u = ('R', 'D', 'L', 'U').index(u)
    l[i] = (int(x), int(y), u)
for _ in range(3):
    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 == 3:
            xy[x + y].append(x)
        elif u == 1:
            yx[x - y + M - 1].append(x)
        elif u == 2:
            xs[y].append(x)
        elif u == 0:
            k.append((x, y))
        l[i] = (y, -x + M - 1, 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 - 1], x)
        if idx < len(yx[x - y + M - 1]):
            ans = min(ans, (yx[x - y + M - 1][idx] - x) * 10)
if ans == 10 ** 18:
    print('SAFE')
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict

dx = defaultdict(list)
dy = defaultdict(list)
dxpy = [defaultdict(list), defaultdict(list)] # (up, right), (down, left)
dxmy = [defaultdict(list), defaultdict(list)] # (up, left), (down, right)

N = int(input())
for i in range(N):
    x, y, u = input().split()
    x = int(x); y = int(y)
    # print(x+y, x-y)
    if u == 'U':
        dx[x].append((y, u))
        dxpy[0][x+y].append((y, u))
        dxmy[0][x-y].append((y, u))
    if u == 'R':
        dy[y].append((x, u))
        dxpy[0][x+y].append((y, u))
        dxmy[1][x-y].append((y, u))
    if u == 'D':
        dx[x].append((y, u))
        dxpy[1][x+y].append((y, u))
        dxmy[1][x-y].append((y, u))
    if u == 'L':
        dy[y].append((x, u))
        dxpy[1][x+y].append((y, u))
        dxmy[0][x-y].append((y, u))


INF = 10**12
def calc1(zs, m1, m2):
    temp = INF
    pre_z = -1; pre_u = m2
    for z, u in zs:
        if pre_u == m1:
            if u == m1:
                pre_z = z
            else:
                pre_u = m2
                temp = min(temp, (z-pre_z)*10//2)
        elif u == m1:
            pre_z = z
            pre_u = m1    
    return temp

def calc2(zs, m1, m2):
    temp = INF
    pre_z = -1; pre_u = m2
    for z, u in zs:
        if pre_u == m1:
            if u == m1:
                pre_z = z
            else:
                pre_u = m2
                temp = min(temp, (z-pre_z)*10)
        elif u == m1:
            pre_z = z
            pre_u = m1    
    return temp



time = []
# up, down
for x in dx:
    dx[x].sort()
    t = calc1(dx[x], 'U', 'D')
    if t < INF:
        time.append(t)

# right, left
for y in dy:
    dy[y].sort()
    t = calc1(dy[y], 'R', 'L')
    if t < INF:
        time.append(t)

m12 = [['U', 'R'], ['L', 'D']]
for i in range(2):
    for xpy in dxpy[i]:
        dxpy[i][xpy].sort()
        t = calc2(dxpy[i][xpy], m12[i][0], m12[i][1])
        if t < INF:
            time.append(t)

m12 = [['U', 'L'], ['R', 'D']]
for i in range(2):
    for xmy in dxmy[i]:
        dxmy[i][xmy].sort()
        t  = calc2(dxmy[i][xmy], m12[i][0], m12[i][1])
        if t < INF:
            time.append(t)

if time:
    print(min(time))
else:
    print('SAFE')

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)

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:
            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])/2)
                    j += 1
                else:
                    k += 1

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

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

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

Submission status: Accepted

Solution code:
import collections
import heapq
def main():

    N = int(input())

    RL = collections.defaultdict(list)
    UD = collections.defaultdict(list)
    UL = collections.defaultdict(list)
    UR = collections.defaultdict(list)
    DL = collections.defaultdict(list)
    DR = collections.defaultdict(list)
    for _ in range(N):
        X, Y, U = input().split()
        X = int(X)
        Y = int(Y)
        if U == 'R':
            RL[Y].append([X, 0])
            UR[X+Y].append([X, 0])
            DR[X-Y].append([X, 0])
        elif U == 'L':
            RL[Y].append([X, 1])
            UL[X-Y].append([X, 1])
            DL[X+Y].append([X, 1])
        elif U == 'U':
            UD[X].append([Y, 0])
            UL[X-Y].append([X, 0])
            UR[X+Y].append([X, 1])
        else:
            UD[X].append([Y, 1])
            DL[X+Y].append([X, 0])
            DR[X-Y].append([X, 1])
    # print(horizontal)
    # print(vertical)

    ans = float('inf')
    for V in [UL, UR, DL, DR]:
        for X in V:
            V[X].sort()
            for j in range(len(V[X])-1):
                if V[X][j][1] == 0 and V[X][j+1][1] == 1:
                    ans = min(ans, 10 * (V[X][j+1][0]- V[X][j][0]))
    for V in [UD, RL]:
        for X in V:
            V[X].sort()
            for j in range(len(V[X])-1):
                if V[X][j][1] == 0 and V[X][j+1][1] == 1:
                    ans = min(ans, 5 * (V[X][j+1][0]- V[X][j][0]))

    if ans == float('inf'): return "SAFE"
    return ans

if __name__ == '__main__':
    print(main())

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
import bisect

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

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    N = in_n()

    X = defaultdict(lambda: [[] for _ in range(4)])
    Y = defaultdict(lambda: [[] for _ in range(4)])
    XYp = defaultdict(lambda: [[] for _ in range(4)])
    XYm = defaultdict(lambda: [[] for _ in range(4)])
    urdl = ['U', 'R', 'D', 'L']

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

        X[y][u].append(x)
        Y[x][u].append(y)
        XYp[x + y][u].append(x)
        XYm[x - y][u].append(x)

    INF = 10**18
    ans = INF

    for k in X.keys():
        for i in range(4):
            X[k][i].sort()

    for k in X.keys():
        for i in range(len(X[k][1])):
            now = X[k][1][i]
            j = bisect.bisect_left(X[k][3], now)

            if j < len(X[k][3]):
                next = X[k][3][j]
                ans = min(ans, (next - now) * 10 // 2)

    for k in Y.keys():
        for i in range(4):
            Y[k][i].sort()

    for k in Y.keys():
        for i in range(len(Y[k][0])):
            now = Y[k][0][i]
            j = bisect.bisect_left(Y[k][2], now)

            if j < len(Y[k][2]):
                next = Y[k][2][j]
                ans = min(ans, (next - now) * 10 // 2)

    for k in XYp.keys():
        for i in range(4):
            XYp[k][i].sort()

    for k in XYp.keys():

        # if len(XYp[k][1]) > 0 and len(XYp[k][0]) > 0:
        #     print(k, XYp[k])
        # if len(XYp[k][2]) > 0 and len(XYp[k][3]) > 0:
        #     print(k, XYp[k])

        for i in range(len(XYp[k][1])):
            now = XYp[k][1][i]
            j = bisect.bisect_left(XYp[k][0], now)
            if j < len(XYp[k][0]):
                next = XYp[k][0][j]
                ans = min(ans, (next - now) * 10)

        for i in range(len(XYp[k][2])):
            now = XYp[k][2][i]
            j = bisect.bisect_left(XYp[k][3], now)
            if j < len(XYp[k][3]):
                next = XYp[k][3][j]
                ans = min(ans, (next - now) * 10)

    for k in XYm.keys():
        for i in range(4):
            XYm[k][i].sort()

    for k in XYm.keys():

        # if len(XYm[k][1]) > 0 and len(XYm[k][2]) > 0:
        #     print(k, XYm[k])
        # if len(XYm[k][0]) > 0 and len(XYm[k][3]) > 0:
        #     print(k, XYm[k])

        for i in range(len(XYm[k][1])):
            now = XYm[k][1][i]
            j = bisect.bisect_left(XYm[k][2], now)
            if j < len(XYm[k][2]):
                next = XYm[k][2][j]
                ans = min(ans, (next - now) * 10)

        for i in range(len(XYm[k][0])):
            now = XYm[k][0][i]
            j = bisect.bisect_left(XYm[k][3], now)
            if j < len(XYm[k][3]):
                next = XYm[k][3][j]
                ans = min(ans, (next - now) * 10)

    # print(X)
    # print(Y)
    # print(XYp)
    # print(XYm)

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


if __name__ == '__main__':
    main()

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)

INF = 10 ** 18
ans = INF

for x in up[0]:
    if x not in dp[0]:
        continue
    us = up[0][x]
    us.sort()
    for y in dp[0][x]:
        i = bisect(us, y)
        if i > 0:
            tmp = y - us[i - 1]
            ans = min(ans, tmp * 5)

for y in rp[0]:
    if y not in lp[0]:
        continue
    rs = rp[0][y]
    rs.sort()
    for x in lp[0][y]:
        i = bisect(rs, x)
        if i > 0:
            tmp = x - rs[i - 1]
            ans = min(ans, tmp * 5)

for xy in rp[1]:
    if xy not in up[1]:
        continue
    rs = rp[1][xy]
    rs.sort()
    for x in up[1][xy]:
        i = bisect(rs, x)
        if i > 0:
            tmp = x - rs[i - 1]
            ans = min(ans, tmp * 10)

for xy in dp[1]:
    if xy not in lp[1]:
        continue
    ds = dp[1][xy]
    ds.sort()
    for x in lp[1][xy]:
        i = bisect(ds, x)
        if i > 0:
            tmp = x - ds[i - 1]
            ans = min(ans, tmp * 10)

for xy in up[2]:
    if xy not in lp[2]:
        continue
    us = up[2][xy]
    us.sort()
    for x in lp[2][xy]:
        i = bisect(us, x)
        if i > 0:
            tmp = x - us[i - 1]
            ans = min(ans, tmp * 10)

for xy in rp[2]:
    if xy not in dp[2]:
        continue
    rs = rp[2][xy]
    rs.sort()
    for x in dp[2][xy]:
        i = bisect(rs, x)
        if i > 0:
            tmp = x - rs[i - 1]
            ans = min(ans, tmp * 10)

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

Submission status: Accepted

Solution code:
from collections import defaultdict
import heapq as hq
N = int(input())
dicUD = defaultdict(list)
dicRL = defaultdict(list)
dicRUp = defaultdict(list)
dicDLp = defaultdict(list)
dicRDm = defaultdict(list)
dicULm = defaultdict(list)
for i in range(N):
    X,Y,U = input().split()
    X,Y = map(int,(X,Y))
    if U == "L":
        hq.heappush(dicRL[Y],(X,"L"))
        hq.heappush(dicDLp[X+Y],(X-Y,"L"))
        hq.heappush(dicULm[X-Y],(X+Y,"L"))
    if U == "R":
        hq.heappush(dicRL[Y],(X,"R"))
        hq.heappush(dicRUp[X+Y],(X-Y,"R"))
        hq.heappush(dicRDm[X-Y],(X+Y,"R"))
    if U == "U":
        hq.heappush(dicUD[X],(Y,"R"))
        hq.heappush(dicRUp[X+Y],(X-Y,"L"))
        hq.heappush(dicULm[X-Y],(X+Y,"R"))
    if U == "D":
        hq.heappush(dicUD[X],(Y,"L"))
        hq.heappush(dicDLp[X+Y],(X-Y,"R"))
        hq.heappush(dicRDm[X-Y],(X+Y,"L"))
time = 10000000
for dic in (dicUD,dicRL,dicRUp,dicDLp,dicRDm,dicULm):
    for q in dic.values():
        cur = -1000000
        dir = "L"
        while q:
            X,U = hq.heappop(q)
            if U == "R":
                dir = "R"
            elif U == "L":
                if dir == "R":
                    time = min(time,(X-cur)*5)
                dir = "L"
            cur = X
if time == 10000000:
    print("SAFE")
else:
    print(time)

Submission status: Accepted

Solution code:
n = int(input())
xyu = []
for i in range(n):
    x, y, u = map(str, input().split())
    x = int(x)
    y = int(y)
    xyu.append( (x, y, u) )

axisx = [[] for _ in range(200001)]
axisy = [[] for _ in range(200001)]
axislb = [[] for _ in range(400001)]
axislt = [[] for _ in range(400001)]

for x, y, u in xyu:
    if u == 'U' or u == 'D':
        axisx[x].append( (y, u) )
    elif u == 'L' or u == 'R':
        axisy[y].append( (x, u) )
    axislb[x+y].append( (x, u) )
    axislt[x-y+200000].append( (x, u) )

m = 100000000

for i in range(200001):
    if axisx[i]:
        axisx[i] = sorted(axisx[i])
        # print('axisx['+str(i)+']: ', axisx[i])
        d = None
        pos = None
        for y, u in axisx[i]:
            if d is None:
                if u == 'U':
                    d = 'U'
                    pos = y
            elif d == 'U':
                if u == 'U':
                    pos = y
                else:
                    m = min((y - pos)*5, m)
                    d = None
                    pos = None

for i in range(200001):
    if axisy[i]:
        axisy[i] = sorted(axisy[i])
        # print('axisy['+str(i)+']: ', axisy[i])
        d = None
        pos = None
        for x, u in axisy[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                else:
                    m = min((x - pos)*5, m)
                    d = None
                    pos = None

for i in range(400001):
    if axislb[i]:
        axislb[i] = sorted(axislb[i])
        # print('axislb['+str(i)+']: ', axislb[i])
        d = None
        pos = None
        for x, u in axislb[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                elif u == 'U':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None
        d = None
        pos = None
        for x, u in axislb[i]:
            if d is None:
                if u == 'D':
                    d = 'D'
                    pos = x
            elif d == 'D':
                if u == 'D':
                    pos = x
                elif u == 'L':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None

for i in range(400001):
    if axislt[i]:
        axislt[i] = sorted(axislt[i])
        # print('axislt['+str(i)+']: ', axislt[i])
        d = None
        pos = None
        for x, u in axislt[i]:
            if d is None:
                if u == 'R':
                    d = 'R'
                    pos = x
            elif d == 'R':
                if u == 'R':
                    pos = x
                elif u == 'D':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None
        d = None
        pos = None
        for x, u in axislt[i]:
            if d is None:
                if u == 'U':
                    d = 'U'
                    pos = x
            elif d == 'U':
                if u == 'U':
                    pos = x
                elif u == 'L':
                    m = min((x - pos)*10, m)
                    d = None
                    pos = None

if m == 100000000:
    print('SAFE')
else:
    print(m)

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [list(map(str, input().split())) for _ in range(row)]
        return map(list, zip(*read_all))

#################

N = I()
X,Y,U = LIR(N,3)
X = [int(x) for x in X]
Y = [int(y) for y in Y]

d1 = defaultdict(lambda:defaultdict(list))
d2 = defaultdict(lambda:defaultdict(list))

u = defaultdict(list)
r = defaultdict(list)
d = defaultdict(list)
l = defaultdict(list)

for i in range(N):
    if U[i] == 'U':
        u[X[i]].append(Y[i])
    elif U[i] == 'D':
        d[X[i]].append(Y[i])
    elif U[i] == 'R':
        r[Y[i]].append(X[i])
    else:
        l[Y[i]].append(X[i])

for k in u.keys():
    u[k].sort()

for k in d.keys():
    d[k].sort()

for k in r.keys():
    r[k].sort()

for k in l.keys():
    l[k].sort()

for i in range(N):
    d1[U[i]][Y[i]-X[i]].append(X[i])
    d2[U[i]][Y[i]+X[i]].append(X[i])

ans = float('inf')
for i in range(N):
    if U[i] == 'U':
        p = bisect_left(d[X[i]],Y[i])
        if p <= len(d[X[i]])-1 and len(d[X[i]]):
            ans = min(ans,(d[X[i]][p]-Y[i])*5)

        p = bisect_left(d1['L'][Y[i]-X[i]],X[i])
        if p <= len(d1['L'][Y[i]-X[i]])-1 and len(d1['L'][Y[i]-X[i]]):
            ans = min(ans,(d1['L'][Y[i]-X[i]][p]-X[i])*10)  

        p = bisect_left(d2['R'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d2['R'][Y[i]+X[i]])-1 and len(d2['R'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d2['R'][Y[i]+X[i]][p-1])*10)

    elif U[i] == 'D':
        p = bisect_left(u[X[i]],Y[i])
        if 0 <= p-1 <= len(u[X[i]])-1 and len(u[X[i]]):
            ans = min(ans,(Y[i]-u[X[i]][p-1])*5)

        p = bisect_left(d1['R'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d1['R'][Y[i]-X[i]])-1 and len(d1['R'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d1['R'][Y[i]-X[i]][p-1])*10)       

        p = bisect_left(d2['L'][Y[i]+X[i]],X[i])
        if p <= len(d2['L'][Y[i]+X[i]])-1 and len(d2['L'][Y[i]+X[i]]):
            ans = min(ans,(d2['L'][Y[i]+X[i]][p]-X[i])*10)

    elif U[i] == 'R':
        p = bisect_left(l[Y[i]],X[i])
        if p <= len(l[Y[i]])-1 and len(l[Y[i]]):
            ans = min(ans,(l[Y[i]][p]-X[i])*5)

        p = bisect_left(d1['D'][Y[i]-X[i]],X[i])
        if p <= len(d1['D'][Y[i]-X[i]])-1 and len(d1['D'][Y[i]-X[i]]):
            ans = min(ans,(d1['D'][Y[i]-X[i]][p]-X[i])*10)       

        p = bisect_left(d2['U'][Y[i]+X[i]],X[i])
        if p <= len(d2['U'][Y[i]+X[i]])-1 and len(d2['U'][Y[i]+X[i]]):
            ans = min(ans,(d2['U'][Y[i]+X[i]][p]-X[i])*10)

    else:
        p = bisect_left(r[Y[i]],X[i])
        if 0 <= p-1 <= len(r[Y[i]])-1 and len(r[Y[i]]):
            ans = min(ans,(X[i]-r[Y[i]][p-1])*5)

        p = bisect_left(d1['U'][Y[i]-X[i]],X[i])
        if 0 <= p-1 <= len(d1['U'][Y[i]-X[i]])-1 and len(d1['U'][Y[i]-X[i]]):
            ans = min(ans,(X[i]-d1['U'][Y[i]-X[i]][p-1])*10)

        p = bisect_left(d2['D'][Y[i]+X[i]],X[i])
        if 0 <= p-1 <= len(d2['D'][Y[i]+X[i]])-1 and len(d2['D'][Y[i]+X[i]]):
            ans = min(ans,(X[i]-d2['D'][Y[i]+X[i]][p-1])*10)


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

Submission status: Accepted

Solution code:
n = int(input())
A = [list(input().split()) for i in range(n)]
l = 2*10**5 + 5
# l = 5
# B = [[int(A[i][0]), int(A[i][1]), int(A[i][0])+int(A[i][1]), int(A[i][0])-int(A[i][1])+l, A[i][2]] for i in range(n)]

D = [[[] for j in range(2*l)] for i in range(4)]

# for i in range(4):
#     for j in range(n):
#         D[i][B[j][i]].append(B[j])

for i in range(n):
    x = int(A[i][0])
    y = int(A[i][1])
    nn = [x,y,A[i][2]]
    D[0][x].append(nn)
    D[1][y].append(nn)
    D[2][x+y].append(nn)
    D[3][x-y+l].append(nn)

# print(D)
import bisect
ans = float("inf")
for i in range(l):
    # print(D[1][i])
    LR = [[], []]
    for j in range(len(D[1][i])):
        
        if D[1][i][j][2] == "L":
            LR[0].append(D[1][i][j][0])
        if D[1][i][j][2] == "R":
            LR[1].append(D[1][i][j][0])
    LR[0].sort()
    LR[1].sort()
        # print(j,LR)
    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, (LR[0][ind]-LR[1][k]) * 5)

for i in range(l):
    # print(D[0][i])
    LR = [[], []]
    for j in range(len(D[0][i])):
        
        if D[0][i][j][2] == "U":
            LR[0].append(D[0][i][j][1])
        if D[0][i][j][2] == "D":
            LR[1].append(D[0][i][j][1])
    LR[0].sort()
    LR[1].sort()
        # print(j,LR)
    for k in range(len(LR[0])):
        ind = bisect.bisect(LR[1], LR[0][k])
        # print("ind",ind)
        if ind != len(LR[1]):
            ans = min(ans, (LR[1][ind]-LR[0][k]) * 5)

for i in range(2*l):
    # print(D[1][i])
    LR = [[], []]
    LR2 = [[], []]
    for j in range(len(D[2][i])):
        
        if D[2][i][j][2] == "L":
            LR[0].append(D[2][i][j][0])
        if D[2][i][j][2] == "D":
            LR[1].append(D[2][i][j][0])

        if D[2][i][j][2] == "U":
            LR2[0].append(D[2][i][j][0])
        if D[2][i][j][2] == "R":
            LR2[1].append(D[2][i][j][0])
        

    # print(j,LR2)
    LR[0].sort()
    LR2[0].sort()
    LR[1].sort()
    LR2[1].sort()

    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, (LR[0][ind]-LR[1][k]) * 10)
    
    for k in range(len(LR2[1])):
        ind = bisect.bisect(LR2[0], LR2[1][k])
        if ind != len(LR2[0]):
            ans = min(ans, (LR2[0][ind]-LR2[1][k]) * 10)

for i in range(2*l):
    # print(D[1][i])
    LR = [[], []]
    LR2 = [[], []]
    for j in range(len(D[3][i])):
        
        if D[3][i][j][2] == "D":
            LR[0].append(D[3][i][j][0])
        if D[3][i][j][2] == "R":
            LR[1].append(D[3][i][j][0])

        if D[3][i][j][2] == "L":
            LR2[0].append(D[3][i][j][0])
        if D[3][i][j][2] == "U":
            LR2[1].append(D[3][i][j][0])
    
    LR[0].sort()
    LR2[0].sort()
    LR[1].sort()
    LR2[1].sort()

        # print(j,LR)
    for k in range(len(LR[1])):
        ind = bisect.bisect(LR[0], LR[1][k])
        if ind != len(LR[0]):
            ans = min(ans, (LR[0][ind]-LR[1][k]) * 10)
    
    for k in range(len(LR2[1])):
        ind = bisect.bisect(LR2[0], LR2[1][k])
        if ind != len(LR2[0]):
            ans = min(ans, (LR2[0][ind]-LR2[1][k]) * 10)


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