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

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
import bisect
n=int(input())
arr=[list(input().split()) for _ in range(n)]
yaxis={}
xaxis={}
saxis={}
t=list()

for i in range(n):
    x,y,u=arr[i]
    x=int(x)
    y=int(y)
    if x+y not in saxis:
        saxis[x+y]=[[y,u]]
    else:
        saxis[x+y].append([y,u])
    if u=="U" or u=="D":
        if x in xaxis:
            xaxis[x].append([y,u])
        else:
            xaxis[x]=[[y,u]]
    else:
        if y in yaxis:
            yaxis[y].append([x,u])
        else:
            yaxis[y]=[[x,u]]

for s in xaxis:
    s=sorted(xaxis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="U" and s[k][1]=="D":
            time=(s[k][0]-s[k-1][0])*5
            heapq.heappush(t,time)
for s in yaxis:
    s=sorted(yaxis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="R" and s[k][1]=="L":
            time=(s[k][0]-s[k-1][0])*5
            heapq.heappush(t,time)
for s in saxis:
    s=sorted(saxis[s],key=lambda x: x[0])
    for k in range(1,len(s)):
        if s[k-1][1]=="U" and (s[k][1]=="R" or s[k][1]=="L"):
            time=10*(s[k][0]-s[k-1][0])
            heapq.heappush(t,time)
        elif (s[k-1][1]=="R" or s[k-1][1]=="L") and s[k][1]=="D":
            time=10*(s[k][0]-s[k-1][0])
            print(time)
            heapq.heappush(t,time)
if not t:
  print("SAFE")
else:
  print(heapq.heappop(t))

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

INF = float("inf")


def f(mp, dir1, dir2):
    res = INF
    for p in mp.values():
        p.sort()
        mn = INF
        for i in range(1, len(p)):
            if p[i - 1][1] == dir1 and p[i][1] == dir2:
                mn = min(mn, p[i][0] - p[i - 1][0])
        res = min(res, mn)
    return res


X = []
Y = []
DIR = []

N = int(input())
for i in range(N):
    x, y, u = map(str, input().split())
    X.append(int(x))
    Y.append(int(y))
    #  URDL = 0123
    if u == 'U':
        DIR.append(0)
    if u == 'R':
        DIR.append(1)
    if u == 'D':
        DIR.append(2)
    if u == 'L':
        DIR.append(3)

ans = INF
# UD
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (0, 2):
        continue
    mp[X[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 2) * 5)
# LR
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (1, 3):
        continue
    mp[Y[i]].append((X[i], DIR[i]))
ans = min(ans, f(mp, 1, 3) * 5)

# UR
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (0, 1):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 1) * 10)
# RD
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (1, 2):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 1, 2) * 10)
# DL
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (2, 3):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 3, 2) * 10)
# LU
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (3, 0):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 3) * 10)

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

INF = float("inf")


def f(mp, dir1, dir2):
    res = INF
    for p in mp.values():
        p.sort()
        mn = INF
        for i in range(1, len(p)):
            if p[i - 1][1] == dir1 and p[i][1] == dir2:
                mn = min(mn, p[i][0] - p[i - 1][0])
        res = min(res, mn)
    return res


X = []
Y = []
DIR = []

N = int(input())
for i in range(N):
    x, y, u = map(str, input().split())
    X.append(int(x))
    Y.append(int(y))
    #  URDL = 0123
    if u == 'U':
        DIR.append(0)
    if u == 'R':
        DIR.append(1)
    if u == 'D':
        DIR.append(2)
    if u == 'L':
        DIR.append(3)

ans = INF
# UD
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (0, 2):
        continue
    mp[X[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 2) * 5)
# LR
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (1, 3):
        continue
    mp[Y[i]].append((X[i], DIR[i]))
ans = min(ans, f(mp, 1, 3) * 5)

# UR
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (0, 1):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 1, 0) * 10)
# RD
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (1, 2):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 1, 2) * 10)
# DL
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (2, 3):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 3) * 10)
# LU
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (3, 0):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 3) * 10)

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

INF = float("inf")


def f(mp, dir1, dir2):
    res = INF
    for p in mp.values():
        p.sort()
        mn = INF
        for i in range(1, len(p)):
            if p[i - 1][1] == dir1 and p[i][1] == dir2:
                mn = min(mn, p[i][0] - p[i - 1][0])
        res = min(res, mn)
    return res


X = []
Y = []
DIR = []

