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

// The main code is at the very bottom.
#[allow(unused_imports)]
use {
  lib::byte::ByteChar,
  std::cell::{Cell, RefCell},
  std::cmp::{
    self,
    Ordering::{self, *},
    Reverse,
  },
  std::collections::*,
  std::convert::identity,
  std::fmt::{self, Debug, Display, Formatter},
  std::io::prelude::*,
  std::iter::{self, FromIterator},
  std::marker::PhantomData,
  std::mem,
  std::num::Wrapping,
  std::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive},
  std::process,
  std::rc::Rc,
  std::thread,
  std::time::{Duration, Instant},
  std::{char, f32, f64, i128, i16, i32, i64, i8, isize, str, u128, u16, u32, u64, u8, usize},
};

#[allow(unused_imports)]
#[macro_use]
pub mod lib {
  pub mod byte {
    pub use self::byte_char::*;

    mod byte_char {
      use std::error::Error;
      use std::fmt::{self, Debug, Display, Formatter};
      use std::str::FromStr;

      #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
      #[repr(transparent)]
      pub struct ByteChar(pub u8);

      impl Debug for ByteChar {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          write!(f, "b'{}'", self.0 as char)
        }
      }

      impl Display for ByteChar {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          write!(f, "{}", self.0 as char)
        }
      }

      impl FromStr for ByteChar {
        type Err = ParseByteCharError;

        fn from_str(s: &str) -> Result<ByteChar, ParseByteCharError> {
          match s.as_bytes().len() {
            1 => Ok(ByteChar(s.as_bytes()[0])),
            0 => Err(ParseByteCharErrorKind::EmptyStr.into()),
            _ => Err(ParseByteCharErrorKind::TooManyBytes.into()),
          }
        }
      }

      #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
      pub struct ParseByteCharError {
        kind: ParseByteCharErrorKind,
      }

      impl Display for ParseByteCharError {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          f.write_str(match self.kind {
            ParseByteCharErrorKind::EmptyStr => "empty string",
            ParseByteCharErrorKind::TooManyBytes => "too many bytes",
          })
        }
      }

      impl Error for ParseByteCharError {}

      #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
      enum ParseByteCharErrorKind {
        EmptyStr,
        TooManyBytes,
      }

      impl From<ParseByteCharErrorKind> for ParseByteCharError {
        fn from(kind: ParseByteCharErrorKind) -> ParseByteCharError {
          ParseByteCharError { kind }
        }
      }
    }
  }

  pub mod io {
    pub use self::scanner::*;

    mod scanner {
      use std::io::{self, BufRead};
      use std::iter;
      use std::str::FromStr;

      #[derive(Debug)]
      pub struct Scanner<R> {
        reader: R,
        buf: String,
        pos: usize,
      }

      impl<R: BufRead> Scanner<R> {
        pub fn new(reader: R) -> Self {
          Scanner {
            reader,
            buf: String::new(),
            pos: 0,
          }
        }

        pub fn next(&mut self) -> io::Result<&str> {
          let start = loop {
            match self.rest().find(|c| c != ' ') {
              Some(i) => break i,
              None => self.fill_buf()?,
            }
          };
          self.pos += start;
          let len = self.rest().find(' ').unwrap_or(self.rest().len());
          let s = &self.buf[self.pos..][..len]; // self.rest()[..len]
          self.pos += len;
          Ok(s)
        }

        pub fn parse_next<T>(&mut self) -> io::Result<Result<T, T::Err>>
        where
          T: FromStr,
        {
          Ok(self.next()?.parse())
        }

        pub fn parse_next_n<T>(&mut self, n: usize) -> io::Result<Result<Vec<T>, T::Err>>
        where
          T: FromStr,
        {
          iter::repeat_with(|| self.parse_next()).take(n).collect()
        }

        pub fn map_next_bytes<T, F>(&mut self, mut f: F) -> io::Result<Vec<T>>
        where
          F: FnMut(u8) -> T,
        {
          Ok(self.next()?.bytes().map(&mut f).collect())
        }

        pub fn map_next_bytes_n<T, F>(&mut self, n: usize, mut f: F) -> io::Result<Vec<Vec<T>>>
        where
          F: FnMut(u8) -> T,
        {
          iter::repeat_with(|| self.map_next_bytes(&mut f))
            .take(n)
            .collect()
        }

        fn rest(&self) -> &str {
          &self.buf[self.pos..]
        }

        fn fill_buf(&mut self) -> io::Result<()> {
          self.buf.clear();
          self.pos = 0;
          let read = self.reader.read_line(&mut self.buf)?;
          if read == 0 {
            return Err(io::ErrorKind::UnexpectedEof.into());
          }
          if *self.buf.as_bytes().last().unwrap() == b'\n' {
            self.buf.pop();
          }
          Ok(())
        }
      }
    }
  }
}

