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

Solution in Rust (1.42.0) (judge verdict: Accepted)

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, [graph1; $len:expr]) => {{
        let mut g = vec![vec![]; $len];
        let ab = read_value!($next, [(usize1, usize1)]);
        for (a, b) in ab {
            g[a].push(b);
            g[b].push(a);
        }
        g
    }};
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };
    ($next:expr, usize1) => (read_value!($next, usize) - 1);
    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        read_value!($next, [$t; len])
    }};
    ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

trait Bisect<T> {
    fn lower_bound(&self, val: &T) -> usize;
    fn upper_bound(&self, val: &T) -> usize;
}

impl<T: Ord> Bisect<T> for [T] {
    fn lower_bound(&self, val: &T) -> usize {
        let mut pass = self.len() + 1;
        let mut fail = 0;
        while pass - fail > 1 {
            let mid = (pass + fail) / 2;
            if &self[mid - 1] >= val {
                pass = mid;
            } else {
                fail = mid;
            }
        }
        pass - 1
    }
    fn upper_bound(&self, val: &T) -> usize {
        let mut pass = self.len() + 1;
        let mut fail = 0;
        while pass - fail > 1 {
            let mid = (pass + fail) / 2;
            if &self[mid - 1] > val {
                pass = mid;
            } else {
                fail = mid;
            }
        }
        pass - 1
    }
}

const INF: usize = 1 << 28;
const W: usize = 200_001;

fn coll_head(plus: &[(usize, usize)], minus: &[(usize, usize)]) -> usize {
    let mut ptbl = vec![vec![]; W];
    let mut mtbl = vec![vec![]; W];
    for &(x, y) in plus {
        ptbl[y].push(x);
    }
    for &(x, y) in minus {
        mtbl[y].push(x);
    }
    let mut mi = INF;
    for i in 0..W {
        if ptbl[i].is_empty() || mtbl[i].is_empty() {
            continue;
        }
        ptbl[i].sort();
        mtbl[i].sort();
        for &p in &ptbl[i] {
            let idx = mtbl[i].lower_bound(&p);
            if idx < mtbl[i].len() {
                mi = min(mi, mtbl[i][idx] - p);
            }
        }
    }
    mi * 5
}
// right: (a, b)
// down: (d, W - c) = (e, f)
// collide <=> a + b = c + d && d < b (t = b - d = c - a)
fn coll_side(right: &[(usize, usize)], down: &[(usize, usize)]) -> usize {
    let mut rtbl = vec![vec![]; 2 * W];
    let mut dtbl = vec![vec![]; 2 * W];
    let mut mi = INF;
    for &(x, y) in right {
        rtbl[x + y].push(y);
    }
    for &(x, y) in down {
        let c = W - y;
        let d = x;
        dtbl[c + d].push(d);
    }
    for i in 0..2 * W {
        rtbl[i].sort();
        dtbl[i].sort();
        for &b in &rtbl[i] {
            let idx = dtbl[i].lower_bound(&b);
            if idx > 0 {
                let dist = b - dtbl[i][idx - 1];
                mi = min(mi, dist);
            }
        }
    }
    mi * 10
}
    
fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (let _ = write!(out,$($format)*););
    }
    input! {
        n: usize,
        xyu: [(usize, usize, chars); n],
    }
    let mut dirs = vec![vec![]; 4];
    for &(x, y, ref u) in &xyu {
        let u = u.iter().cloned().collect::<String>();
        let idx = ["R", "U", "L", "D"].iter().position(|&dir| dir == u).unwrap();
        dirs[idx].push((x, y));
    }
    let mut mi = INF;
    mi = min(mi, coll_head(&dirs[0], &dirs[2]));
    for &v in &[1, 3] {
        for j in 0..dirs[v].len() {
            let (x, y) = dirs[v][j];
            dirs[v][j] = (y, x);
        }
    }
    mi = min(mi, coll_head(&dirs[1], &dirs[3]));
    for &v in &[1, 3] {
        for j in 0..dirs[v].len() {
            let (x, y) = dirs[v][j];
            dirs[v][j] = (y, x);
        }
    }
    // TODO
    for v in 1..4 {
        for i in 0..dirs[v].len() {
            for _ in 0..v {
                let (x, y) = dirs[v][i];
                dirs[v][i] = (y, W - x);
            }
        }
    }
    for i in 0..4 {
        mi = min(mi, coll_side(&dirs[i], &dirs[(i + 1) % 4]));
    }
    if mi < INF {
        puts!("{}\n", mi);
    } else {
        puts!("SAFE\n");
    }
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}