N = int(input())
for i in range(N):
    x, y, u = map(str, input().split())
    X.append(int(x))
    Y.append(int(y))
    #  URDL = 0123
    if u == 'U':
        DIR.append(0)
    if u == 'R':
        DIR.append(1)
    if u == 'D':
        DIR.append(2)
    if u == 'L':
        DIR.append(3)

ans = INF
# UD
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (0, 2):
        continue
    mp[X[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 2) * 5)
# LR
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (1, 3):
        continue
    mp[Y[i]].append((X[i], DIR[i]))
ans = min(ans, f(mp, 1, 3) * 5)

# UR
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (0, 1):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 1) * 10)
# RD
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (1, 2):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 1, 2) * 10)
# DL
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (2, 3):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 3, 2) * 10)
# LU
mp = defaultdict(list)
for i in range(N):
    if DIR[i] not in (3, 0):
        continue
    mp[X[i] + Y[i]].append((Y[i], DIR[i]))
ans = min(ans, f(mp, 0, 3) * 10)

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

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from bisect import *

def into_dict(dics,x,y,u):
  x,y = int(x),int(y)
  insort(dics[u+'_x'][x],y)
  insort(dics[u+'_y'][y],x)
  insort(dics[u+'_xpy'][x+y],x)
  insort(dics[u+'_ymx'][y-x],x)
  return dics

def para(dics,dic1,dic2):
  ans = float('inf')
  for k,v in dics[dic1].items():
    for zahyou in v[1:-1]:
      ind = bisect_right(dics[dic2][k],zahyou)
      dis = zahyou-dics[dic2][k][ind-1]
      ans = min(ans,dis)
  return ans

def solve():
  ans = []
  N = int(input())
  dics = defaultdict(lambda: defaultdict(lambda: [-float('inf'),float('inf')]))
  for i in range(N):
    dics = into_dict(dics,*input().split())
  lis1 = [['L_y','R_y'],['D_x','U_x']]
  lis2 = [['L_ymx','U_ymx'],['U_xpy','R_xpy'],['L_xpy','D_xpy'],['D_y_x','R_y_x']]
  for arg in lis1:
    ans.append(para(dics,*arg)*5)
  for arg in lis2:
    ans.append(para(dics,*arg)*10)
  ans = min(ans)
  return ans if ans<float('inf') else 'SAFE'
print(solve())

Submission status: Wrong Answer

Solution code:
import bisect
def main():
    N = int(input())
    dx = {}
    dy = {}
    dxpy = {}
    dxmy = {}
    for _ in range(N):
        x, y, u = input().split()
        x = int(x)
        y = int(y)
        if u in dx:
            if x in dx[u]:
                dx[u][x].append(y)
            else:
                dx[u][x] = [y]
            if y in dy[u]:
                dy[u][y].append(x)
            else:
                dy[u][y] = [x]
            if x + y in dxpy[u]:
                dxpy[u][x+y].append(y)
            else:
                dxpy[u][x+y] = [y]
            if x - y in dxmy[u]:
                dxmy[u][x-y].append(y)
            else:
                dxmy[u][x-y] = [y]
        else:
            dx[u] = {}
            dx[u][x] = [y]
            dy[u] = {}
            dy[u][y] = [x]
            dxpy[u] = {}
            dxpy[u][x+y] = [y]
            dxmy[u] = {}
            dxmy[u][x-y] = [y]
    for d in [dx, dy, dxpy, dxmy]:
        for j in d:
            for k in d[j]:
                d[j][k].sort()
    M = 3 * (10**6)
    ###SHOUMEN SHOTOTSU
    # U and D
    if "U" in dx and "D" in dx:
        for x in dx["U"]:
            if x not in dx["D"]:
                continue
            for y in dx["U"][x]:
                yi = bisect.bisect_left(dx["D"][x], y)
                if yi < len(dx["D"][x]):
                    M = min((dx["D"][x][yi] - y)*5, M)
    # L and R
    if "L" in dy and "R" in dy:
        for y in dy["R"]:
            if y not in dy["L"]:
                continue
            for x in dy["R"][y]:
                xi = bisect.bisect_left(dy["L"][y], x)
                if xi < len(dy["L"][y]):
                    M = min((dy["L"][y][xi] - x)*5, M)
    ###KOUSA
    # D and R
    if "D" in dy and "R" in dy:
        for s in dxmy["R"]:
            if s not in dxmy["D"]:
                continue
            for p in dxmy["R"][s]:
                yi = bisect.bisect_left(dxmy["D"][s], p)
                if yi < len(dxmy["D"][s]):
                    M = min((dxmy["D"][s][yi] - p)*10, M)
    # L and U
    if "L" in dy and "U" in dy:
        for s in dxmy["U"]:
            if s not in dxmy["L"]:
                continue
            for p in dxmy["U"][s]:
                yi = bisect.bisect_left(dxmy["L"][s], p)
                if yi < len(dxmy["L"][s]):
                    M = min((dxmy["L"][s][yi] - p)*10, M)
    # U and R
    if "U" in dy and "R" in dy:
        for s in dxpy["U"]:
            if s not in dxpy["R"]:
                continue
            for p in dxpy["U"][s]:
                yi = bisect.bisect_left(dxpy["R"][s], p)
                if yi < len(dxpy["R"][s]):
                    M = min((dxpy["R"][s][yi] - p)*10, M)
    # L and D
    if "D" in dy and "L" in dy:
        for s in dxpy["L"]:
            if s not in dxpy["D"]:
                continue
            for p in dxpy["L"][s]:
                yi = bisect.bisect_left(dxpy["D"][s], p)
                if yi < len(dxpy["D"][s]):
                    M = min((dxpy["D"][s][yi] - p)*10, M)
    return M