#[allow(unused_macros)]
macro_rules! eprint {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::eprint!($($arg)*)
    }
  };
}
#[allow(unused_macros)]
macro_rules! eprintln {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::eprintln!($($arg)*)
    }
  };
}
#[allow(unused_macros)]
macro_rules! dbg {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::dbg!($($arg)*)
    } else {
      ($($arg)*)
    }
  };
}

const CUSTOM_STACK_SIZE_MIB: Option<usize> = Some(128);
const INTERACTIVE: bool = false;

fn main() -> std::io::Result<()> {
  match CUSTOM_STACK_SIZE_MIB {
    Some(stack_size_mib) => std::thread::Builder::new()
      .name("run_solver".to_owned())
      .stack_size(stack_size_mib * 1024 * 1024)
      .spawn(run_solver)?
      .join()
      .unwrap(),
    None => run_solver(),
  }
}

fn run_solver() -> std::io::Result<()> {
  let stdin = std::io::stdin();
  let reader = stdin.lock();
  let stdout = std::io::stdout();
  let writer = stdout.lock();
  macro_rules! with_wrapper {
    ($($wrapper:expr)?) => {{
      let mut writer = $($wrapper)?(writer);
      solve(reader, &mut writer)?;
      writer.flush()
    }};
  }
  if cfg!(debug_assertions) || INTERACTIVE {
    with_wrapper!()
  } else {
    with_wrapper!(std::io::BufWriter::new)
  }
}

