A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly $$$n$$$ minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of $$$n$$$ numbers: $$$d_1, d_2, \dots, d_n$$$ ($$$-10^6 \le d_i \le 10^6$$$). The $$$i$$$-th element means that monster's hp (hit points) changes by the value $$$d_i$$$ during the $$$i$$$-th minute of each round. Formally, if before the $$$i$$$-th minute of a round the monster's hp is $$$h$$$, then after the $$$i$$$-th minute it changes to $$$h := h + d_i$$$.The monster's initial hp is $$$H$$$. It means that before the battle the monster has $$$H$$$ hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to $$$0$$$. Print -1 if the battle continues infinitely.

The first line contains two integers $$$H$$$ and $$$n$$$ ($$$1 \le H \le 10^{12}$$$, $$$1 \le n \le 2\cdot10^5$$$). The second line contains the sequence of integers $$$d_1, d_2, \dots, d_n$$$ ($$$-10^6 \le d_i \le 10^6$$$), where $$$d_i$$$ is the value to change monster's hp in the $$$i$$$-th minute of a round.

Print -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer $$$k$$$ such that $$$k$$$ is the first minute after which the monster is dead.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val H = nl()
    val N = ni()
    val D = na(N)
    val S = sumL(D)
    val cum = cumSum(D)

    debugL(S)
    debug(cum)

    def simulateLastTurn(remainH: Long): Long = {
      var t = 0
      var h = remainH
      while(h > 0) {
        h += D(t)
        t += 1
      }
      t
    }

    // one turn kill
    if (H + cum.min <= 0) {
      val t = simulateLastTurn(H)
      out.println(t)
    } else if (S >= 0) out.println(-1) // 何ターンかかってもたおせない
    else {
      val turns = (H + cum.min - 1) / -S + 1
      debugL(turns)
      val remain = H + turns * S
      debug(s"turns:$turns remain:$remain")
      val ans = turns * N + simulateLastTurn(remain)
      out.println(ans)
    }
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.io.StdIn
import scala.util.control.Breaks._
import java.util.Scanner

object Hello extends App {
  val line = new Scanner(StdIn.readLine())
  val health: BigInt = line.nextBigInteger()
  val mins = line.nextInt()
  val d = StdIn.readLine().split(' ').map(_.toInt)
  var damage: BigInt = BigInt(0)
  var maxDamage: BigInt = BigInt(0)
  for (i <- 0 until mins) {
     damage += d(i)
     if (damage < maxDamage) {
       maxDamage = damage
     }
  }
  if (damage >= 0 && maxDamage * -1 < health) {
    println("-1")
    System.exit(0)
  }
  val fullRounds: BigInt = (health + maxDamage) / (if(damage == 0) BigInt(1) else damage)
  var finalFullRounds: BigInt = if (fullRounds >= 0) fullRounds else fullRounds * -1
  if ((health + maxDamage) % (if(damage == 0) BigInt(1) else damage) != 0) {
    finalFullRounds += 1
  }
  if (maxDamage * -1 >= health) {
    finalFullRounds = 0
  }
  var secondDamage: BigInt = 0
  breakable {
    for (i <- 0 until mins) {
      secondDamage += d(i)
      if (health + damage * finalFullRounds + secondDamage <= 0) {
        println(finalFullRounds * mins + i + 1)
        break()
      }
    }
  }
}

import scala.io.StdIn
import scala.util.control.Breaks._
import java.util.Scanner

object Hello extends App {
  val line = new Scanner(StdIn.readLine())
  val health: BigInt = line.nextBigInteger()
  val mins = line.nextInt()
  val d = StdIn.readLine().split(' ').map(_.toInt)
  var damage: BigInt = BigInt(0)
  var maxDamage: BigInt = BigInt(0)
  for (i <- 0 until mins) {
     damage += d(i)
     if (damage < maxDamage) {
       maxDamage = damage
     }
  }
  if (damage >= 0 && maxDamage * -1 < health) {
    println("-1")
    System.exit(0)
  }
  val fullRounds: BigInt = (health + maxDamage) / (if(damage == 0) BigInt(1) else damage)
  var finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1
  if ((health + maxDamage) % (if(damage == 0) BigInt(1) else damage) != 0) {
    finalFullRounds += 1
  }
  if (maxDamage * -1 >= health) {
    finalFullRounds = 0
  }
  var secondDamage = 0
  breakable {
    for (i <- 0 until mins) {
      secondDamage += d(i)
      if (health + damage * finalFullRounds + secondDamage <= 0) {
        println(finalFullRounds * mins + i + 1)
        break()
      }
    }
  }
}

import scala.io.StdIn
import scala.util.control.Breaks._
import java.util.Scanner

import scala.math.BigDecimal.RoundingMode

object Hello extends App {
  val line = new Scanner(StdIn.readLine())
  val health: BigDecimal = line.nextBigDecimal()
  val mins = line.nextInt()
  val d = StdIn.readLine().split(' ').map(_.toInt)
  var damage: BigDecimal = BigDecimal(0)
  var maxDamage: BigDecimal = BigDecimal(0)
  for (i <- 0 until mins) {
     damage += d(i)
     if (damage < maxDamage) {
       maxDamage = damage
     }
  }
  if (damage >= 0 && maxDamage < health) {
    println("-1")
  }
  (health + maxDamage).setScale(0, RoundingMode.CEILING)
  val fullRounds: BigDecimal = ((health + maxDamage) / (if(damage == 0) BigDecimal(1) else damage)).setScale(0, RoundingMode.UP)
  val finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1

  var secondDamage = 0
  breakable {
    for (i <- 0 until mins) {
      secondDamage += d(i)
      if (health + damage * finalFullRounds + secondDamage <= 0) {
        println((finalFullRounds * mins + i + 1).toBigInt())
        break()
      }
    }
  }
}

import scala.io.StdIn
import scala.util.control.Breaks._
import java.util.Scanner

import scala.math.BigDecimal.RoundingMode

object Hello extends App {
  val line = new Scanner(StdIn.readLine())
  val health: BigDecimal = line.nextBigDecimal()
  val mins = line.nextInt()
  val d = StdIn.readLine().split(' ').map(_.toInt)
  var damage: BigDecimal = BigDecimal(0)
  var maxDamage: BigDecimal = BigDecimal(0)
  for (i <- 0 until mins) {
     damage += d(i)
     if (damage < maxDamage) {
       maxDamage = damage
     }
  }
  if (damage >= 0 && maxDamage * -1 < health) {
    println("-1")
    System.exit(0)
  }
  val fullRounds: BigDecimal = ((health + maxDamage) / (if(damage == 0) BigDecimal(1) else damage)).setScale(0, RoundingMode.UP)
  var finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1

  if (maxDamage * -1 >= health) {
    finalFullRounds = 0
  }
  var secondDamage = 0
  breakable {
    for (i <- 0 until mins) {
      secondDamage += d(i)
      if (health + damage * finalFullRounds + secondDamage <= 0) {
        println((finalFullRounds * mins + i + 1).toBigInt())
        break()
      }
    }
  }
}

import scala.io.StdIn
import scala.util.control.Breaks._
import java.util.Scanner

