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

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

"""

上下 or 左右　それぞれの組はすぐ求まる．
同じライン上で上むきと下向きをまとめておいて，上向のaに対して，それよりも上にいて最も近い下向きのを探せば良い．
実際にはもっと早くできそうだけど二分探索で十分早いか

右+上　が当たる場合を考える．
u，rがそれぞれ約N個あるとして
uの中で一番左にあるやつ vs r全部
を考えて，uを左から順に見ていく？
微妙．

当たるとはdx=dyのこと
これ，右向きのやつを通る傾き-1の直線上（かつy座標が上の位置）に右向きのものがあれば当たれる．
45度回転させるか
X=x-y
Y=x+y
で反時計45度回転か．

uとrで，Y座標が同じで，rの方がX座標が小さい
dとlで，Y座標が同じで，dの方がX座標が小さい
dとrで，X座標が同じで，rの方がY座標が小さい
uとlで，X座標が同じで，uの方がY座標が小さい

だるすぎる，直線上の点をみよう，y=-x+kとすればx+y=kなので，kで場合わけ
各kでx座標が小さい順に並べておき，
u,rで，rの方がx座標が小さい
d,rで，rの方がx座標が小さい
u,lで，uの方がx座標が小さい
d,lで，dの方がx座標が小さい

"""
def main():
    import bisect
    
    mod=10**9+7
    N=I()
    M=200000 + 3
    inf = 10**10
    
    X=[0]*N
    Y=[0]*N
    U=[0]*N
    for i in range(N):
        xyu=input().split()
        X[i]=int(xyu[0])
        Y[i]=int(xyu[1])
        U[i]=xyu[2]
        
    # 同じ行/列のものを調べる
    
    xu=[[-inf, inf]for _ in range(M)]
    xd=[[-inf, inf]for _ in range(M)]
    yl=[[-inf, inf]for _ in range(M)]
    yr=[[-inf, inf]for _ in range(M)]
    
    for i in range(N):
        x=X[i]
        y=Y[i]
        if U[i] == "U":
            xu[x].append(y)
        elif U[i] == "D":
            xd[x].append(y)
        elif U[i] == "L":
            yl[y].append(x)
        else:
            yr[y].append(x)
    
    for i in range(M):
        xu[i].sort()
        xd[i].sort()
        yl[i].sort()
        yr[i].sort()
     
    ans_d=inf
    
    # uとかdで走査しても良いけど，全ての頂点を走査したいので此の形が楽
    for i in range(N):
        x=X[i]
        y=Y[i]
        u=U[i]
        
        if u=="U":
            num=bisect.bisect_left(xd[x], y)
            ne=xd[x][num]
            diff=ne-y
            ans_d=min(ans_d,diff)
            
        if u=="R":
            num=bisect.bisect_left(yl[y], x)
            ne=yl[y][num]
            diff=ne-x
            ans_d=min(ans_d,diff)
            
        """
        if u=="D":
            num=bisect.bisect_left(xu[x], y)
            pre=xu[x][num-1]
            diff=y-pre
            ans_d=min(ans_d,diff)

        if u=="L":
            num=bisect.bisect_left(yr[y], x)
            pre=yr[y][num-1]
            diff=x-pre
            ans_d=min(ans_d,diff)
        """
            
        # print(i,x,y,diff,ans_d)
    
    ################################################################        
    # ここから斜め

    ku=[[-inf, inf]for _ in range(M*2)]
    kd=[[-inf, inf]for _ in range(M*2)]
    kl=[[-inf, inf]for _ in range(M*2)]
    kr=[[-inf, inf]for _ in range(M*2)]    

    for i in range(N):
        x=X[i]
        y=Y[i]
        k=x+y
        if U[i] == "U":
            ku[k].append(x)
        elif U[i] == "D":
            kd[k].append(x)
        elif U[i] == "L":
            kl[k].append(x)
        else:
            kr[k].append(x)
            
    for i in range(M*2):
        ku[i].sort()
        kd[i].sort()
        kl[i].sort()
        kr[i].sort()
       
    """     
    各kでx座標が小さい順に並べておき，
    u,rで，rの方がx座標が小さい
    d,rで，rの方がx座標が小さい
    u,lで，uの方がx座標が小さい
    d,lで，dの方がx座標が小さい
    """
    
    # print("---")    
    
    ans_d2=inf
    # uとかdで走査しても良いけど，全ての頂点を走査したいので此の形が楽
    for i in range(N):
        x=X[i]
        y=Y[i]
        k=x+y
        if U[i] == "U":
            num=bisect.bisect_left(kr[k],x)
            pre=kr[k][num-1]
            diff=x-pre
            ans_d2=min(ans_d2,diff)

            num=bisect.bisect_left(kl[k],x)
            ne=kl[k][num]
            diff=ne-x
            ans_d2=min(ans_d2,diff)
            
        elif U[i] == "D":
            num=bisect.bisect_left(kr[k],x)
            pre=kr[k][num-1]
            diff=x-pre
            ans_d2=min(ans_d2,diff)

            num=bisect.bisect_left(kl[k],x)
            ne=kl[k][num]
            diff=ne-x
            ans_d2=min(ans_d2,diff)
        
        # print(i,x,y,pre,ne,diff,ans_d2)
            
    
        
    ans = min(ans_d*5, ans_d2*10) #速度分で*10， ans_dは向かい合っているので/2
    
    if ans>=10**8:
        assert False
        print("SAFE")
    else:
        print(ans)
        
        



        
        
            
    
            
            
        

