import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    var i = 0
    while (i < neighbours(u).length) {
      val v = neighbours(u)(i)
      if (v != parent) dfs(v, u, depth + 1)
      i += 1
    }
  }

  dfs(0, -1, 0)

  def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {
    var v = _v
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, min10)
  }

  def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    // now depths(v) == depths(u)
    var (v, min10) = levelAncestor(v0, depths(u), limit)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lowestCommonAncestor(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)

  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    //ancestorsBuilder.clear()
    //min10Builder.clear()

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }
    //    var depthDelta = 1
    //    while (depthDelta <= depth) {
    //      ancestorsBuilder += path(depth - depthDelta)
    //      depthDelta <<= 1
    //    }
    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) dfs(v, u, depth + 1)
    }
  }

  dfs(0, -1, 0)

  def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
        i += 1 // FIXME
      }
      i -= 1
    }
    // now depths(v) == depths(u)
    assert(depths(v) == depths(u))
//    if (ancestors(v).length != ancestors(u).length) {
//      println(ancestors(v).length, ancestors(u).length)
//      Console.flush
//      return Array.empty
//    }
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lca(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) dfs(v, u, depth + 1)
    }
  }

  dfs(0, -1, 0)

  def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {
    var v = _v
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, min10)
  }

  def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    // now depths(v) == depths(u)
    var (v, min10) = levelAncestor(v0, depths(u), limit)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lowestCommonAncestor(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder
import java.io.PrintWriter

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    var i = 0
    while (i < neighbours(u).length) {
      val v = neighbours(u)(i)
      if (v != parent) dfs(v, u, depth + 1)
      i += 1
    }
  }

  dfs(0, -1, 0)

  def levelAncestor(_v: Int, depth: Int, limit: Int): (Int , Array[Int]) = {
    var v = _v
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, min10)
  }

  def lowestCommonAncestor(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    // now depths(v) == depths(u)
    var (v, min10) = levelAncestor(v0, depths(u), limit)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

  val out = new PrintWriter(System.out)

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lowestCommonAncestor(u, v, a)
    out.println(res.length + " " + res.mkString(" "))
  }

  out.flush()
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val min10s = Array.ofDim[Array[Array[Int]]](n)

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    builder.sizeHint(limit)
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    ancestorsBuilder.sizeHint(17)
    val min10Builder = new ArrayBuilder.ofRef[Array[Int]]
    min10Builder.sizeHint(17)

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 0
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i < ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i), 10)
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) dfs(v, u, depth + 1)
    }
  }

  dfs(0, -1, 0)

  def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit)
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    // now depths(v) == depths(u)
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          min10 = merge(min10, min10s(v)(i), limit)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lca(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object C extends App {

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

  val Array(n, m, q) = readInts(3)

  val neighbourBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 until n) {
    val Array(u, v) = readInts(2)
    neighbourBuilders(u - 1) += v - 1
    neighbourBuilders(v - 1) += u - 1
  }
  val neighbours = neighbourBuilders.map(_.result)

  val cs = readInts(m)
  val pBuilders = Array.fill(n) { new ArrayBuilder.ofInt }
  for (i <- cs.indices) {
    pBuilders(cs(i) - 1) += i + 1
  }
  val ps = pBuilders.map(_.result.sorted)

  val depths = Array.ofDim[Int](n)

  val ancestors = Array.ofDim[Array[Int]](n)
  val ancestorsBuilder = new ArrayBuilder.ofInt

  val min10s = Array.ofDim[Array[Array[Int]]](n)
  val min10Builder = new ArrayBuilder.ofRef[Array[Int]]

  def merge(xs: Array[Int], ys: Array[Int], limit: Int): Array[Int] = {
    val builder = new ArrayBuilder.ofInt
    var xi, yi, size = 0
    while (size < limit && (xi < xs.length || yi < ys.length)) {
      if (xi < xs.length && (yi == ys.length || xs(xi) < ys(yi))) {
        builder += xs(xi)
        xi += 1
      } else {
        builder += ys(yi)
        yi += 1
      }
      size += 1
    }
    builder.result
  }

  def dfs(u: Int, parent: Int, depth: Int): Unit = {

    depths(u) = depth

    ancestorsBuilder.clear()
    min10Builder.clear()

    if (parent >= 0) {
      ancestorsBuilder += parent
      min10Builder += ps(parent)
      var i = 1
      var prev = parent
      var prevMin10 = ps(parent)
      while (prev > 0 && i <= ancestors(prev).length) {
        prevMin10 = merge(prevMin10, min10s(prev)(i - 1), 10)
        prev = ancestors(prev)(i - 1)
        ancestorsBuilder += prev
        min10Builder += prevMin10
        i += 1
      }
    }
    //    var depthDelta = 1
    //    while (depthDelta <= depth) {
    //      ancestorsBuilder += path(depth - depthDelta)
    //      depthDelta <<= 1
    //    }
    ancestors(u) = ancestorsBuilder.result
    min10s(u) = min10Builder.result

    for (v <- neighbours(u)) {
      if (v != parent) {
        dfs(v, u, depth + 1)
      }
    }
  }

  dfs(0, -1, 0)

  def lca(_v: Int, _u: Int, limit: Int): Array[Int] = {
    var (v, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var i = ancestors(v).length - 1
    var min10 = ps(v).take(limit) //Array.empty[Int]
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depths(u)) {
        min10 = merge(min10, min10s(v)(i), limit)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    //println(min10.mkString(" "))
    // now depths(v) == depths(u)
    if (ancestors(v).length != ancestors(u).length) {
      println(ancestors(v).length, ancestors(u).length)
      Console.flush
      return Array.empty
    }
    if (v == u) min10 // v
    else {
      min10 = merge(min10, ps(u), limit)
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          min10 = merge(min10, min10s(u)(i), limit)
          //println(min10.mkString(" "))
          min10 = merge(min10, min10s(v)(i), limit)
          //println(min10.mkString(" "))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      //ancestors(v)(0)
      merge(min10, ps(ancestors(v)(0)), limit)
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 0 until q) {
    val Array(_v, _u, a) = readInts(3)
    val v = _v - 1
    val u = _u - 1
    val res = lca(u, v, a)
    println(res.length + " " + res.mkString(" "))
  }

  Console.flush
}


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()
      }
    }
  }
}

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 = 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()
      }
    }
  }
}


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))
  }
}


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(" "))

}


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 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")
    }
  }
}

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")
    }
  }
}

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")
}


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)
      }
    }
  }

}

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")
  }
}

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
  }
}

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
  }
}


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) {}

}