object Hello extends App {
  val line = new Scanner(StdIn.readLine())
  val health: BigInt = line.nextBigInteger()
  val mins = line.nextInt()
  val d = StdIn.readLine().split(' ').map(_.toInt)
  var damage: BigInt = BigInt(0)
  var maxDamage: BigInt = BigInt(0)
  for (i <- 0 until mins) {
     damage += d(i)
     if (damage < maxDamage) {
       maxDamage = damage
     }
  }
  if (damage >= 0 && maxDamage * -1 < health) {
    println("-1")
    System.exit(0)
  }
  val fullRounds: BigInt = (health + maxDamage) / (if(damage == 0) BigInt(1) else damage)
  var finalFullRounds = (if (fullRounds >= 0) fullRounds else fullRounds * -1) + 1

  if (maxDamage * -1 >= health) {
    finalFullRounds = 0
  }
  var secondDamage = 0
  breakable {
    for (i <- 0 until mins) {
      secondDamage += d(i)
      if (health + damage * finalFullRounds + secondDamage <= 0) {
        println(finalFullRounds * mins + i + 1)
        break()
      }
    }
  }
}

import scala.io.StdIn
import scala.util.control.Breaks._
import java.util.Scanner

import scala.math.BigDecimal.RoundingMode

object Hello extends App {
  val line = new Scanner(StdIn.readLine())
  val health: BigDecimal = line.nextBigDecimal()
  val mins = line.nextInt()
  val d = StdIn.readLine().split(' ').map(_.toInt)
  var damage: BigDecimal = BigDecimal(0)
  var maxDamage: BigDecimal = BigDecimal(0)
  for (i <- 0 until mins) {
     damage += d(i)
     if (damage < maxDamage) {
       maxDamage = damage
     }
  }
  if (damage >= 0 && maxDamage * -1 < health) {
    println("-1")
    System.exit(0)
  }
  (health + maxDamage).setScale(0, RoundingMode.CEILING)
  val fullRounds: BigDecimal = ((health + maxDamage) / (if(damage == 0) BigDecimal(1) else damage)).setScale(0, RoundingMode.UP)
  var finalFullRounds = if (fullRounds >= 0) fullRounds else fullRounds * -1

  if (maxDamage * -1 >= health) {
    finalFullRounds = 0
  }
  var secondDamage = 0
  breakable {
    for (i <- 0 until mins) {
      secondDamage += d(i)
      if (health + damage * finalFullRounds + secondDamage <= 0) {
        println((finalFullRounds * mins + i + 1).toBigInt())
        break()
      }
    }
  }
}


Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.

The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).

In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.

import scala.collection._

object B extends App {

  def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(n, m, p) = readInts(3)
  val mpL = p.longValue * (m - 1)

  val as0 = readInts(n)
  val bs0 = readInts(m)

  val amap = bs0.zipWithIndex.reverse.toMap.withDefaultValue(m)
  val as = as0.map(amap)
  val bs = bs0.map(amap)

  val bc = Array.fill(m + 1)(0)
  for (b <- bs) bc(b) += 1

  val res = mutable.ArrayBuffer[Int]()

  var offset = 0

  while (offset < p && offset + mpL < n) {

    val ac = bc.clone

    var i = 0
    while (i < m) {
      val a = as(offset + i * p)
      ac(a) -= 1
      i += 1
    }

    var q = offset
    var zeroC = ac.count(_ == 0)
    if (zeroC > m) res += (q + 1)

    while (q + m * p < n) {
      val a1 = as(q)
      ac(a1) += 1
      if (ac(a1) == 0) zeroC += 1 else if (ac(a1) == 1) zeroC -=1
      val a2 = as(q + m * p)
      ac(a2) -= 1
      if (ac(a2) == 0) zeroC += 1 else if (ac(a2) == -1) zeroC -=1
      q += p
      if (zeroC > m) res += (q + 1)
    }

    offset += 1
  }

  println(res.size)
  println(res.sorted.mkString(" "))
}

import scala.collection._

object B extends App {

  def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val Array(n, m, p) = readInts(3)
  val as0 = /*Array.fill(n)(scala.util.Random.nextInt) */readInts(n)
  val bs0 = /*Array.fill(n)(scala.util.Random.nextInt) */readInts(m)

  val amap = bs0.zipWithIndex.reverse.toMap.withDefaultValue(m)
  val as = as0.map(amap)
  val bs = bs0.map(amap)

  val bc = Array.fill(m + 1)(0)
  for (b <- bs) bc(b) += 1

  val res = mutable.ArrayBuffer[Int]()

  var offset = 0
  while (offset < p && offset + (m - 1) * p < n) {
    val ac = Array.fill(m + 1)(0)
    var i = 0
    while (i < m) {
      ac(as(offset + i * p)) += 1
      i += 1
    }
    var q = offset
    var lastBad = 0
    while (lastBad <= m && ac(lastBad) == bc(lastBad)) lastBad += 1
    if (lastBad > m) res += (q + 1)
    while (q + m * p < n) {
      ac(as(q)) -= 1
      val qq = q + m * p
      ac(as(qq)) += 1
      if ((as(q) == lastBad && ac(as(q)) == bc(as(q))) ||
          as(qq) == lastBad && ac(as(qq)) == bc(as(qq))) {
    	  while (lastBad <= m && ac(lastBad) == bc(lastBad)) lastBad += 1
      } else lastBad = as(q) min as(qq) min lastBad
      q += p
      if (lastBad > m) res += (q + 1)
    }
    offset += 1
  }

  println(res.size)
  println(res.sorted.mkString(" "))
}


Let's call the string beautiful if it does not contain a substring of length at least $$$2$$$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You are given a string $$$s$$$ of length $$$n$$$, each character of the string is one of the first $$$3$$$ letters of the Latin alphabet (in lowercase).You have to answer $$$m$$$ queries — calculate the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$ and the number of queries. The second line contains the string $$$s$$$, it consists of $$$n$$$ characters, each character one of the first $$$3$$$ Latin letters. The following $$$m$$$ lines contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — parameters of the $$$i$$$-th query.

For each query, print a single integer — the cost of the substring of the string $$$s$$$ from $$$l_i$$$-th to $$$r_i$$$-th position, inclusive.

NoteConsider the queries of the example test.  in the first query, the substring is baa, which can be changed to bac in one operation;  in the second query, the substring is baacb, which can be changed to cbacb in two operations;  in the third query, the substring is cb, which can be left unchanged;  in the fourth query, the substring is aa, which can be changed to ba in one operation.

import java.io._
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new BufferedReader(new java.io.InputStreamReader(System.in))
    val writer =  new PrintWriter(System.out)
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        //var t = readInt()
        //while (t > 0) {
            val Array(n,m) = readArrayInt()
            val s = readString()
            val q = new Array[(Int, Int)](m)

            for (i <- 0 until m) {
                val Array(l, r) = readArrayInt()
                q(i) = (l,r)
            }

            val c = Array("abc","acb","bca","bac","cab","cba")
            val f = Array.ofDim[Int](6,n)

            for (i <- 0 until 6) {
                if (c(i)(0) != s(0))
                    f(i)(0) = 1

                for (j <- 1 until n) {
                    if (c(i)(j % 3) != s(j))
                        f(i)(j) = f(i)(j-1) + 1
                    else
                        f(i)(j) = f(i)(j-1)

                }
            }

            for (i <- 0 until m) {
                val (l,r) = q(i)
                var max = n
                for (i <- 0 until 6) {
                    if (l - 2 >= 0) {
                        max = Math.min(max, f(i)(r - 1) - f(i)(l - 2))
                    } else
                        max = Math.min(max, f(i)(r - 1))
                }
                writer.println(max)
            }

            //t -= 1
       // }

    }

    def main(args: Array[String]) {
        //multiTest(solve)
        solve()
        writer.flush()
    }
}