main()

Submission status: Runtime Error

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

"""

上下 or 左右　それぞれの組はすぐ求まる．
同じライン上で上むきと下向きをまとめておいて，上向のaに対して，それよりも上にいて最も近い下向きのを探せば良い．
実際にはもっと早くできそうだけど二分探索で十分早いか

右+上　が当たる場合を考える．
u，rがそれぞれ約N個あるとして
uの中で一番左にあるやつ vs r全部
を考えて，uを左から順に見ていく？
微妙．

当たるとはdx=dyのこと
これ，右向きのやつを通る傾き-1の直線上（かつy座標が上の位置）に右向きのものがあれば当たれる．
45度回転させるか
X=x-y
Y=x+y
で反時計45度回転か．

uとrで，Y座標が同じで，rの方がX座標が小さい
dとlで，Y座標が同じで，dの方がX座標が小さい
dとrで，X座標が同じで，rの方がY座標が小さい
uとlで，X座標が同じで，uの方がY座標が小さい

だるすぎる，直線上の点をみよう，y=-x+kとすればx+y=kなので，kで場合わけ
各kでx座標が小さい順に並べておき，
u,rで，rの方がx座標が小さい
d,rで，rの方がx座標が小さい
u,lで，uの方がx座標が小さい
d,lで，dの方がx座標が小さい

"""
def main():
    import bisect
    
    mod=10**9+7
    N=I()
    M=200000 + 3
    inf = 10**10
    
    X=[0]*N
    Y=[0]*N
    U=[0]*N
    for i in range(N):
        xyu=input().split()
        X[i]=int(xyu[0])
        Y[i]=int(xyu[1])
        U[i]=xyu[2]
        
    # 同じ行/列のものを調べる
    
    xu=[[-inf, inf]for _ in range(M)]
    xd=[[-inf, inf]for _ in range(M)]
    yl=[[-inf, inf]for _ in range(M)]
    yr=[[-inf, inf]for _ in range(M)]
    
    for i in range(N):
        x=X[i]
        y=Y[i]
        if U[i] == "U":
            xu[x].append(y)
        elif U[i] == "D":
            xd[x].append(y)
        elif U[i] == "L":
            yl[y].append(x)
        else:
            yr[y].append(x)
    
    for i in range(M):
        xu[i].sort()
        xd[i].sort()
        yl[i].sort()
        yr[i].sort()
     
    ans_d=inf
    
    # uとかdで走査しても良いけど，全ての頂点を走査したいので此の形が楽
    for i in range(N):
        x=X[i]
        y=Y[i]
        u=U[i]
        
        if u=="U":
            num=bisect.bisect_left(xd[x], y)
            ne=xd[x][num]
            diff=ne-y
            ans_d=min(ans_d,diff)
            
        if u=="D":
            num=bisect.bisect_left(xu[x], y)
            pre=xu[x][num-1]
            diff=y-pre
            ans_d=min(ans_d,diff)
            
        if u=="L":
            num=bisect.bisect_left(yr[y], x)
            pre=yr[y][num-1]
            diff=x-pre
            ans_d=min(ans_d,diff)
            
        if u=="R":
            num=bisect.bisect_left(yl[y], x)
            ne=yl[y][num]
            diff=ne-x
            ans_d=min(ans_d,diff)
            
        # print(i,x,y,diff,ans_d)
    
    ################################################################        
    # ここから斜め

    ku=[[-inf, inf]for _ in range(M*2)]
    kd=[[-inf, inf]for _ in range(M*2)]
    kl=[[-inf, inf]for _ in range(M*2)]
    kr=[[-inf, inf]for _ in range(M*2)]    

    for i in range(N):
        x=X[i]
        y=Y[i]
        k=x+y
        if U[i] == "U":
            ku[k].append(x)
        elif U[i] == "D":
            kd[k].append(x)
        elif U[i] == "L":
            kl[k].append(x)
        else:
            kr[k].append(x)
            
    for i in range(M):
        ku[i].sort()
        kd[i].sort()
        kl[i].sort()
        kr[i].sort()
       
    """     
    各kでx座標が小さい順に並べておき，
    u,rで，rの方がx座標が小さい
    d,rで，rの方がx座標が小さい
    u,lで，uの方がx座標が小さい
    d,lで，dの方がx座標が小さい
    """
    
    # print("---")    
    
    ans_d2=inf
    # uとかdで走査しても良いけど，全ての頂点を走査したいので此の形が楽
    for i in range(N):
        x=X[i]
        y=Y[i]
        k=x+y
        if U[i] == "U":
            num=bisect.bisect_left(kr[k],x)
            pre=kr[k][num-1]
            diff=x-pre
            ans_d2=min(ans_d2,diff)

            num=bisect.bisect_left(kl[k],x)
            ne=kl[k][num]
            diff=ne-x
            ans_d2=min(ans_d2,diff)
        elif U[i] == "D":
            num=bisect.bisect_left(kr[k],x)
            pre=kr[k][num-1]
            diff=x-pre
            ans_d2=min(ans_d2,diff)

            num=bisect.bisect_left(kl[k],x)
            ne=kl[k][num]
            diff=ne-x
            ans_d2=min(ans_d2,diff)
        
        # print(i,x,y,pre,ne,diff,ans_d2)
            
    
        
    ans = min(ans_d*5, ans_d2*10) # ans_dは向かい合っているので/2
    
    if ans>=10**8:
        print("SAFE")
    else:
        print(ans)
        
        



        
        
            
    
            
            
        