x = main()
if x < 3 * (10**5):
    print(x)
else:
    print('SAFE')

Submission status: Wrong Answer

Solution code:
import bisect
def main():
    N = int(input())
    dx = {}
    dy = {}
    dxpy = {}
    dxmy = {}
    for _ in range(N):
        x, y, u = input().split()
        x = int(x)
        y = int(y)
        if u in dx:
            if x in dx[u]:
                dx[u][x].append(y)
            else:
                dx[u][x] = [y]
            if y in dy[u]:
                dy[u][y].append(x)
            else:
                dy[u][y] = [x]
            if x + y in dxpy[u]:
                dxpy[u][x+y].append(y)
            else:
                dxpy[u][x+y] = [y]
            if x - y in dxmy[u]:
                dxmy[u][x-y].append(y)
            else:
                dxmy[u][x-y] = [y]
        else:
            dx[u] = {}
            dx[u][x] = [y]
            dy[u] = {}
            dy[u][y] = [x]
            dxpy[u] = {}
            dxpy[u][x+y] = [y]
            dxmy[u] = {}
            dxmy[u][x-y] = [y]
    for d in [dx, dy, dxpy, dxmy]:
        for j in d:
            for k in d[j]:
                d[j][k].sort()
    M = 3 * (10**5)
    ###SHOUMEN SHOTOTSU
    # U and D
    if "U" in dx and "D" in dx:
        for x in dx["U"]:
            if x not in dx["D"]:
                continue
            for y in dx["U"][x]:
                yi = bisect.bisect_left(dx["D"][x], y)
                if yi < len(dx["D"][x]):
                    M = min((dx["D"][x][yi] - y)*5, M)
    # L and R
    if "L" in dy and "R" in dy:
        for y in dy["R"]:
            if y not in dy["L"]:
                continue
            for x in dy["R"][y]:
                xi = bisect.bisect_left(dy["L"][y], x)
                if xi < len(dy["L"][y]):
                    M = min((dy["L"][y][xi] - x)*5, M)
    ###KOUSA
    # D and R
    if "D" in dy and "R" in dy:
        for s in dxmy["R"]:
            if s not in dxmy["D"]:
                continue
            for p in dxmy["R"][s]:
                yi = bisect.bisect_left(dxmy["D"][s], p)
                if yi < len(dxmy["D"][s]):
                    M = min((dxmy["D"][s][yi] - p)*10, M)
    # L and U
    if "L" in dy and "U" in dy:
        for s in dxmy["U"]:
            if s not in dxmy["L"]:
                continue
            for p in dxmy["U"][s]:
                yi = bisect.bisect_left(dxmy["L"][s], p)
                if yi < len(dxmy["L"][s]):
                    M = min((dxmy["L"][s][yi] - p)*10, M)
    # U and R
    if "U" in dy and "R" in dy:
        for s in dxpy["U"]:
            if s not in dxpy["R"]:
                continue
            for p in dxpy["U"][s]:
                yi = bisect.bisect_left(dxpy["R"][s], p)
                if yi < len(dxpy["R"][s]):
                    M = min((dxpy["R"][s][yi] - p)*10, M)
    # L and D
    if "D" in dy and "L" in dy:
        for s in dxpy["L"]:
            if s not in dxpy["D"]:
                continue
            for p in dxpy["L"][s]:
                yi = bisect.bisect_left(dxpy["D"][s], p)
                if yi < len(dxpy["D"][s]):
                    M = min((dxpy["D"][s][yi] - p)*10, M)
    return M