import java.io._

object Solution {
  // let's talk about beatiful strings
  case class Solver(s: String) {
    //    def notAPalindrome(s: String, ll: Int, rr: Int): Boolean = {
    //      var l = ll
    //      var r = rr
    //      while (l < r) {
    //        if (s.charAt(l) != s.charAt(r)) return true
    //        l += 1
    //        r -= 1
    //      }
    //      false
    //    }
    //
    //    def isBeautiful(s: String): Boolean =
    //      (0 until s.length).forall { left =>
    //        ((left + 1) until s.length).forall { right =>
    //          notAPalindrome(s, left, right)
    //        }
    //      }
    //
    //    def enumBeautiful(len: Int): LazyList[String] =
    //      if (len == 0)
    //        LazyList.from(Seq(""))
    //      else
    //        enumBeautiful(len - 1).flatMap(l => Seq(l + "a", l + "b", l + "c")).filter(isBeautiful)

    val totals: Array[Array[Int]] = Seq(0, 1, 2).flatMap { offset =>
      Seq('a', 'b', 'c').map { ch =>
        val total: Array[Int] = s.zipWithIndex.map { case (ch2, idx) =>
          if ((ch2 == ch) && (idx % 3 == offset)) 1 else 0
        }.scan(0)(_ + _).tail.toArray
        ((offset * 3 + (ch - 'a')), total)
      }
    }.sortBy(_._1).map(_._2).toArray

    // r-l % 3 == 0
    def charCount(l: Int, r: Int, char: Char): Int = {
      val total = totals((l % 3) * 3 + (char - 'a'))
      if (l == 0) total(r) else total(r) - total(l - 1)
    }

    // inclusive
    def notCharCount(l: Int, _r: Int, char: Char): Int = {
      if (l > _r) return 0

      val mod = (_r - l) % 3
      val r = _r - mod
      val total = (r - l) / 3 + 1
      total - charCount(l, r, char)
    }

    def cost(l: Int, r: Int, src: String): Int = {
      notCharCount(l, r, src.charAt(0)) +
        notCharCount(l + 1, r, src.charAt(1)) +
        notCharCount(l + 2, r, src.charAt(2))
    }

    def query(l: Int, r: Int): Int = Math.min(
      Math.min(
        Math.min(
          cost(l, r, "abc"),
          cost(l, r, "acb")
        ),
        Math.min(
          cost(l, r, "bac"),
          cost(l, r, "bca"),
        )
      ),
      Math.min(
        cost(l, r, "cab"),
        cost(l, r, "cba")
      )
    )
  }

  def run(input: BufferedReader, output: PrintWriter): Unit = {
    // len 1: a, b, c
    // len 2: ab, ac, ba, bc, ca, cb
    // len 3: abc, acb, bac, bca, cab, cba
    // len 4: abca, acba, bacb, bcab, cabc, cbac
    // so it's always one of "abc", "acb", "bac", "bca", "cab", "cba"
//    Solver("").enumBeautiful(4).foreach(println)
//    println("done")
//    val solver2 =Solver("a".repeat(200000))
//    println("done")

    val nm = input.readLine()
    val n = nm.split(" ")(0).toInt
    val m = nm.split(" ")(1).toInt
    val s = input.readLine()

    val solver = Solver(s.substring(0, n))

    (1 to m).foreach { _ =>
      val lr = input.readLine()
      output.println(solver.query(lr.split(" ")(0).toInt - 1, lr.split(" ")(1).toInt - 1))
    }
    output.flush()
  }

  def main(args: Array[String]): Unit = {
    run(new BufferedReader(new InputStreamReader(System.in)), new PrintWriter(System.out))
  }
}


A tree is an undirected connected graph without cycles.Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).    For this rooted tree the array p is [2, 3, 3, 2]. Given a sequence p1, p2, ..., pn, one is able to restore a tree:  There must be exactly one index r that pr = r. A vertex r is a root of the tree.  For all other n - 1 vertices i, there is an edge between vertex i and vertex pi. A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.

The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).

In the first line print the minimum number of elements to change, in order to get a valid sequence. In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.

NoteIn the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.  In the second sample, the given sequence is already valid.

/**
  * Created by allen on 16-7-22.
  */

import scala.io._

/**
  * Cheat Sheet:
  * Input: scala.io.StdIn
  * Output: println
  */

object main {
  val MAXN = 200010
  var n = 0
  var p = new Array[Int](MAXN)

  var vis = new Array[Boolean](MAXN)
  var tag = new Array[Int](MAXN)
  var rep = new Array[Int](MAXN)
  var tag_now = 0

  // Variables

  def readNInts(n: Int): Seq[Int] = StdIn.readLine().split(' ').map(x => x.toInt).toSeq

  def dfs(root: Int, tag_now: Int): Boolean = {
    vis(root) = true

    val parent = p(root - 1)
    if(vis(parent)) {
      if(tag(parent) == -1) {
        tag(root) = tag_now
        rep(tag_now) = root
        true
      } else {
        tag(root) = tag(parent)
        false
      }
    } else {
      val ret = dfs(parent, tag_now)
      tag(root) = tag(parent)
      ret
    }
  }

  def run() = {
    try {
      n = StdIn.readInt()
      readNInts(n).copyToArray(p, 0, n)

      (1 to MAXN).map(x => -1).copyToArray(tag)
      (1 to MAXN).map(x => false).copyToArray(vis)
      for (i <- 1 to n) if (!vis(i)) if (dfs(i, tag_now)) tag_now = tag_now + 1

      var new_root: Int = -1
      val rt = (0 until tag_now).filter(x => p(rep(x) - 1) == rep(x))

      if(rt.nonEmpty)
        new_root = rep(rt.head)

      if(new_root == -1) {
        p(rep(tag_now - 1) - 1) = rep(tag_now - 1)
        rep.toList.take(tag_now - 1).foreach(x => p(x - 1) = rep(tag_now - 1))
        println(tag_now)
      }
      else {
        println(tag_now - 1)
        rep.toList.take(tag_now).foreach(x => if(x != new_root) p(x - 1) = new_root)
      }
      println(p.take(n).mkString(" "))
    } catch {
      case e: Exception => println(e.getMessage())
    }
  }

  def main(args: Array[String])= {
    run()
  }
}

/**
  * Created by allen on 16-7-22.
  */

import scala.io._

/**
  * Cheat Sheet:
  * Input: scala.io.StdIn
  * Output: println
  */

object main {
  val MAXN = 200010
  var n = 0
  var p = new Array[Int](MAXN)

  var vis = new Array[Boolean](MAXN)
  var tag = new Array[Int](MAXN)
  var rep = new Array[Int](MAXN)
  var tag_now = 0

  // Variables

  def readNInts(n: Int): Seq[Int] = StdIn.readLine().split(' ').map(x => x.toInt).toSeq

  def dfs(root: Int, tag_now: Int): Boolean = {
    vis(root) = true

    val parent = p(root - 1)
    if(vis(parent)) {
      if(tag(parent) == -1) {
        tag(root) = tag_now
        rep(tag_now) = root
        true
      } else {
        tag(root) = tag(parent)
        false
      }
    } else {
      val ret = dfs(parent, tag_now)
      tag(root) = tag(parent)
      ret
    }
  }