main()

Submission status: Runtime Error

Solution code:
n = int(input())

xyu_s = []
for _ in range(n):
    xyu = list(input().split())
    xyu = [int(xyu[0]), int(xyu[1]), str(xyu[2])]
    xyu_s.append(xyu)

state = "SAFE"

def change_u(dir):
    if dir == "U":
        return "D"
    elif dir == "R":
        return "L"
    elif dir == "D":
        return "U"
    else:
        return "R"

for i in range(n):
    x = xyu_s[i][0]
    y = xyu_s[i][1]
    u = xyu_s[i][2]
    u_change = change_u(u)
    for j in range(i, n):
        if x == xyu_s[j][0] and u_change == xyu_s[j][2]:
            y_diff = abs(y - xyu_s[j][1])
            if y_diff % 2 == 0:
                state = y_diff / 2 * 10

        if y == xyu_s[j][1] and u_change == xyu_s[j][2]:
            x_diff = abs(x - xyu_s[j][0])
            if x_diff % 2 == 0:
                state = x_diff / 2 * 10

print(int(state))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

struct Add
{
    int x, y, add;
    Add(int _x, int _y): x(_x), y(_y), add(x+y) {}
    bool operator< (const Add& o) const
    {
        if (add != o.add)
            return add < o.add;
        return x < o.x;
    }
};

struct Sub
{
    int x, y, sub;
    Sub(int _x, int _y): x(_x), y(_y), sub(x-y) {}
    bool operator< (const Sub& o) const
    {
        if (sub != o.sub)
            return sub < o.sub;
        return x < o.x;
    }
};