fn solve<R, W>(reader: R, mut writer: W) -> std::io::Result<()>
where
  R: BufRead,
  W: Write,
{
  let mut _scanner = lib::io::Scanner::new(reader);
  #[allow(unused_macros)]
  macro_rules! scan {
    ($T:ty) => {
      _scanner.parse_next::<$T>()?.unwrap()
    };
    ($($T:ty),+) => {
      ($(scan!($T)),+)
    };
    ($T:ty; $n:expr) => {
      _scanner.parse_next_n::<$T>($n)?.unwrap()
    };
    ($($T:ty),+; $n:expr) => {
      iter::repeat_with(|| -> std::io::Result<_> { Ok(($(scan!($T)),+)) })
        .take($n)
        .collect::<std::io::Result<Vec<_>>>()?
    };
  }
  #[allow(unused_macros)]
  macro_rules! scan_bytes_map {
    ($f:expr) => {
      _scanner.map_next_bytes($f)?
    };
    ($f:expr; $n:expr) => {
      _scanner.map_next_bytes_n($n, $f)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! print {
    ($($arg:tt)*) => {
      write!(writer, $($arg)*)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! println {
    ($($arg:tt)*) => {
      writeln!(writer, $($arg)*)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! answer {
    ($($arg:tt)*) => {{
      println!($($arg)*);
      return Ok(());
    }};
  }
  {
    let n = scan!(usize);
    let xyu = scan!(usize, usize, ByteChar; n);

    let mut ans = usize::MAX;
    {
      let mut sets_u = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_d = vec![BTreeSet::<usize>::new(); 2_000_001];

      for i in 0..n {
        let (x, y, u) = xyu[i];
        match u.0 {
          b'U' => {
            sets_u[x].insert(y);
            if let Some(y_) = sets_d[x].range(y + 1..).next() {
              dbg!("");
              ans = cmp::min(ans, (y_ - y) * 5);
            }
          }
          b'D' => {
            sets_d[x].insert(y);
            if let Some(y_) = sets_u[x].range(..y).next_back() {
              dbg!("");
              ans = cmp::min(ans, (y - y_) * 5);
            }
          }
          _ => {}
        }
      }
    }
    {
      let mut sets_l = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_r = vec![BTreeSet::<usize>::new(); 2_000_001];

      for i in 0..n {
        let (x, y, u) = xyu[i];
        match u.0 {
          b'L' => {
            sets_l[y].insert(x);
            if let Some(x_) = sets_r[y].range(..x).next_back() {
              dbg!("");
              ans = cmp::min(ans, (x - x_) * 5);
            }
          }
          b'R' => {
            sets_r[y].insert(x);
            if let Some(x_) = sets_l[y].range(x + 1..).next() {
              dbg!("");
              ans = cmp::min(ans, (x_ - x) * 5);
            }
          }
          _ => {}
        }
      }
    }
    {
      let mut sets_u = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_d = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_l = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_r = vec![BTreeSet::<usize>::new(); 2_000_001];

      for i in 0..n {
        let (x, y, u) = xyu[i];
        if x < y {
          continue;
        }
        match u.0 {
          b'U' => {
            sets_u[x - y].insert(x);
            if let Some(x_) = sets_l[x - y].range(x + 1..).next() {
              dbg!("");
              ans = cmp::min(ans, (x_ - x) * 10);
            }
          }
          b'D' => {
            sets_d[x - y].insert(x);
            if let Some(x_) = sets_r[x - y].range(..x).next_back() {
              dbg!("");
              ans = cmp::min(ans, (x - x_) * 10);
            }
          }
          b'L' => {
            sets_l[x - y].insert(x);
            if let Some(x_) = sets_u[x - y].range(..x).next_back() {
              dbg!("");
              ans = cmp::min(ans, (x - x_) * 10);
            }
          }
          b'R' => {
            sets_r[x - y].insert(x);
            if let Some(x_) = sets_d[x - y].range(x + 1..).next() {
              dbg!("");
              ans = cmp::min(ans, (x_ - x) * 10);
            }
          }
          _ => unreachable!(),
        }
      }
    }
    {
      let mut sets_u = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_d = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_l = vec![BTreeSet::<usize>::new(); 2_000_001];
      let mut sets_r = vec![BTreeSet::<usize>::new(); 2_000_001];

      for i in 0..n {
        let (x, y, u) = xyu[i];
        if x > y {
          continue;
        }
        match u.0 {
          b'U' => {
            sets_u[y - x].insert(x);
            if let Some(x_) = sets_l[y - x].range(x + 1..).next() {
              dbg!("");
              ans = cmp::min(ans, (x_ - x) * 10);
            }
          }
          b'D' => {
            sets_d[y - x].insert(x);
            if let Some(x_) = sets_r[y - x].range(..x).next_back() {
              dbg!("");
              ans = cmp::min(ans, (x - x_) * 10);
            }
          }
          b'L' => {
            sets_l[y - x].insert(x);
            if let Some(x_) = sets_u[y - x].range(..x).next_back() {
              dbg!(&sets_u[y - x]);
              ans = cmp::min(ans, (x - x_) * 10);
            }
          }
          b'R' => {
            sets_r[y - x].insert(x);
            if let Some(x_) = sets_d[y - x].range(x + 1..).next_back() {
              dbg!("");
              ans = cmp::min(ans, (x_ - x) * 10);
            }
          }
          _ => unreachable!(),
        }
      }
    }
    {
      let mut sets_u = vec![BTreeSet::<usize>::new(); 4_000_001];
      let mut sets_d = vec![BTreeSet::<usize>::new(); 4_000_001];
      let mut sets_l = vec![BTreeSet::<usize>::new(); 4_000_001];
      let mut sets_r = vec![BTreeSet::<usize>::new(); 4_000_001];

      for i in 0..n {
        let (x, y, u) = xyu[i];
        match u.0 {
          b'U' => {
            sets_u[x + y].insert(x);
            if let Some(x_) = sets_r[x + y].range(..x).next_back() {
              ans = cmp::min(ans, (x - x_) * 10);
            }
          }
          b'D' => {
            sets_d[x + y].insert(x);
            if let Some(x_) = sets_l[x + y].range(x + 1..).next() {
              ans = cmp::min(ans, (x_ - x) * 10);
            }
          }
          b'L' => {
            sets_l[x + y].insert(x);
            if let Some(x_) = sets_d[x + y].range(..x).next_back() {
              ans = cmp::min(ans, (x - x_) * 10);
            }
          }
          b'R' => {
            sets_r[x + y].insert(x);
            if let Some(x_) = sets_u[x + y].range(x + 1..).next() {
              ans = cmp::min(ans, (x_ - x) * 10);
            }
          }
          _ => unreachable!(),
        }
      }
    }

    if ans != usize::MAX {
      println!("{}", ans);
    } else {
      println!("SAFE");
    }
  }
  #[allow(unreachable_code)]
  Ok(())
}