  def run() = {
    try {
      n = StdIn.readInt()
      readNInts(n).copyToArray(p, 0, n)

      (1 to MAXN).map(x => -1).copyToArray(tag)
      (1 to MAXN).map(x => false).copyToArray(vis)
      for (i <- 1 to n) if (!vis(i)) if (dfs(i, tag_now)) tag_now = tag_now + 1
      if(p(rep(tag_now - 1) - 1) != rep(tag_now - 1)) {
        p(rep(tag_now - 1) - 1) = rep(tag_now - 1)
        println(tag_now)
      } else {
        println(tag_now - 1)
      }
      rep.toList.take(tag_now - 1).map(x => p(x - 1) = rep(tag_now - 1))
      println(p.take(n).mkString(" "))
    } catch {
      case e: Exception => println(e.getMessage())
    }
  }

  def main(args: Array[String])= {
    run()
  }
}

/**
  * Created by allen on 16-7-22.
  */

import scala.io._

/**
  * Cheat Sheet:
  * Input: scala.io.StdIn
  * Output: println
  */

object main {
  val MAXN = 200010
  var n = 0
  var p = new Array[Int](MAXN)

  var vis = new Array[Boolean](MAXN)
  var tag = new Array[Int](MAXN)
  var rep = new Array[Int](MAXN)
  var tag_now = 0

  // Variables

  def readNInts(n: Int): Seq[Int] = StdIn.readLine().split(' ').map(x => x.toInt).toSeq

  def dfs(root: Int, tag_now: Int): Boolean = {
    vis(root) = true

    val parent = p(root - 1)
    if(vis(parent)) {
      if(tag(parent) == -1) {
        tag(root) = tag_now
        rep(tag_now) = root
        true
      } else {
        tag(root) = tag(parent)
        false
      }
    } else {
      val ret = dfs(parent, tag_now)
      tag(root) = tag(parent)
      ret
    }
  }

  def run() = {
    try {
      n = StdIn.readInt()
      readNInts(n).copyToArray(p, 0, n)

      (1 to MAXN).map(x => -1).copyToArray(tag)
      (1 to MAXN).map(x => false).copyToArray(vis)
      for (i <- 1 to n) if (!vis(i)) if (dfs(i, tag_now)) tag_now = tag_now + 1

      println(tag_now - 1)
      rep.toList.take(tag_now - 1).map(x => p(x - 1) = rep(tag_now - 1))
      println(p.take(n).mkString(" "))
    } catch {
      case e: Exception => println(e.getMessage())
    }
  }

  def main(args: Array[String])= {
    run()
  }
}


Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.

The first line contains a single integer n — the number of items (1 ≤ n ≤ 105). The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items.

Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.

NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one.

import java.io._
import java.util._

import scala.collection.mutable

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val set = new Array[Int](n)
    val values = new mutable.TreeSet[Int]()
    for (i <- 0 until n) {
      a(i) = nextInt
      values.add(i + 1)
      set(i) = a(i)
    }
    for (i <- 0 until n) {
      if (set(i) < n && values.contains(set(i))) {
        values -= set(i)
      }
    }
    var ind = 0
    var min = 1
    val s = new mutable.HashSet[Int]()
    while (ind < n) {
      val x = a(ind)
      if (s.contains(x) || x > n) {
        min = values.keySet.firstKey
        set(ind) = min
        s.add(min)
        values -= min
      } else {
        s.add(x)
        set(ind) = x
        values -= x
      }
      ind += 1
    }
    if (!values.isEmpty) {
      for (i <- 0 until n) {
        if (set(i) > n) {
          set(i) = values.keySet.firstKey
          values -= set(i)
        }
      }
    }
    for (i <- 0 until n) {
      out.print(set(i) + " ")
    }
    return 0
  }
}

import scala.io.StdIn._

object B extends App {
  readInt()
  val numbers = readLine().split(" ").map(_.toInt)

  val pool = Array.fill[Boolean](numbers.length + 1)(false)

  val answer = numbers.map { x =>
    if (x <= numbers.length && !pool(x)) {
      pool(x) = true
      x
    } else {
      -1
    }
  }

  var current = 1
  val answer2 = answer.map { x =>
    if (x > -1) x
    else {
      while (pool(current)) current += 1
      pool(current) = true
      current += 1
      current - 1
    }

  }

  println(answer2.mkString(" "))

}

import java.util.Scanner

object PB extends App {
    var in = new Scanner(System.in)
    val n = in.nextInt()
    val a = (1 to n).map(_ => in.nextInt())
    val vis = Array.fill[Boolean](n+1)(false)
    val ans = Array.fill[Int](n)(0)
    for(i <- 0 until n if a(i) <= n && !vis(a(i))){
        vis(a(i)) = true
        ans(i) = a(i)
    }
    val emp = (0 until n).filter(ans(_) == 0)
    val vs = (1 to n).filter(!vis(_))
    for(i <- 0 until emp.length)
        ans(emp(i)) = vs(i)
    println(ans.mkString(" "))
}

import java.io._
import java.util._

import scala.collection.mutable

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = return Integer.parseInt(next)

  def nextLong: Long = return java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    val set = new Array[Int](n)
    val values = new mutable.TreeSet[Int]()
    for (i <- 0 until n) {
      a(i) = nextInt
      values.add(i + 1)
      set(i) = a(i)
    }
    var ind = 0
    var min = 1
    val s = new mutable.HashSet[Int]()
    while (ind < n) {
      val x = a(ind)
      if (s.contains(x)) {
        min = values.keySet.firstKey
        set(ind) = min
        values -= min
      } else {
        s.add(x)
        set(ind) = x
        values -= x
      }
      ind += 1
    }
    if (!values.isEmpty) {
      for (i <- 0 until n) {
        if (set(i) > n) {
          set(i) = values.keySet.firstKey
          values -= set(i)
        }
      }
    }
    for (i <- 0 until n) {
      out.print(set(i) + " ")
    }
    return 0
  }
}

import scala.io.StdIn._

object B extends App {
  readInt()
  val numbers = readLine().split(" ").map(_.toInt)

  val pool = Array.fill[Boolean](numbers.length + 1)(false)

  var current = 1
  val answer = numbers.map { x =>
    if (x <= numbers.length && !pool(x)) {
      pool(x) = true
      x
    } else {
      while (pool(current)) current += 1
      pool(current) = true
      current += 1
      current - 1
    }
  }

  println(answer.mkString(" "))

}


Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move. Help Anton and write the program that for the given position determines whether the white king is in check.Remainder, on how do chess pieces move:   Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells.  Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells.  Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap".

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of black pieces. The second line contains two integers x0 and y0 ( - 109 ≤ x0, y0 ≤ 109) — coordinates of the white king. Then follow n lines, each of them contains a character and two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — type of the i-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position.

The only line of the output should contains "YES" (without quotes) if the white king is in check and "NO" (without quotes) otherwise.

