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:
#十字で合流する場合
n=int(input())
ud=[[[],[]] for i in range(200001)]
rl=[[[],[]] for i in range(200001)]
from bisect import *
cross=[[dict(),dict()] for i in range(4)]
for i in range(n):
    x,y,u=input().split()
    x,y=int(x),int(y)
    if u=="U":
        ud[x][0].append(y)
        if x+y in cross[0][1]:
            cross[0][1][x+y].append(x)
        else:
            cross[0][1][x+y]=[x]
        if x-y in cross[1][1]:
            cross[1][1][x-y].append(x)
        else:
            cross[1][1][x-y]=[x]
    elif u=="D":
        ud[x][1].append(y)
        if x+y in cross[3][1]:
            cross[3][1][x+y].append(x)
        else:
            cross[3][1][x+y]=[x]
        if x-y in cross[2][1]:
            cross[2][1][x-y].append(x)
        else:
            cross[2][1][x-y]=[x]
    elif u=="R":
        rl[y][0].append(x)
        if x+y in cross[0][0]:
            cross[0][0][x+y].append(x)
        else:
            cross[0][0][x+y]=[x]
        if x-y in cross[2][0]:
            cross[2][0][x-y].append(x)
        else:
            cross[2][0][x-y]=[x]
    else:
        rl[y][1].append(x)
        if x+y in cross[3][0]:
            cross[3][0][x+y].append(x)
        else:
            cross[3][0][x+y]=[x]
        if x-y in cross[1][0]:
            cross[1][0][x-y].append(x)
        else:
            cross[1][0][x-y]=[x]
for i in range(200001):
    ud[i][0].sort()
    ud[i][1].sort()
    rl[i][0].sort()
    rl[i][1].sort()
ans=[]
for i in range(200001):
    l1,l2=len(ud[i][0]),len(ud[i][1])
    if l1 and l2:
        for j in ud[i][0]:
            b=bisect_left(ud[i][1],j)
            if b!=l2:
                ans.append(ud[i][1][b]-j)
    l1,l2=len(rl[i][0]),len(rl[i][1])
    if l1 and l2:
        for j in rl[i][0]:
            b=bisect_left(rl[i][1],j)
            if b!=l2:
                ans.append(rl[i][1][b]-j)
for i in range(4):
    for j in range(2):
        for k in cross[i][j]:
            cross[i][j][k].sort()
#print(cross)
for i in range(4):
    for j in cross[i][1]:
        if j in cross[i][0]:
            l=len(cross[i][0][j])
            if i%2==1:
                for k in cross[i][1][j]:
                    b=bisect_left(cross[i][0][j],k)
                if b!=l:
                    ans.append(2*cross[i][0][j][b]-2*k)
            else:
                for k in cross[i][1][j]:
                    b=bisect_right(cross[i][0][j],k)-1
                if b!=-1:
                    ans.append(2*k-2*cross[i][0][j][b])
if len(ans) :
    print(min(ans)*5)
else:
    print(wdfwf)
    print("SAFE")

Submission status: Runtime Error

Solution code:
import logging
logging.basicConfig(level=logging.DEBUG)
def printd(s):
  logging.debug(s)
  return

import numpy as np
from operator import itemgetter
N = int(input())

PP = {
  "D" : [],
  "U" : [],
  "L" : [],
  "R" : [],
}

for i in range(N):
  x,y,d = input().split()
  x,y = int(x), int(y)
  PP[d].append((x,y,x+y, x-y))
  
#print(PP)
ans = 1e18

def conflict_180(Ax,Ay,Bx,By,ans):
  NA, NB = len(Ax), len(Bx)
  if NA == 0 or NB == 0:
    return ans
  j = 0
  for i in range(NA):
    while j < NB-1 and Ax[i] > Bx[j]:
      j += 1
      if j == NB-1:
        break
    if Ax[i] == Bx[j]:
      # 衝突条件。ここ符号をちゃんと気にしよう
      if Ay[i] >= By[j]:
        printd((Ay[i], By[i], ans))
        ans = min(ans, Ay[i] - By[j])
  return ans
  """
  ay>byで衝突にするのだから、AがD、BがUじゃないとだめ。家帰ると、A、B＝L、R。
  """

printd("DvsU")
PA = np.array(sorted(PP['D']))
PB = np.array(sorted(PP['U']))
if PA.size and PB.size:
  ans = conflict_180(PA[:, 0], PA[:, 1], PB[:, 0], PB[:, 1], ans)
  