x = main()
if x < 3 * (10**5):
    print(x)
else:
    print('SAFE')

Submission status: Wrong Answer

Solution code:
N = int(input())
X = [None] * N
Y = [None] * N
U = [None] * N
for i in range(N):
  X[i], Y[i], U[i] = input().split()

def main():
  for i in range(N):
    for j in range(N):
      if (i > j):
        continue

      if (U[i] == U[j]):
        continue

      '''
      U vs R ... Ux > Rx and Ux - Rx == Ry - Uy
      U vs D ... Ux == Dx and Uy < Dy and (Uy - Dy) % 2 == 0 # Note: if Uy = 3, Dy = 0, conflict does NOT happen
      U vs L ... Uy > Ly and Uy - Ly == Lx - Ux
      '''
      if (U[i] == 'U' and U[j] == 'R'):
        if (int(X[i]) > int(X[j]) and int(X[i]) - int(X[j]) == int(Y[j]) - int(Y[i])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[j]) - int(Y[i]))*10))

      if (U[i] == 'U' and U[j] == 'D'):
        if (int(X[i]) == int(X[j])) and (int(Y[i]) < int(Y[j])) and (int(Y[i]) - int(Y[j])) % 2 == 0:
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*5))

      if (U[i] == 'U' and U[j] == 'L'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*10))

      '''
      R vs U ... Ry > Uy and Ry - Uy == Ux - Rx
      R vs D ... Dx > Rx and Dx - Rx == Dy - Ry
      R vs L ... Ry == Ly and Rx < Lx and (Rx - Lx) % 2 == 0
      '''
      if (U[i] == 'R' and U[j] == 'U'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[j]) - int(X[i]))*10))

      if (U[i] == 'R' and U[j] == 'D'):
        if (int(X[j]) > int(X[i]) and int(X[j]) - int(X[i]) == int(Y[j]) - int(Y[i])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[j]) - int(X[i]))*10))

      if (U[i] == 'R' and U[j] == 'L'):
        if (int(Y[i]) == int(Y[j])) and (int(X[i]) < int(X[j])) and (int(X[i]) - int(X[j])) % 2 == 0:
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[i]) - int(X[j]))*5))

      '''
      D vs U ... Dx == Ux and Dy > Uy and (Dy - Uy) % 2 == 0
      D vs R ... Dy > Ry and Dy - Ry == Dx - Rx
      D vs L ... Dy > Ly and Dy - Ly == Lx - Dx
      '''
      if (U[i] == 'D' and U[j] == 'U'):
        if (int(X[i]) == int(X[j])) and (int(Y[i]) > int(Y[j])) and (int(Y[i]) - int(Y[j])) % 2 == 0:
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*5))

      if (U[i] == 'D' and U[j] == 'R'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[i]) - int(X[j])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*10))

      if (U[i] == 'D' and U[j] == 'L'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*10))

      '''
      L vs U ... Lx > Ux and Lx - Ux == Ly - Uy
      L vs D ... Lx > Dx and Lx - Dx == Dy - Ly
      L vs R ... Ly == Ry and Lx > Rx and (Rx - Lx) % 2 == 0
      '''
      if (U[i] == 'L' and U[j] == 'U'):
        if (int(X[i]) > int(X[j]) and int(X[i]) - int(X[j]) == int(Y[i]) - int(Y[j])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[i]) - int(X[j]))*10))
      
      if (U[i] == 'L' and U[j] == 'D'):
        if (int(X[i]) > int(X[j]) and int(X[i]) - int(X[j]) == int(Y[j]) - int(Y[i])):
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[i]) - int(X[j]))*10))

      if (U[i] == 'L' and U[j] == 'R'):
        if (int(Y[i]) == int(Y[j])) and (int(X[i]) > int(X[j])) and (int(X[j]) - int(X[i])) % 2 == 0:
          #print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[j]) - int(X[i]))*5))

  return('SAFE')

print(main())