NotePicture for the first sample:    White king is in check, because the black bishop can reach the cell with the white king in one move. The answer is "YES".Picture for the second sample:    Here bishop can't reach the cell with the white king, because his path is blocked by the rook, and the bishop cant "leap" over it. Rook can't reach the white king, because it can't move diagonally. Hence, the king is not in check and the answer is "NO".

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val Array(x0, y0) = in.next().split(' ').map(_.toLong)

  def mayBlock(x: Int, y: Int) = {
    x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))
  }

  def scoreBlock(x: Int, y: Int) = {
    if (x == x0 && y > y0) 0 //"UP"
    else if (x == x0 && y < y0) 1 // "DOWN"
    else if (y == y0 && x > x0) 2 // "RIGHT"
    else if (y == y0 && x < x0) 3 // "LEFT"
    else if (y > y0 && x > x0) 4 // "UP RIGHT"
    else if (y > y0 && x < x0) 5 // "UP LEFT"
    else if (y < y0 && x > x0) 6 // "DOWN RIGHT"
    else if (y < y0 && x < x0) 7 // "DOWN LEFT"
    else throw new Exception(s"don't know $x $y")
  }

  def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)

  val line = in.take(n).map(_.split(' ')).map {
    case Array("B", x, y) => (0, x.toInt, y.toInt)
    case Array("R", x, y) => (1, x.toInt, y.toInt)
    case Array("Q", x, y) => (2, x.toInt, y.toInt)
  }.filter{
    case (d, x, y) => mayBlock(x, y)
  }.toList

  val res = line.sortBy {
    case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))
  }.foldLeft(false, Set.empty[Int]) {
    case ((true, set), el) => (true, set)
    case ((false, set), (l, x, y)) =>
      val score = scoreBlock(x, y)
      if (set.contains(score))
        (false, set)
      else if (attack(l, score))
        (true, set)
      else
        (false, set + score)
  }._1
  if (res)
    println("YES")
  else
    println("NO")
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _734D extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val kx, ky = read[Long]

    var north, northeast, east, southeast, south, southwest, west, northwest = Option.empty[Piece]

    repeat(n) {
      val piece = Piece(read[Char], read[Long], read[Long])
      (piece.x, piece.y) match {
        case (`kx`,    y) if y < ky && (north.isEmpty || y > north.get.y) => north = Some(piece)
        case (`kx`,    y) if ky < y && (south.isEmpty || y < south.get.y) => south = Some(piece)
        case (   x, `ky`) if x < kx && ( west.isEmpty || x >  west.get.x) =>  west = Some(piece)
        case (   x, `ky`) if kx < x && ( east.isEmpty || x <  east.get.x) =>  east = Some(piece)
        case (   x,    y) if (kx - x).abs == (ky - y).abs =>
          ((kx - x).signum, (ky - y).signum) match {
            case (-1, -1) if northwest.isEmpty || (kx - x).abs < (kx - northwest.get.x).abs => northwest = Some(piece)
            case (-1,  1) if southwest.isEmpty || (kx - x).abs < (kx - southwest.get.x).abs => southwest = Some(piece)
            case ( 1, -1) if northeast.isEmpty || (kx - x).abs < (kx - northeast.get.x).abs => northeast = Some(piece)
            case ( 1,  1) if southeast.isEmpty || (kx - x).abs < (kx - southeast.get.x).abs => southeast = Some(piece)
            case  _ =>
          }
        case _ =>
      }
      debug(piece, north, northeast, east, southeast, south, southwest, west, northwest)
    }

    val isCheck =       Seq(north, east, south, west).flatten.exists(p => p.kind == 'Q' || p.kind == 'R') ||
      Seq(northeast, southeast, southwest, northwest).flatten.exists(p => p.kind == 'Q' || p.kind == 'B')

    write(isCheck.toEnglish)
  }

  case class Piece(kind: Char, x: Long, y: Long)
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import scala.io.StdIn._

object Solution {

  trait ChessPiece {
    val x: Int
    val y: Int

    def checkMate(x1: Int, y1: Int): Boolean
  }

  case class Rook(x: Int, y: Int) extends ChessPiece {
    def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y
  }

  case class Bishop(x: Int, y: Int) extends ChessPiece {
    def checkMate(x1: Int, y1: Int): Boolean = Math.abs(x1 - x) == Math.abs(y1 - y)
  }

  case class Queen(x: Int, y: Int) extends ChessPiece {
    def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y || Math.abs(x1 - x) == Math.abs(y1 - y)
  }

  def main(args: Array[String]): Unit = {
    val n = readInt
    val Array(x, y) = readLine.split(" ").map(_.toInt)
    val list = List.fill(n)(readLine.split(" ").toList).map {
      case "R" :: x1 :: y1 :: Nil => Rook(x1.toInt, y1.toInt)
      case "Q" :: x1 :: y1 :: Nil => Queen(x1.toInt, y1.toInt)
      case "B" :: x1 :: y1 :: Nil => Bishop(x1.toInt, y1.toInt)
    }
    if (List(
      list.filter(p => p.x == x && p.y > y).sortBy(_.y),  // Up
      list.filter(p => p.x == x && p.y < y).sortBy(-_.y), // Down
      list.filter(p => p.y == y && p.x > x).sortBy(_.x),  // Right
      list.filter(p => p.y == y && p.x < x).sortBy(-_.x), // Left
      list.filter(p => p.x - x == p.y - y && p.x > x).sortBy(_.x),  // Up-Right
      list.filter(p => p.x - x == p.y - y && p.x < x).sortBy(-_.x), // Down-Left
      list.filter(p => p.x - x == y - p.y && p.x > x).sortBy(_.x),  // Down-Right
      list.filter(p => p.x - x == y - p.y && p.x < x).sortBy(-_.x)  // Up-Left
    ).filter(_.nonEmpty).exists(_.head.checkMate(x, y))) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

import scala.io.StdIn._

object Solution {

  trait ChessPiece {
    val x: Int
    val y: Int
    def checkMate(x1: Int, y1: Int): Boolean
  }

  case class Rook (x: Int, y: Int) extends ChessPiece {
    def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y
  }

  case class Bishop(x: Int, y: Int) extends ChessPiece {
    def checkMate(x1: Int, y1: Int): Boolean = Math.abs(x1 - x) == Math.abs(y1 - y)
  }

  case class Queen (x: Int, y: Int) extends ChessPiece {
    def checkMate(x1: Int, y1: Int): Boolean = x1 == x || y1 == y || Math.abs(x1 - x) == Math.abs(y1 - y)
  }

  def main(args: Array[String]): Unit = {
    val n = readInt
    val Array(x, y) = readLine.split(" ").map(_.toInt)
    val list = List.fill(n)(readLine.split(" ").toList).map {
      case "R" :: x1 :: y1 => Rook(x1.toInt, y1.head.toInt)
      case "B" :: x1 :: y1 => Bishop(x1.toInt, y1.head.toInt)
      case "Q" :: x1 :: y1 => Queen(x1.toInt, y1.head.toInt)
    }
    if( List(
      list.filter(p => p.x == x && p.y > y).sortBy(_.y),            // Up
      list.filter(p => p.x == x && p.y < y).sortBy(-_.y),           // Down
      list.filter(p => p.y == y && p.x > x).sortBy(_.x),            // Right
      list.filter(p => p.y == y && p.x < x).sortBy(-_.x),           // Left
      list.filter(p => p.x - x == p.y - y && p.x > x).sortBy(_.x),  // Up-Right
      list.filter(p => p.x - x == p.y - y && p.x < x).sortBy(-_.x), // Down-Left
      list.filter(p => p.x - x == y - p.y && p.x > x).sortBy(_.x),  // Down-Right
      list.filter(p => p.x - x == y - p.y && p.x < x).sortBy(-_.x)  // Up-Left
    ).filter(_.nonEmpty).map(_.head).exists(_.checkMate(x, y))) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val Array(x0, y0) = in.next().split(' ').map(_.toInt)

  def mayBlock(x: Int, y: Int) = {
    x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))
  }

  def scoreBlock(x: Int, y: Int) = {
    if (x == x0 && y > y0) 0 //"UP"
    else if (x == x0 && y < y0) 1 // "DOWN"
    else if (y == y0 && x > x0) 2 // "RIGHT"
    else if (y == y0 && x < x0) 3 // "LEFT"
    else if (y > y0 && x > x0) 4 // "UP RIGHT"
    else if (y > y0 && x < x0) 5 // "UP LEFT"
    else if (y < y0 && x > x0) 6 // "DOWN RIGHT"
    else if (y < y0 && x < x0) 7 // "DOWN LEFT"
    else throw new Exception(s"don't know $x $y")
  }

  def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)