printd("LvsR")
PA = np.array(sorted(PP["L"], key=itemgetter(1)))
PB = np.array(sorted(PP["R"], key=itemgetter(1)))
if PA.size and PB.size:
  ans = conflict_180(PA[:, 1], PA[:, 0], PB[:, 1], PB[:, 0], ans)

def conflict_90(Ax,Ay,Bx,By,ans):
  """
  UP, RIGHTの例で書いて、90どずつ回転させて考える。。。？
  y = -x + k <-> x+y = k が同一の点は当たる可能性
  X = x+y, Y = x-yと読み替えて使えば良い。
  """
  NA, NB = len(Ax), len(Bx)
  if NA == 0 or NB == 0:
    return ans
  j = 0
  for i in range(NA):
    while j < NB-1 and Ax[i] > Bx[j]:
      j += 1
      if j == NB-1:
        break
    if Ax[i] == Bx[j]:
      # 衝突条件。ここ符号をちゃんと気にしよう
      if Ay[i] >= By[j]:
        printd((Ay[i], By[i], ans))
        ans = min(ans, Ay[i] - By[j])
  return ans

printd("UvsR")
PA = np.array(sorted(PP["U"], key=itemgetter(2)))
PB = np.array(sorted(PP["R"], key=itemgetter(2)))
if PA.size and PB.size:
  ans = conflict_90(PA[:, 2], PA[:, 3], PB[:, 2], PB[:, 3], ans)

printd("LvsU")
PA = np.array(sorted(PP["L"], key=itemgetter(3)))
PB = np.array(sorted(PP["U"], key=itemgetter(3)))
if PA.size and PB.size:
  ans = conflict_90(PA[:, 3], PA[:, 2], PB[:, 3], PB[:, 2], ans)

printd("DvsL")
PA = np.array(sorted(PP["L"], key=itemgetter(2)))
PB = np.array(sorted(PP["D"], key=itemgetter(2)))
if PA.size and PB.size:
  ans = conflict_90(PA[:, 2], PA[:, 3], PB[:, 2], PB[:, 3], ans)

printd("RvsD")
PA = np.array(sorted(PP["D"], key=itemgetter(3)))
PB = np.array(sorted(PP["R"], key=itemgetter(3)))
if PA.size and PB.size:
  ans = conflict_90(PA[:, 3], PA[:, 2], PB[:, 3], PB[:, 2], ans)
  
print(ans * 5 if ans < 1e16 else "SAFE")

Submission status: Runtime Error

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

#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define FOR(i,n,m) for(int i=(int)(n); i<=(int)(m); i++)
#define RFOR(i,n,m) for(int i=(int)(n); i>=(int)(m); i--)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define RITR(x,c) for(__typeof(c.rbegin()) x=c.rbegin();x!=c.rend();x++)
#define setp(n) fixed << setprecision(n)

template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }

#define ll long long
#define vll vector<ll>
#define vi vector<int>
#define pll pair<ll,ll>
#define pi pair<int,int>

#define all(a) (a.begin()),(a.end())
#define rall(a) (a.rbegin()),(a.rend())
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define ins insert

using namespace std;

const int X_MAX = 200020;
const int S_MAX = 400040;
const int INF = INT_MAX;

set<int> LSet[X_MAX];
set<int> RSet[X_MAX];
set<int> USet[X_MAX];
set<int> DSet[X_MAX];

set<int> LSum[S_MAX], LDiff[S_MAX];
set<int> RSum[S_MAX], RDiff[S_MAX];
set<int> USum[S_MAX], UDiff[S_MAX];
set<int> DSum[S_MAX], DDiff[S_MAX];

//-------------------------------------------------