Submission status: Wrong Answer

Solution code:
n = int(input())
xx = [[] for _ in range(200001)]
yy = [[] for _ in range(200001)]
xy = [[] for _ in range(400001)]
yx = [[] for _ in range(200001)]
for _ in range(n):
    x, y, u = input().split()
    if u=='U' or u=='D':
        xx[int(x)].append((int(y), u))
    else:
        yy[int(y)].append((int(x), u))
    xy[int(x)+int(y)].append((int(x), u))
    yx[int(y)-int(x)].append((int(x), u))
ans = 10**10
for i in xx:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='U':
            d = j
        elif ans > (j-d)*5:
            ans = (j-d)*5
for i in yy:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='R':
            d = j
        elif ans > (j-d)*5:
            ans = (j-d)*5
for i in xy:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='R':
            d = j
        elif k=='U' and ans > (j-d)*10:
            ans = (j-d)*10
    d = -10**10
    for j, k in i:
        if k=='D':
            d = j
        elif k=='L' and ans > (j-d)*10:
            ans = (j-d)*10
for i in yx:
    if len(i)<=1:
        continue
    i.sort()
    d = -10**10
    for j, k in i:
        if k=='U':
            d = j
        elif k=='L' and ans > (j-d)*10:
            ans = (j-d)*10
    d = -10**10
    for j, k in i:
        if k=='R':
            d = j
        elif k=='D' and ans > (j-d)*10:
            ans = (j-d)*10
if ans == 10**10:
    print('safe')
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
X = [None] * N
Y = [None] * N
U = [None] * N
for i in range(N):
  X[i], Y[i], U[i] = input().split()

def main():
  for i in range(N):
    for j in range(N):
      if (i > j):
        continue

      if (U[i] == U[j]):
        continue

      '''
      U vs R ... Ux > Rx and Ux - Rx == Ry - Uy
      U vs D ... Ux == Dx and Uy < Dy and (Uy - Dy) % 2 == 0 # Note: if Uy = 3, Dy = 0, conflict does NOT happen
      U vs L ... Uy > Ly and Uy - Ly == Lx - Ux
      '''
      if (U[i] == 'U' and U[j] == 'R'):
        if (int(X[i]) > int(X[j]) and int(X[i]) - int(X[j]) == int(Y[j]) - int(Y[i])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[j]) - int(Y[i]))*10))

      if (U[i] == 'U' and U[j] == 'D'):
        if (int(X[i]) == int(X[j])) and (int(Y[i]) < int(Y[j])) and (int(Y[i]) - int(Y[j])) % 2 == 0:
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*5))

      if (U[i] == 'U' and U[j] == 'L'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*10))

      '''
      R vs U ... Ry > Uy and Ry - Uy == Ux - Rx
      R vs D ... Dx > Rx and Dx - Rx == Dy - Ry
      R vs L ... Ry == Ly and Rx < Lx and (Rx - Lx) % 2 == 0
      '''
      if (U[i] == 'R' and U[j] == 'U'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[j]) - int(X[i]))*10))

      if (U[i] == 'R' and U[j] == 'D'):
        if (int(X[j]) > int(X[i]) and int(X[j]) - int(X[i]) == int(Y[j]) - int(Y[i])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[j]) - int(X[i]))*10))

      if (U[i] == 'R' and U[j] == 'L'):
        if (int(Y[i]) == int(Y[j])) and (int(X[i]) < int(X[j])) and (int(X[i]) - int(X[j])) % 2 == 0:
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[i]) - int(X[j]))*5))

      '''
      D vs U ... Dx == Ux and Dy > Uy and (Dy - Uy) % 2 == 0
      D vs R ... Dy > Ry and Dy - Ry == Dx - Rx
      D vs L ... Dy > Ly and Dy - Ly == Lx - Dx
      '''
      if (U[i] == 'D' and U[j] == 'U'):
        if (int(X[i]) == int(X[j])) and (int(Y[i]) > int(Y[j])) and (int(Y[i]) - int(Y[j])) % 2 == 0:
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*5))

      if (U[i] == 'D' and U[j] == 'R'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[i]) - int(X[j])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*10))

      if (U[i] == 'D' and U[j] == 'L'):
        if (int(Y[i]) > int(Y[j]) and int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(Y[i]) - int(Y[j]))*10))

      '''
      L vs U ... Lx > Ux and Lx - Ux == Ly - Uy
      L vs D ... Lx > Dx and Lx - Dx == Dy - Ly
      L vs R ... Ly == Ry and Lx > Rx and (Rx - Lx) % 2 == 0
      '''
      if (U[i] == 'L' and U[j] == 'U'):
        if (int(X[i]) > int(X[j]) and int(X[i]) - int(X[j]) == int(Y[i]) - int(Y[j])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[i]) - int(X[j]))*10))
      
      if (U[i] == 'L' and U[j] == 'D'):
        if (int(X[i]) > int(X[j]) and int(X[i]) - int(X[j]) == int(Y[j]) - int(Y[i])):
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[i]) - int(X[j]))*10))

      if (U[i] == 'L' and U[j] == 'R'):
        if (int(Y[i]) == int(Y[j])) and (int(X[i]) > int(X[j])) and (int(X[j]) - int(X[i])) % 2 == 0:
          print('{} {}'.format(U[i], U[j]))
          return(abs((int(X[j]) - int(X[i]))*5))

  return('SAFE')