  val line = in.take(2).map(_.split(' ')).map {
    case Array("B", x, y) => (0, x.toInt, y.toInt)
    case Array("R", x, y) => (1, x.toInt, y.toInt)
    case Array("Q", x, y) => (2, x.toInt, y.toInt)
  }.filter{
    case (d, x, y) => mayBlock(x, y)
  }.toList

  val res = line.sortBy {
    case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))
  }.foldLeft(false, Set.empty[Int]) {
    case ((true, set), el) => (true, set)
    case ((false, set), (l, x, y)) =>
      val score = scoreBlock(x, y)
      if (set.contains(score))
        (false, set)
      else if (attack(l, score))
        (true, set)
      else
        (false, set + score)
  }._1
  if (res)
    println("YES")
  else
    println("NO")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val Array(x0, y0) = in.next().split(' ').map(_.toInt)

  def mayBlock(x: Int, y: Int) = {
    x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))
  }

  def scoreBlock(x: Int, y: Int) = {
    if (x == x0 && y > y0) 0 //"UP"
    else if (x == x0 && y < y0) 1 // "DOWN"
    else if (y == y0 && x > x0) 2 // "RIGHT"
    else if (y == y0 && x < x0) 3 // "LEFT"
    else if (y > y0 && x > x0) 4 // "UP RIGHT"
    else if (y > y0 && x < x0) 5 // "UP LEFT"
    else if (y < y0 && x > x0) 6 // "DOWN RIGHT"
    else if (y < y0 && x < x0) 7 // "DOWN LEFT"
    else throw new Exception(s"don't know $x $y")
  }

  def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)

  val line = in.take(2).map(_.split(' ')).map {
    case Array("B", x, y) => (0, x.toInt, y.toInt)
    case Array("R", x, y) => (1, x.toInt, y.toInt)
    case Array("Q", x, y) => (2, x.toInt, y.toInt)
  }.filter{
    case (d, x, y) => mayBlock(x, y)
  }.toList

  val res = line.sortBy {
    case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))
  }.foldLeft(false, Set.empty[Int]) {
    case ((true, set), el) => (true, set)
    case ((false, set), (l, x, y)) =>
      val score = scoreBlock(x, y)
      println(set)
      if (set.contains(score))
        (false, set)
      else if (attack(l, score))
        (true, set)
      else
        (false, set + score)
  }._1
  if (res)
    println("YES")
  else
    println("NO")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val Array(x0, y0) = in.next().split(' ').map(_.toLong)

  def mayBlock(x: Long, y: Long) = {
    x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))
  }

  def scoreBlock(x: Long, y: Long) = {
    if (x == x0 && y > y0) 0 //"UP"
    else if (x == x0 && y < y0) 1 // "DOWN"
    else if (y == y0 && x > x0) 2 // "RIGHT"
    else if (y == y0 && x < x0) 3 // "LEFT"
    else if (y > y0 && x > x0) 4 // "UP RIGHT"
    else if (y > y0 && x < x0) 5 // "UP LEFT"
    else if (y < y0 && x > x0) 6 // "DOWN RIGHT"
    else if (y < y0 && x < x0) 7 // "DOWN LEFT"
    else throw new Exception(s"don't know $x $y")
  }

  def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)

  val line = in.take(2).map(_.split(' ')).map {
    case Array("B", x, y) => (0, x.toLong, y.toLong)
    case Array("R", x, y) => (1, x.toLong, y.toLong)
    case Array("Q", x, y) => (2, x.toLong, y.toLong)
  }.filter{ case (d, x, y) => mayBlock(x, y) }.toList
    .sortBy {
    case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))
  }

  val res = line.foldLeft(false, Set.empty[Int]) {
    case ((true, set), el) => (true, set)
    case ((false, set), (l, x, y)) =>
      val score = scoreBlock(x, y)
      if (set.contains(score))
        (false, set)
      else if (attack(l, score))
        (true, set)
      else
        (false, set + score)
  }._1
  if (res)
    println("YES")
  else
    println("NO")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val Array(x0, y0) = in.next().split(' ').map(_.toLong)

  def mayBlock(x: Int, y: Int) = {
    x == x0 || y == y0 || (Math.abs(x - x0) == Math.abs(y - y0))
  }

  def scoreBlock(x: Int, y: Int) = {
    if (x == x0 && y > y0) 0 //"UP"
    else if (x == x0 && y < y0) 1 // "DOWN"
    else if (y == y0 && x > x0) 2 // "RIGHT"
    else if (y == y0 && x < x0) 3 // "LEFT"
    else if (y > y0 && x > x0) 4 // "UP RIGHT"
    else if (y > y0 && x < x0) 5 // "UP LEFT"
    else if (y < y0 && x > x0) 6 // "DOWN RIGHT"
    else if (y < y0 && x < x0) 7 // "DOWN LEFT"
    else throw new Exception(s"don't know $x $y")
  }

  def attack(t: Int, score: Int) = t == 2 || (t == 0 && score > 3) || (t == 1 && score < 4)

  val line = in.take(2).map(_.split(' ')).map {
    case Array("B", x, y) => (0, x.toInt, y.toInt)
    case Array("R", x, y) => (1, x.toInt, y.toInt)
    case Array("Q", x, y) => (2, x.toInt, y.toInt)
  }.filter{
    case (d, x, y) => mayBlock(x, y)
  }.toList

  val res = line.sortBy {
    case (s, x, y) => Math.max(Math.abs(x - x0), Math.abs(y - y0))
  }.foldLeft(false, Set.empty[Int]) {
    case ((true, set), el) => (true, set)
    case ((false, set), (l, x, y)) =>
      val score = scoreBlock(x, y)
      if (set.contains(score))
        (false, set)
      else if (attack(l, score))
        (true, set)
      else
        (false, set + score)
  }._1
  if (res)
    println("YES")
  else
    println("NO")
}


You are playing a strange game with Li Chen. You have a tree with $$$n$$$ nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from $$$1$$$ to $$$n$$$. Neither of you know the other's labelling of the tree.You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled $$$x_1, x_2, \ldots, x_{k_1}$$$ in your labeling, Li Chen's subtree consists of the vertices labeled $$$y_1, y_2, \ldots, y_{k_2}$$$ in his labeling. The values of $$$x_1, x_2, \ldots, x_{k_1}$$$ and $$$y_1, y_2, \ldots, y_{k_2}$$$ are known to both of you.   The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most $$$5$$$ questions, each of which is in one of the following two forms:   A x: Andrew will look at vertex $$$x$$$ in your labeling and tell you the number of this vertex in Li Chen's labeling.  B y: Andrew will look at vertex $$$y$$$ in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.