int main(void)
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N; cin>>N;
    rep(i,N){
        int x,y; cin>>x>>y;
        char c; cin>>c;
        if (c=='L') LSet[y].ins(x), LSum[x+y].ins(x), LDiff[x-y+X_MAX].ins(x);
        if (c=='R') RSet[y].ins(x), RSum[x+y].ins(x), RDiff[x-y+X_MAX].ins(x);
        if (c=='U') USet[x].ins(y), USum[x+y].ins(x), UDiff[x-y+X_MAX].ins(x);
        if (c=='D') DSet[x].ins(y), DSum[x+y].ins(x), DDiff[x-y+X_MAX].ins(x);
    }
    int ans=INF;
    // L-R
    rep(y,X_MAX){
        for(auto r:RSet[y]){
            auto itr = LSet[y].upper_bound(r);
            if (itr==LSet[y].end()) continue;
            int l = *itr;
            chmin(ans,(l-r)*5);
        }
    }
    // U-D
    rep(x,X_MAX){
        for(auto u:USet[x]){
            auto itr = DSet[x].upper_bound(u);
            if (itr==DSet[x].end()) continue;
            int d = *itr;
            chmin(ans,(d-u)*5);
        }
    }
    // L-D
    rep(s,S_MAX){
        for(auto l:LSum[s]){
            auto itr = DSum[s].upper_bound(l);
            if (itr==DSum[s].end()) continue;
            int d = *itr;
            chmin(ans,(d-l)*10);
        }
    }
    // L-U
    rep(s,S_MAX){
        for(auto l:LDiff[s]){
            auto itr = UDiff[s].upper_bound(l);
            if (itr==UDiff[s].end()) continue;
            int u = *itr;
            chmin(ans,(u-l)*10);
        }
    }
    // U-R
    rep(s,S_MAX){
        for(auto u:USum[s]){
            auto itr = RSum[s].upper_bound(u);
            if (itr==RSum[s].end()) continue;
            int r = *itr;
            chmin(ans,(r-u)*10);
        }
    }
    // D-R
    rep(s,S_MAX){
        for(auto d:DDiff[s]){
            auto itr = RDiff[s].upper_bound(d);
            if (itr==RDiff[s].end()) continue;
            int r = *itr;
            chmin(ans,(r-d)*10);
        }
    }
    if (ans==INF){
        cout<<"SAFE\n";
    }else{
        cout<<ans<<endl;
    }
    return 0;
}

Submission status: Runtime Error

Solution code:
N = int(input())

Xaxis = [[] for _ in range(180001)]
Yaxis = [[] for _ in range(180001)]
sum = [[] for _ in range(360001)]
dif = [[] for _ in range(360001)]
value = []
ans = 10**8

for i in range(N):
    X,Y,P = input().split()
    X,Y = int(X),int(Y)
    value.append([X,Y,P])
    Xaxis[X].append(i)
    Yaxis[Y].append(i)
    sum[X+Y].append(i)
    dif[X-Y].append(i)

for i in Xaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'D' and value[i[k]][2] == 'U'):
                    if value[i[j]][1] >= value[i[k]][1]:
                        ans = min((value[i[j]][1]-value[i[k]][1])*5,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'D'):
                    if value[i[j]][1] <= value[i[k]][1]:
                        ans = min((value[i[k]][1]-value[i[j]][1])*5,ans)

for i in Yaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*5,ans)
                elif (value[i[j]][2] == 'R' and value[i[k]][2] == 'L'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*5,ans)

for i in sum:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if  (value[i[j]][2] == 'L' and value[i[k]][2] == 'D') or (value[i[j]][2] == 'U' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'D' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'U'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

for i in dif:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'U') or (value[i[j]][2] == 'D' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'D'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

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

Submission status: Runtime Error

Solution code:
N = int(input())

Xaxis = [[] for _ in range(180001)]
Yaxis = [[] for _ in range(180001)]
sum = [[] for _ in range(180001)]
dif = [[] for _ in range(180001)]
value = []
ans = 10**8

for i in range(N):
    X,Y,P = input().split()
    X,Y = int(X),int(Y)
    value.append([X,Y,P])
    Xaxis[X].append(i)
    Yaxis[Y].append(i)
    sum[X+Y].append(i)
    dif[X-Y].append(i)

for i in Xaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'D' and value[i[k]][2] == 'U'):
                    if value[i[j]][1] >= value[i[k]][1]:
                        ans = min((value[i[j]][1]-value[i[k]][1])*5,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'D'):
                    if value[i[j]][1] <= value[i[k]][1]:
                        ans = min((value[i[k]][1]-value[i[j]][1])*5,ans)

for i in Yaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*5,ans)
                elif (value[i[j]][2] == 'R' and value[i[k]][2] == 'L'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*5,ans)