print(main())

Submission status: Wrong Answer

Solution code:
N = int(input())
X = [None] * N
Y = [None] * N
U = [None] * N
for i in range(N):
  X[i], Y[i], U[i] = input().split()

def main():
  for i in range(N):
    for j in range(N):
      if (i > j):
        continue

      if (U[i] == U[j]):
        continue

      '''
      U vs R ... Ux - Ry == Ry - Uy
      U vs D ... Ux == Dx and Uy < Dy and (Uy - Dy) % 2 == 0 # Note: if Uy = 3, Dy = 0, conflict does NOT happen
      U vs L ... Uy - Ly == Lx - Ux
      '''
      if (U[i] == 'U' and U[j] == 'R') or (U[i] == 'R' and U[j] == 'U'):
        if (int(X[i]) - int(X[j]) == int(Y[j]) - int(Y[i])):
          return(abs((int(Y[j]) - int(Y[i]))*10))

      if (U[i] == 'U' and U[j] == 'D'):
        if (int(X[i]) == int(X[j])) and (int(Y[i]) < int(Y[j])) and (int(Y[i]) - int(Y[j])) % 2 == 0:
          return(abs((int(Y[i]) - int(Y[j]))*5))

      if (U[i] == 'U' and U[j] == 'L') or (U[i] == 'L' and U[j] == 'U'):
        if (int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          return(abs((int(Y[i]) - int(Y[j]))*10))

      '''
      R vs U ... Ry - Uy == Ux - Rx
      R vs D ... Dx - Rx == Dy - Ry
      R vs L ... Ry == Ly and Rx > Lx and (Rx - Lx) % 2 == 0
      '''
      if (U[i] == 'R' and U[j] == 'U'):
        if (int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          return(abs((int(X[j]) - int(X[i]))*10))

      if (U[i] == 'R' and U[j] == 'D') or (U[i] == 'D' and U[j] == 'R'):
        if (int(X[j]) - int(X[i]) == int(Y[j]) - int(Y[i])):
          return(abs((int(X[j]) - int(X[i]))*10))

      if (U[i] == 'R' and U[j] == 'L'):
        if (int(Y[i]) == int(Y[j])) and (int(X[i]) > int(X[j])) and (int(X[i]) - int(X[j])) % 2 == 0:
          return(abs((int(X[i]) - int(X[j]))*5))

      '''
      D vs U ... Dx == Ux and Dy > Uy and (Dy - Uy) % 2 == 0
      D vs R ... Dy - Ry == Dx - Rx
      D vs L ... Dy - Ly == Lx - Dx
      '''
      if (U[i] == 'D' and U[j] == 'U'):
        if (int(X[i]) == int(X[j])) and (int(Y[i]) > int(Y[j])) and (int(Y[i]) - int(Y[j])) % 2 == 0:
          return(abs((int(Y[i]) - int(Y[j]))*5))

      if (U[i] == 'D' and U[j] == 'R'):
        if (int(Y[i]) - int(Y[j]) == int(X[i]) - int(X[j])):
          return(abs((int(Y[i]) - int(Y[j]))*10))

      if (U[i] == 'D' and U[j] == 'L'):
        if (int(Y[i]) - int(Y[j]) == int(X[j]) - int(X[i])):
          return(abs((int(Y[i]) - int(Y[j]))*10))

      '''
      L vs U ... Lx - Ux == Ly - Uy
      L vs D ... Lx - Dx == Dy - Ly
      L vs R ... Ly == Ry and Lx < Rx and (Rx - Lx) % 2 == 0
      '''
      if (U[i] == 'L' and U[j] == 'U'):
        if (int(X[i]) - int(X[j]) == int(Y[i]) - int(Y[j])):
          return(abs((int(X[i]) - int(X[j]))*10))
      
      if (U[i] == 'L' and U[j] == 'D'):
        if (int(X[i]) - int(X[j]) == int(Y[j]) - int(Y[i])):
          return(abs((int(X[i]) - int(X[j]))*10))

      if (U[i] == 'L' and U[j] == 'R'):
        if (int(Y[i]) == int(Y[j])) and (int(X[i]) < int(X[j])) and (int(X[j]) - int(X[i])) % 2 == 0:
          return(abs((int(X[j]) - int(X[i]))*5))

print(main())

Submission status: Wrong Answer

Solution code:
import bisect
def main():
    N = int(input())
    dx = {}
    dy = {}
    dxpy = {}
    dxmy = {}
    for _ in range(N):
        x, y, u = input().split()
        x = int(x)
        y = int(y)
        if u in dx:
            if x in dx[u]:
                dx[u][x].append(y)
            else:
                dx[u][x] = [y]
            if y in dy[u]:
                dy[u][y].append(x)
            else:
                dy[u][y] = [x]
            if x + y in dxpy[u]:
                dxpy[u][x+y].append(y)
            else:
                dxpy[u][x+y] = [y]
            if x - y in dxmy[u]:
                dxmy[u][x-y].append(y)
            else:
                dxmy[u][x-y] = [y]
        else:
            dx[u] = {}
            dx[u][x] = [y]
            dy[u] = {}
            dy[u][y] = [x]
            dxpy[u] = {}
            dxpy[u][x+y] = [y]
            dxmy[u] = {}
            dxmy[u][x-y] = [y]
    for d in [dx, dy, dxpy, dxmy]:
        for j in d:
            for k in d[j]:
                d[j][k].sort()
    M = 3 * (10**5)
    ###SHOUMEN SHOTOTSU
    # U and D
    if "U" in dx and "D" in dx:
        for x in dx["U"]:
            if x not in dx["D"]:
                continue
            for y in dx["U"][x]:
                yi = bisect.bisect_left(dx["D"][x], y)
                if yi < len(dx["D"][x]):
                    M = min((dx["D"][x][yi] - y)*5, M)
    # L and R
    if "L" in dy and "R" in dy:
        for y in dy["R"]:
            if y not in dy["L"]:
                continue
            for x in dy["R"][y]:
                xi = bisect.bisect_left(dy["L"][y], x)
                if xi < len(dy["L"][y]):
                    M = min((dy["L"][y][xi] - x)*5, M)
    ###KOUSA
    # D and R
    if "D" in dy and "R" in dy:
        for s in dxmy["R"]:
            if s not in dxmy["D"]:
                continue
            for p in dxmy["R"][s]:
                yi = bisect.bisect_left(dxmy["D"][s], p)
                if yi < len(dxmy["D"][s]):
                    M = min((dxmy["D"][s][yi] - p)*10, M)
    # L and U
    if "L" in dy and "U" in dy:
        for s in dxmy["U"]:
            if s not in dxmy["L"]:
                continue
            for p in dxmy["U"][s]:
                yi = bisect.bisect_left(dxmy["L"][s], p)
                if yi < len(dxmy["L"][s]):
                    M = min((dxmy["L"][s][yi] - p)*10, M)
                    print("LU")
    # U and R
    if "U" in dy and "R" in dy:
        for s in dxpy["U"]:
            if s not in dxpy["R"]:
                continue
            for p in dxpy["U"][s]:
                yi = bisect.bisect_left(dxpy["R"][s], p)
                if yi < len(dxpy["R"][s]):
                    M = min((dxpy["R"][s][yi] - p)*10, M)
    # L and D
    if "D" in dy and "L" in dy:
        for s in dxpy["L"]:
            if s not in dxpy["D"]:
                continue
            for p in dxpy["L"][s]:
                yi = bisect.bisect_left(dxpy["D"][s], p)
                if yi < len(dxpy["D"][s]):
                    M = min((dxpy["D"][s][yi] - p)*10, M)
    return M
x = main()
if x < 3 * (10**5):
    print(x)
else:
    print('SAFE')