NoteFor the first sample, Li Chen's hidden permutation is $$$[2, 3, 1]$$$, and for the second, his hidden permutation is $$$[5, 3, 2, 4, 1, 6]$$$ for both cases.In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose:   In the first question, you ask Andrew to look at node $$$1$$$ in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with $$$2$$$. At this point, you know that both of your subtrees contain the same node (i.e. node $$$1$$$ according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node $$$2$$$ in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with $$$1$$$ (this step was given with the only reason — to show you how to ask questions).For the second sample, there are two test cases. The first looks is the one from the statement:   We first ask "B 2", and Andrew will tell us $$$3$$$. In this case, we know $$$3$$$ is a common vertex, and moreover, any subtree with size $$$3$$$ that contains node $$$3$$$ must contain node $$$1$$$ as well, so we can output either "C 1" or "C 3" as our answer.In the second case in the second sample, the situation looks as follows:   In this case, you know that the only subtree of size $$$3$$$ that doesn't contain node $$$1$$$ is subtree $$$4,5,6$$$. You ask Andrew for the label of node $$$1$$$ in Li Chen's labelling and Andrew says $$$5$$$. In this case, you know that Li Chen's subtree doesn't contain node $$$1$$$, so his subtree must be consist of the nodes $$$4,5,6$$$ (in your labelling), thus the two subtrees have no common nodes.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    def ask(com: Char, node: Int): Int = {
      println(s"$com $node")
      ni()
    }

    def answer(node: Int): Unit = {
      println(s"C $node")
    }

    rep(ni()) { _ =>
      val N = ni()
      val (from, to) = na2(N - 1, -1)
      val g = packUGraph(N, from, to)
      val k1 = ni()
      val X = na(k1, -1)
      val k2 = ni()
      val Y = na(k2, -1)
      val setY = Set(Y: _*)
      val y0_x = ask('B', Y(0) + 1) - 1
      val rootSubTree = find(g, X, y0_x)
      val root_y = ask('A', rootSubTree + 1) - 1
      if (setY.contains(root_y)) {
        answer(rootSubTree + 1)
      } else {
        answer(-1)
      }
    }
  }

  def find(g: Array[Array[Int]], set: Array[Int], from: Int): Int = {
    val (depth, _, _) = traceBfs(g, from)
    set.minBy(v => depth(v))
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      rep(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    rep(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    rep(n) { i =>
      rep(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(t) = readInts(1)

  for (_ <- 1 to t) {
    val Array(n) = readInts(1)

    val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }
    for (_ <- 1 until n) {
      val Array(a, b) = readInts(2)
      adjBuilders(a - 1) += b - 1
      adjBuilders(b - 1) += a - 1
    }
    val adjs = adjBuilders.map(_.result())

    val Array(k1) = readInts(1)
    val xs = readInts(k1).toSet

    val Array(k2) = readInts(1)
    val ys = readInts(k2).toSet

    println("B " + ys.min)
    val xx = readLine.toInt

    def dfs(u: Int, parent: Int, depth: Int): Int = {
      if (xs(u + 1)) u
      else {
        val it = adjs(u).iterator
        var res = -1
        while (it.hasNext) {
          val v = it.next()
          if (v != parent) {
            val d = dfs(v, u, depth + 1)
            if (d >= 0) res = d
          }
        }
        res
      }
    }

    val d = dfs(xx - 1, -1, 0) + 1

    println("A " + d)
    val yy = readLine.toInt

    if (ys(yy)) println("C " + d)
    else println("C -1")
  }
}

import java.io._
import java.util
import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  def dfs(x: Int): Int = {
    was(x) = true
    if (set1.contains(x))
      x
    else {
      var ans = -1
      edges(x).foreach { e =>
        if (!was(e) && ans == -1)
          ans = dfs(e)
      }
      ans
    }
  }

  val was = Array.fill(1000)(false)
  val edges = Array.fill(1000)(ArrayBuffer[Int]())
  val set1 = mutable.Set[Int]()
  val set2 = mutable.Set[Int]()

  def solve(in: InputReader): Unit = {
    val tests = in.nextInt
    (1 to tests).foreach { _ =>
      val n = in.nextInt
      util.Arrays.fill(was, false)
      edges.foreach(_.clear())
      (1 until n) foreach { _ =>
        val x, y = in.nextInt - 1
        edges(x).append(y)
        edges(y).append(x)
      }
      val k1 = in.nextInt
      set1.clear()
      (1 to k1).foreach(_ => set1.add(in.nextInt - 1))

      val k2 = in.nextInt
      set2.clear()
      (1 to k2).foreach(_ => set2.add(in.nextInt - 1))
      //set2.foreach(println)
      System.out.println(s"B ${set2.head + 1}")
      System.out.flush()
      val t = in.nextInt - 1

      val ans = dfs(t)

      System.out.println(s"A ${ans + 1}")
      System.out.flush()

      if (set2.contains(in.nextInt - 1))
        System.out.println(s"C ${ans + 1}")
      else
        System.out.println(s"C -1")
      System.out.flush()
    }

  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

    def next: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens) {
        tokenizer = new StringTokenizer(readLine)
      }
      tokenizer.nextToken
    }

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    def ask(com: Char, node: Int): Int = {
      println(s"$com $node")
      ni()
    }

    def answer(node: Int): Unit = {
      println(s"C $node")
    }

    rep(ni()) { _ =>
      val N = ni()
      val (from, to) = na2(N - 1, -1)
      val g = packUGraph(N, from, to)
      val k1 = ni()
      val X = na(k1, -1)
      val k2 = ni()
      val Y = na(k2, -1)
      val setY = Set(Y: _*)
      if (k1 <= 5) {
        val ys = map(k1) { i =>
          ask('A', X(i) + 1) - 1
        }
        val ok = ys find setY.contains
        val ans = ok.map(_+1).getOrElse(-1)
        answer(ans)
      } else {
        val y = Y(0)
        val y_x = ask('B', y) - 1
        val rootSubTree = find(g, X, y_x)
        val root_y = ask('A', rootSubTree + 1) - 1
        if (setY.contains(root_y)) {
          answer(root_y + 1)
        } else {
          answer(-1)
        }
      }
    }
  }

  def find(g: Array[Array[Int]], set: Array[Int], from: Int): Int = {
    val (depth, _, _) = traceBfs(g, from)
    set.minBy(v => depth(v))
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      rep(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    rep(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    rep(n) { i =>
      rep(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


Alice lives on a flat planet that can be modeled as a square grid of size $$$n \times n$$$, with rows and columns enumerated from $$$1$$$ to $$$n$$$. We represent the cell at the intersection of row $$$r$$$ and column $$$c$$$ with ordered pair $$$(r, c)$$$. Each cell in the grid is either land or water.  An example planet with $$$n = 5$$$. It also appears in the first sample test. Alice resides in land cell $$$(r_1, c_1)$$$. She wishes to travel to land cell $$$(r_2, c_2)$$$. At any moment, she may move to one of the cells adjacent to where she is—in one of the four directions (i.e., up, down, left, or right).Unfortunately, Alice cannot swim, and there is no viable transportation means other than by foot (i.e., she can walk only on land). As a result, Alice's trip may be impossible.To help Alice, you plan to create at most one tunnel between some two land cells. The tunnel will allow Alice to freely travel between the two endpoints. Indeed, creating a tunnel is a lot of effort: the cost of creating a tunnel between cells $$$(r_s, c_s)$$$ and $$$(r_t, c_t)$$$ is $$$(r_s-r_t)^2 + (c_s-c_t)^2$$$.For now, your task is to find the minimum possible cost of creating at most one tunnel so that Alice could travel from $$$(r_1, c_1)$$$ to $$$(r_2, c_2)$$$. If no tunnel needs to be created, the cost is $$$0$$$.

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the width of the square grid. The second line contains two space-separated integers $$$r_1$$$ and $$$c_1$$$ ($$$1 \leq r_1, c_1 \leq n$$$) — denoting the cell where Alice resides. The third line contains two space-separated integers $$$r_2$$$ and $$$c_2$$$ ($$$1 \leq r_2, c_2 \leq n$$$) — denoting the cell to which Alice wishes to travel. Each of the following $$$n$$$ lines contains a string of $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th such line ($$$1 \leq i, j \leq n$$$) is 0 if $$$(i, j)$$$ is land or 1 if $$$(i, j)$$$ is water. It is guaranteed that $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are land.

Print an integer that is the minimum possible cost of creating at most one tunnel so that Alice could travel from $$$(r_1, c_1)$$$ to $$$(r_2, c_2)$$$.

NoteIn the first sample, a tunnel between cells $$$(1, 4)$$$ and $$$(4, 5)$$$ should be created. The cost of doing so is $$$(1-4)^2 + (4-5)^2 = 10$$$, which is optimal. This way, Alice could walk from $$$(1, 1)$$$ to $$$(1, 4)$$$, use the tunnel from $$$(1, 4)$$$ to $$$(4, 5)$$$, and lastly walk from $$$(4, 5)$$$ to $$$(5, 5)$$$.In the second sample, clearly a tunnel between cells $$$(1, 3)$$$ and $$$(3, 1)$$$ needs to be created. The cost of doing so is $$$(1-3)^2 + (3-1)^2 = 8$$$.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val r1, c1, r2, c2 = ni() - 1
    val g = Array.ofDim[Array[Boolean]](N) // landかどうか
    REP(N) { i =>
      g(i) = ns(N).map(_ == '0')
    }

    DEBUG {
      REP(N) { i =>
        debug(g(i))
      }
    }

    val uf = new UnionFind(N * N)
    val D = Array(
      Array(-1, 0), Array(1, 0), Array(0, -1), Array(0, 1)
    )

    def nd(r: Int, c: Int) = r * N + c
    def dist(v: Int, u: Int): Int = {
      val rv = v / N
      val cv = v % N
      val ru = u / N
      val cu = u % N
      val r = abs(rv - ru)
      val c = abs(cv - cu)
      r * r + c * c
    }

    val v1 = nd(r1, c1)
    val v2 = nd(r2, c2)
    REP(N) { i =>
      REP(N) { j =>
        if (g(i)(j)) {
          val v = nd(i, j)
          REP(4) { k =>
            val di = D(k)(0)
            val dj = D(k)(1)
            if (di + i >= 0 && di + i < N && dj + j >= 0 && dj + j < N && g(i + di)(j + dj)) {
              uf.unite(v, nd(i + di, j + dj))
            }
          }
        }
      }
    }

    def sameSet(v: Int) = {
      val set = Array.ofDim[Boolean](N * N)
      val id = uf.find(v)
      REP(N * N) { i =>
        if (uf.find(i) == id) set(i) = true
      }
      set
    }

    // 連結されてるのでトンネルいらない
    if (uf.find(v1) == uf.find(v2)) out.println(0)
    else {
      val set1 = sameSet(v1)
      val set2 = sameSet(v2)

      debug("set1")
      debug(set1)
      debug("set2")
      debug(set2)

      var ans = 1e9.toInt
      // 周辺だけにしてもいいけど2500 * 2500でまにあうからやらない
      REP(N * N) { v =>
        REP(N * N) { u =>
          if (set1(v) && set2(u)) {
            ans = min(ans, dist(v, u))
          }
        }
      }

      out.println(ans)
    }
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    REP(n) (i => par(i) = i)
    val rank: Array[Int] = Array.fill[Int](n)(1) // 集合の要素数
    private val visits = Array.ofDim[Int](n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす

    def find(x: Int): Int = {
      var ptr = 0
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          visits(ptr) = x
          ptr += 1
          step(par(x))
        }
      }

      val res = step(x)
      REP(ptr){ i => par(visits(i)) = res }
      res
    }

    def unite(x: Int, y: Int): Int = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 == y1) x1
      else {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
          y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += rank(y1)
          x1
        }
      }
    }

    /**
      * xを解決する必要がないときは直にrankをみる
      */
    def cntNodes(x: Int): Int = rank(find(x))
  }

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugNum(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.io.StdIn

object Codeforces1130C {

  def getMinimumTunnelLength(n: Int, r1: Int, c1: Int, r2: Int, c2: Int, grid: Seq[String]): Int = {
    val componentNumbers: Array[Array[Int]] = (1 to n).map(_ => (1 to n).map(_ => -1).toArray).toArray
    var componentNumber = 1
    var unexploredPoint = getFirstUnexploredPoint(n, componentNumbers)
    while (unexploredPoint != NullPoint) {
      startExploring(n, componentNumbers, grid, componentNumber, unexploredPoint)
      componentNumber += 1
      unexploredPoint = getFirstUnexploredPoint(n, componentNumbers)
    }

    val fromComponent = componentNumbers(r1 - 1)(c1 - 1)
    val toComponent = componentNumbers(r2 - 1)(c2 - 1)

    var minimumDistance = Int.MaxValue
    for (x1 <- 0 until n) for (y1 <- 0 until n) for (x2 <- 0 until n) for (y2 <- 0 until n)
      if (componentNumbers(x1)(y1) == fromComponent && componentNumbers(x2)(y2) == toComponent)
        minimumDistance = math.min(minimumDistance, calculateDistance(x1, y1, x2, y2))

    minimumDistance
  }

  def calculateDistance(x1: Int, y1: Int, x2: Int, y2: Int): Int = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)

  def getFirstUnexploredPoint(n: Int, componentNumbers: Array[Array[Int]]): Point = {
    for (i <- 0 until n) for (j <- 0 until n)
      if (componentNumbers(i)(j) == -1) return Point(i, j)
    NullPoint
  }

  def startExploring(n: Int, componentNumbers: Array[Array[Int]], grid: Seq[String], componentNumber: Int, point: Point): Unit = {
    componentNumbers(point.x)(point.y) = componentNumber
    for (neighbourPoint <- point.neighboursInRange(n)) {
      if (isSameType(point, neighbourPoint, grid)) {
        if (!isExplored(neighbourPoint, componentNumbers)) {
          startExploring(n, componentNumbers, grid, componentNumber, neighbourPoint)
        }
      }
    }
  }

  def isSameType(pointA: Point, pointB: Point, grid: Seq[String]): Boolean =
    grid(pointA.x)(pointA.y) == grid(pointB.x)(pointB.y)

  def isExplored(point: Point, componentNumbers: Array[Array[Int]]): Boolean =
    componentNumbers(point.x)(point.y) != -1

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val Array(r1, c1) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val Array(r2, c2) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val grid = (1 to n).map(_ => StdIn.readLine())

    val minimumTunnelLength = getMinimumTunnelLength(n, r1, c1, r2, c2, grid)
    println(minimumTunnelLength)
  }

  case class Point(x: Int, y: Int) {
    def isAdjacent(that: Point): Boolean =
      math.abs(this.x - that.x) + math.abs(this.y - that.y) == 1

    def left: Point = Point(x - 1, y)

    def right: Point = Point(x + 1, y)

    def up: Point = Point(x, y - 1)

    def down: Point = Point(x, y + 1)

    def fitsInRage(n: Int): Boolean = 0 <= x && x < n && 0 <= y && y < n

    def neighboursInRange(n: Int): Seq[Point] =
      Seq(left, right, up, down).filter(p => p.fitsInRage(n))
  }

  object NullPoint extends Point(-1, -1) {}

}