for i in sum:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if  (value[i[j]][2] == 'L' and value[i[k]][2] == 'D') or (value[i[j]][2] == 'U' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'D' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'U'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

for i in dif:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'U') or (value[i[j]][2] == 'D' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'D'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

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

Submission status: Runtime Error

Solution code:
from bisect import bisect_left
import sys
input = sys.stdin.readline

N = int(input())
X = [0] * N
Y = [0] * N
U = [''] * N
for i in range(N):
    x, y, u = input().split()
    X[i] = int(x)
    Y[i] = int(y)
    U[i] = u

def calc(X, Y, U):
    mx = min(X)
    for i in range(N):
        X[i] -= mx
    my = min(Y)
    for i in range(N):
        Y[i] -= my
    Mx = max(X)
    My = max(Y)
    up = [[] for _ in range(Mx+1)]
    down = [[] for _ in range(Mx+1)]
    left = [[] for _ in range(My+1)]
    right = [[] for _ in range(My+1)]
    for x, y, u in zip(X, Y, U):
        if u == 'U':
            up[x].append(y)
        if u == 'D':
            down[x].append(y)
        if u == 'L':
            left[y].append(x)
        if u == 'R':
            right[y].append(x)
    ret = float('inf')
    for x in range(Mx+1):
        up[x].sort()
        down[x].sort()
        s = t = 0
        while s < len(up[x]):
            while t < len(down[x]) and up[x][s] > down[x][t]:
                t += 1
            if t < len(down[x]):
                ret = min(ret, (down[x][t] - up[x][t]) * 5)
            s += 1
    for y in range(My+1):
        right[y].sort()
        left[y].sort()
        s = t = 0
        while s < len(right[y]):
            while t < len(left[y]) and right[y][s] > left[y][t]:
                t += 1
            if t < len(left[y]):
                ret = min(ret, (left[y][t] - right[y][t]) * 5)
            s += 1
    return ret


ans = calc(X, Y, U)
nX = [X[i] - Y[i] for i in range(N)]
nY = [X[i] + Y[i] for i in range(N)]

U1 = []
for u in U:
    if u == 'R':
        U1.append('U')
    elif u == 'L':
        U1.append('D')
    else:
        U1.append(u)
ans = min(ans, calc(nX, nY, U1))

U2 = []
for u in U:
    if u == 'U':
        U2.append('L')
    elif u == 'D':
        U2.append('R')
    else:
        U2.append(u)
ans = min(ans, calc(nX, nY, U2))

print(ans if ans < float('inf') else 'SAFE')

Submission status: Runtime Error

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()
    d_list.sort()
    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])
    l_list.sort(key=lambda x: x[1])
    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])
    l_list.sort(key=lambda x: x[0]-x[1])
    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])
    l_list.sort(key=lambda x: x[0]+x[1])
    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(1/0)
    else:
        print(ans[0])


main()

Submission status: Runtime Error

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 = [deque() for _ in range(200001)]
  LR = [deque() for _ in range(200001)]
  UR = [deque() for _ in range(400001)]
  DL = [deque() for _ in range(400001)]
  DR = [deque() for _ in range(400001)]
  UL = [deque() for _ in range(400001)]


  for X,Y,u in XYU:
    X = int(X)
    Y = int(Y)
    if u=='R':
      LR[Y].append((X,u))
      UR[X+Y].append((Y,u))
      DR[X-Y+200000].append((Y,u))
    elif u=='L':
      LR[Y].append((X,u))
      DL[X+Y].append((Y,u))
      UL[X-Y+200000].append((Y,u))
    elif u=='U':
      UD[X].append((Y,u))
      UR[X+Y].append((Y,u))
      UL[X-Y+200000].append((Y,u))
    else:
      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:
    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:
    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:
    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:
    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:
    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:
    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: Runtime Error

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


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



D1 = defaultdict(list)
D2 = defaultdict(list)
D3 = defaultdict(list)
D4 = defaultdict(list)
n = I()
L = []
ans = INF
for i in range(n):
    x, y, u = LS()
    x = int(x)
    y = int(y)
    D1[(x + y, u)] += [x]
    D2[(x - y, u)] += [x]
    D3[x, u] += [(x, y)]
    D4[y, u] += [(x, y)]
    L += [(x, y, u)]