struct X
{
    int x, y;
    X(int _x, int _y): x(_x), y(_y) {}
    bool operator< (const X& o) const
    {
        if (x != o.x)
            return x < o.x;
        return y < o.y;
    }
};

struct Y
{
    int x, y;
    Y(int _x, int _y): x(_x), y(_y) {}
    bool operator< (const Y& o) const
    {
        if (y != o.y)
            return y < o.y;
        return x < o.x;
    }
};

int main()
{
	freopen("data.in", "r", stdin);
    int x, y;
    char d[2];
    int ans = -1;
    std::set<Add>
        UAdd, DAdd, LAdd, RAdd;
    std::set<Sub>
        USub, DSub, LSub, RSub;
    std::set<X>
        UX, DX;
    std::set<Y>
        LY, RY;
    int N;
    auto upd = [&](int x) -> void
    {
        if (ans == -1 || ans > x)
            ans = x;
    };
    scanf("%d", &N);
    for (int i = 0; i < N; ++i)
    {
        scanf("%d %d %s", &x, &y, d);
        if (d[0] == 'U')
        {
            UAdd.emplace(x, y); USub.emplace(x, y); UX.emplace(x, y);
            std::set<Add>::iterator i1 = RAdd.lower_bound({x, y});
            if (i1 != RAdd.begin())
                if ((--i1)->add == x + y)
                    upd((i1->y - y) * 10);
            std::set<Sub>::iterator i2 = LSub.lower_bound({x, y});
            if (i2 != LSub.end())
                if (i2->sub == x - y)
                    upd((i2->y - y) * 10);
            std::set<X>::iterator i3 = DX.lower_bound({x, y});
            if (i3 != DX.end())
                if (i3->x == x)
                    upd((i3->y - y) * 5);
        }
        else if (d[0] == 'D')
        {
            DAdd.emplace(x, y); DSub.emplace(x, y); DX.emplace(x, y);
            std::set<Sub>::iterator i1 = RSub.lower_bound({x, y});
            if (i1 != RSub.begin())
                if ((--i1)->sub == x - y)
                    upd((y - i1->y) * 10);
            std::set<Add>::iterator i2 = LAdd.lower_bound({x, y});
            if (i2 != LAdd.end())
                if (i2->add == x + y)
                    upd((y - i2->y) * 10);
            std::set<X>::iterator i3 = UX.lower_bound({x, y});
            if (i3 != UX.begin())
                if ((--i3)->x == x)
                    upd((y - i3->y) * 5);
        }
        else if (d[0] == 'L')
        {
            LAdd.emplace(x, y); LSub.emplace(x, y); LY.emplace(x, y);
            std::set<Add>::iterator i1 = DAdd.lower_bound({x, y});
            if (i1 != DAdd.begin())
                if ((--i1)->add == x + y)
                    upd((x - i1->x) * 10);
            std::set<Sub>::iterator i2 = USub.lower_bound({x, y});
            if (i2 != USub.begin())
                if ((--i2)->sub == x - y)
                    upd((x - i2->x) * 10);
            std::set<Y>::iterator i3 = RY.lower_bound({x, y});
            if (i3 != RY.begin())
                if ((--i3)->y == y)
                    upd((x - i3->x) * 5);
        }
        else // d[0] == 'R'
        {
            RAdd.emplace(x, y); RSub.emplace(x, y); RY.emplace(x, y);
            std::set<Sub>::iterator i1 = DSub.lower_bound({x, y});
            if (i1 != DSub.end())
                if (i1->sub == x - y)
                    upd((i1->x - x) * 10);
            std::set<Add>::iterator i2 = UAdd.lower_bound({x, y});
            if (i2 != UAdd.end())
                if (i2->add == x + y)
                    upd((i2->x - x) * 10);
            std::set<Y>::iterator i3 = LY.lower_bound({x, y});
            if (i3 != LY.end())
                if (i3->y == y)
                    upd((i3->x - x) * 5);
        }
    }
    if (ans == -1)
        printf("SAFE\n");
    else
        printf("%d\n", ans);
}

Submission status: Runtime Error

Solution code:
import heapq
import copy
n = int(input())

size = 2*10**5
def f(ary):
    t_ans = 10**100
    for i in range(len(ary)):
        t_ud = ary[i]
        if len(t_ud) != 0:
            #print(t_ud)
            t_ud.sort()
            t_u = -10**100
            for j in range(len(t_ud)):
                if t_ud[j][1] == 'U':
                    t_u = t_ud[j][0]
                elif t_u == -10**100:
                    continue
                else:
                    t_ans = min(t_ans, (t_ud[j][0] - t_u))
    return t_ans

xyu = []

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

ud = [[] for i in range(size)]
rl = [[] for i in range(size)]
ul = [[] for i in range(size*2+2)]
ur = [[] for i in range(size*2+2)]
dl = [[] for i in range(size*2+2)]
dr = [[] for i in range(size*2+2)]

for i in range(n):
    if xyu[i][2] == 'U':
        ud[xyu[i][0]].append([xyu[i][1],'U'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'U'])
    if xyu[i][2] == 'D':
        ud[xyu[i][0]].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
    if xyu[i][2] == 'R':
        rl[xyu[i][0]].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
    if xyu[i][2] == 'L':
        rl[xyu[i][0]].append([xyu[i][1],'D'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'U'])
                  
ans = 10**100
ans = min(ans,f(ud)*5)
ans = min(ans,f(rl)*5)
ans = min(ans,f(ul)*10)
ans = min(ans,f(ur)*10)
ans = min(ans,f(dl)*10)
ans = min(ans,f(dr)*10)
if ans == 10**100:
    print('SAFE')
else:
    print(ans)

Submission status: Runtime Error

Solution code:
import heapq
import copy
n = int(input())

size = 2*10**5
def f(ary):
    t_ans = 10**100
    for i in range(len(ary)):
        t_ud = ary[i]
        if len(t_ud) != 0:
            #print(t_ud)
            t_ud.sort()
            t_u = -10**100
            for j in range(len(t_ud)):
                if t_ud[j][1] == 'U':
                    t_u = t_ud[j][0]
                elif t_u == -10**100:
                    continue
                else:
                    t_ans = min(t_ans, (t_ud[j][0] - t_u))
    return t_ans

xyu = []

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

ud = [[] for i in range(size)]
rl = [[] for i in range(size)]
ul = [[] for i in range(size*2+2)]
ur = [[] for i in range(size*2+2)]
dl = [[] for i in range(size*2+2)]
dr = [[] for i in range(size*2+2)]

for i in range(n):
    if xyu[i][2] == 'U':
        ud[xyu[i][0]].append([xyu[i][1],'U'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'U'])
    if xyu[i][2] == 'D':
        ud[xyu[i][0]].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
    if xyu[i][2] == 'R':
        rl[xyu[i][0]].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]].append([xyu[i][1],'U'])
    if xyu[i][2] == 'L':
        rl[xyu[i][0]].append([xyu[i][1],'D'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'U'])
                  
ans = 10**100
ans = min(ans,f(ud)*5)
ans = min(ans,f(rl)*5)
ans = min(ans,f(ul)*10)
ans = min(ans,f(ur)*10)
ans = min(ans,f(dl)*10)
ans = min(ans,f(dr)*10)
if ans == 10**100:
    print('SAFE')
else:
    print(ans)

Submission status: Runtime Error

Solution code:
import heapq
import copy
n = int(input())

size = 2*10**5
def f(ary):
    t_ans = 10**100
    for i in range(len(ary)):
        t_ud = ary[i]
        if len(t_ud) != 0:
            #print(t_ud)
            t_ud.sort()
            t_u = -10**100
            for j in range(len(t_ud)):
                if t_ud[j][1] == 'U':
                    t_u = t_ud[j][0]
                elif t_u == -10**100:
                    continue
                else:
                    t_ans = min(t_ans, (t_ud[j][0] - t_u))
    return t_ans

xyu = []

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

ud = [[] for i in range(size)]
rl = [[] for i in range(size)]
ul = [[] for i in range(size*2+2)]
ur = [[] for i in range(size*2+2)]
dl = [[] for i in range(size*2+2)]
dr = [[] for i in range(size*2+2)]