for xi, yi, u in L:
    if u == "R" and D2[(xi - yi, "D")]:
        ll = D2[(xi - yi, "D")]
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "R" and D1[(xi + yi, "U")]:
        ll = D1[(xi + yi, "U")]
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii] - xi)
    if u == "L" and D2[(xi - yi , "U")]:
        ll = D2[(xi - yi, "D")]
        ii = bisect_right(ll, xi)
        if ii:
            ret = min(ll[ii] - xi)
    if u == "L" and D1[(xi + yi, "D")]:
        ll = D1[(xi + yi, "D")]
        ii = bisect_right(ll, xi)
        if ii:
            ans = min(ans, xi - ll[ii - 1])
    if u == "L" and D4[yi, "R"]:
        ll = D4[(yi, "R")]
        ii = bisect_right(ll, (yi, 0))
        ans = min(ans, (ll[ii][1] - yi) / 2)
    if u == "D" and D3[xi, "U"]:
        ll = D3[(xi, "U")]
        ii = bisect_right(ll, (xi, 0))
        ans = min(ans, abs(ll[ii][1] - yi) / 2)


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

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

"""

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

Submission status: Runtime Error

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


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



D1 = defaultdict(list)
D2 = defaultdict(list)
D3 = defaultdict(list)
D4 = defaultdict(list)
n = I()
L = []
ans = INF
for i in range(n):
    x, y, u = LS()
    x = int(x)
    y = int(y)
    D1[(x + y, u)] += [x]
    D2[(x - y, u)] += [x]
    D3[x, u] += [(x, y)]
    D4[y, u] += [(x, y)]
    L += [(x, y, u)]

for xi, yi, u in L:
    if u == "R" and D2[(xi - yi, "D")]:
        ll = D2[(xi - yi, "D")]
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii][0] - xi)
    if u == "R" and D1[(xi + yi, "U")]:
        ll = D1[(xi + yi, "U")]
        ii = bisect_right(ll, xi)
        if ii < len(ll):
            ans = min(ans, ll[ii][0] - xi)
    if u == "L" and D2[(xi - yi , "U")]:
        ll = D2[(xi - yi, "D")]
        ii = bisect_right(ll, xi)
        if ii:
            ret = min(ll[ii][0] - xi)
    if u == "L" and D1[(xi + yi, "D")]:
        ll = D1[(xi + yi, "D")]
        ii = bisect_right(ll, xi)
        if ii:
            ans = min(ans, xi - ll[ii - 1])
    if u == "L" and D4[yi, "R"]:
        ll = D4[(yi, "R")]
        ii = bisect_right(ll, (yi, 0))
        ans = min(ans, (ll[ii][1] - yi) / 2)
    if u == "D" and D3[xi, "U"]:
        ll = D3[(xi, "U")]
        ii = bisect_right(ll, (xi, 0))
        ans = min(ans, abs(ll[ii][1] - yi) / 2)


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

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

"""

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

Submission status: Runtime Error

Solution code:
N = int(input())

Xaxis = [[] for _ in range(200001)]
Yaxis = [[] for _ in range(200001)]
sum = [[] for _ in range(400001)]
dif = [[] for _ in range(40001)]
value = []
ans = 10**8

for i in range(N):
    X,Y,P = input().split()
    X,Y = int(X),int(Y)
    value.append([X,Y,P])
    Xaxis[X].append(i)
    Yaxis[Y].append(i)
    sum[X+Y].append(i)
    dif[X-Y].append(i)

for i in Xaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'D' and value[i[k]][2] == 'U'):
                    if value[i[j]][1] >= value[i[k]][1]:
                        ans = min((value[i[j]][1]-value[i[k]][1])*5,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'D'):
                    if value[i[j]][1] <= value[i[k]][1]:
                        ans = min((value[i[k]][1]-value[i[j]][1])*5,ans)

for i in Yaxis:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*5,ans)
                elif (value[i[j]][2] == 'R' and value[i[k]][2] == 'L'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*5,ans)

for i in sum:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if  (value[i[j]][2] == 'L' and value[i[k]][2] == 'D') or (value[i[j]][2] == 'U' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'D' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'U'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

for i in dif:
    l = len(i)
    if l >= 2:
        for j in range(l-1):
            for k in range(j+1,l):
                if (value[i[j]][2] == 'L' and value[i[k]][2] == 'U') or (value[i[j]][2] == 'D' and value[i[k]][2] == 'R'):
                    if value[i[j]][0] >= value[i[k]][0]:
                        ans = min((value[i[j]][0]-value[i[k]][0])*10,ans)
                elif (value[i[j]][2] == 'U' and value[i[k]][2] == 'L') or (value[i[j]][2] == 'R' and value[i[k]][2] == 'D'):
                    if value[i[j]][0] <= value[i[k]][0]:
                        ans = min((value[i[k]][0]-value[i[j]][0])*10,ans)

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