for i in range(n):
    if xyu[i][2] == 'U':
        ud[xyu[i][0]].append([xyu[i][1],'U'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'U'])
    if xyu[i][2] == 'D':
        ud[xyu[i][0]].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]].append([xyu[i][1],'D'])
    if xyu[i][2] == 'R':
        rl[xyu[i][0]].append([xyu[i][1],'U'])
        ur[xyu[i][1]+xyu[i][0]].append([xyu[i][1],'D'])
        dr[xyu[i][1]-xyu[i][0]].append([xyu[i][1],'U'])
    if xyu[i][2] == 'L':
        rl[xyu[i][0]].append([xyu[i][1],'D'])
        ul[xyu[i][1]-xyu[i][0]+size].append([xyu[i][1],'D'])
        dl[xyu[i][0]+xyu[i][1]].append([xyu[i][1],'U'])
                  
ans = 10**100
ans = min(ans,f(ud)*5)
ans = min(ans,f(rl)*5)
ans = min(ans,f(ul)*10)
ans = min(ans,f(ur)*10)
ans = min(ans,f(dl)*10)
ans = min(ans,f(dr)*10)
if ans == 10**100:
    print('SAFE')
else:
    print(ans)

Submission status: Runtime Error

Solution code:
from bisect import bisect_left
from collections import defaultdict

n = int(input())

xysame, upright, downright = {},{},{}
u_list = ("U","R","D","L")
for u in u_list:
    xysame[u] = defaultdict(list)
    upright[u] = defaultdict(list)
    downright[u] = defaultdict(list)

for _ in range(n):
    x,y,u = input().split()
    x,y = int(x),int(y)
    if u == "U" or "D":
        xysame[u][x].append(y)
    else:
        xysame[u][y].append(x)
    upright[u][y-x].append(x)
    downright[u][y+x].append(x)
    
for u in u_list:
    for key in xysame[u].keys():
        xysame[u][key].sort()
    for key in upright[u].keys():
        upright[u][key].sort()
    for key in downright[u].keys():
        downright[u][key].sort()

INF = 10**6
ans = INF


def line(low,high,type_ = 1):
    ret = INF
    for k,v in low.items():
        if high[k] == []: continue

        for vi in v:
            index = bisect_left(high[k], vi)
            if index == len(high[k]): conitnue
            ret = min(ret,(high[k][index]-vi)/type_)
    return ret

ans = min(ans, line(xysame["U"],xysame["D"],2))
ans = min(ans, line(xysame["R"],xysame["L"],2))
ans = min(ans, line(upright["R"],upright["D"],1))
ans = min(ans, line(upright["U"],upright["L"],1))
ans = min(ans, line(downright["R"],downright["U"],1))
ans = min(ans, line(downright["D"],downright["L"],1))

ans = int(ans*10)
if ans ==INF*10: ans = "SAFE"
    
print(ans)

Submission status: Runtime Error

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
        if d == U:
            y_axis[x].append((y,d))
            ul[sum_cordinate].append((x,y,d))
            ru[sum_cordinate].append((x,y,d))
        elif d == R:
            x_axis[y].append((x,d))
            ru[sum_cordinate].append((x,y,d))
            dr[sum_cordinate].append((x,y,d))
        elif d == D:
            y_axis[x].append((y,d))
            dr[sum_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[sum_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[i][0])*5)
                        braek
                    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[i][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[i][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[i][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[i][0])*10)
                        break
                    j += 1
                i = j
            i += 1


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

    

    



    
main()

Submission status: Runtime Error

Solution code:
import sys
# from collections import Counter

N_MAX = 200000 + 5
INF = 10**9 + 7
sys.setrecursionlimit(N_MAX)
MOD = 10**9 + 7


def main():
    N = int(sys.stdin.readline().rstrip())
    X = [[] for _ in range(200000)]
    Y = [[] for _ in range(200000)]
    A = [[] for _ in range(200000 * 2 + 1)]
    B = [[] for _ in range(200000 * 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 + 200000].append((x, u))

    # 正面衝突
    length = 1000000
    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((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((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((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((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((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((y - tmp_y) * 10, length)
                    is_count = False
                if u == "R":
                    tmp_y = y
                    is_count = True


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


main()