Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms. Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)). Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs.

The first line of the input contains single integer n (1 ≤ n ≤ 105) — the number of moves in the walking sequence. The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.

On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.

NoteThe figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at which Fafa have to pay silver coins.

object _935B extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._

  override def apply(io: IO): io.type = {
    val (n, instr) = io.read[(Int, String)]

    val res = instr.scanLeft(0) {
      case (x, 'R') => x + 1
      case (x, 'U') => x - 1
    }

    //debug(res)

    var curr = if (instr.head == 'R') 1 else -1
    var ans = 0
    for {
      i <- res if i != 0
      if curr.signum != i.signum
    } {
      curr = i.signum
      ans += 1
    }

    io.write(ans)
  }
}
/****************************[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 = 0, until: Int = a.length)(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 = 0, until: Int = a.length)(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
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(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]).withDefaultValue(b().result())
    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
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  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 indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    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 getBit(i: Int): Int = (x >> i) & 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 getBit(i: Int): Long = (x >> i) & 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")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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


You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c). You are staying in the cell (r1, c1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2, c2) since the exit to the next level is there. Can you do this?

The first line contains two integers, n and m (1 ≤ n, m ≤ 500) — the number of rows and columns in the cave description. Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice). The next line contains two integers, r1 and c1 (1 ≤ r1 ≤ n, 1 ≤ c1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1, c1), that is, the ice on the starting cell is initially cracked. The next line contains two integers r2 and c2 (1 ≤ r2 ≤ n, 1 ≤ c2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.

If you can reach the destination, print 'YES', otherwise print 'NO'.

NoteIn the first sample test one possible path is:After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    Integer.parseInt(next)
  }

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  val dx = Array(0, 0, 1, -1)
  val dy = Array(1, -1, 0, 0)

  def check(n: Int, m: Int, x: Int, y: Int): Boolean = {
    0 <= x && x < n && 0 <= y && y < m
  }

  def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {
    val n = matrix.length
    val m = matrix(0).length
    val vst = Array.ofDim[Boolean](n, m)
    for (i <- 0 until n; j <- 0 until m) {
      vst(i)(j) = (matrix(i)(j) == 'X')
    }
    var queue = new mutable.Queue[(Int, Int)]()
    queue += Tuple2(startx, starty)
    while (queue.nonEmpty) {
      val front = queue.head
      queue = queue.tail
      for (i <- 0 until dx.length) {
        val nextx = front._1 + dx(i)
        val nexty = front._2 + dy(i)
        if (nextx == endx && nexty == endy) {
          return true
        }
        if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == false) {
          vst(nextx)(nexty) = true
          queue += Tuple2(nextx, nexty)
        }
      }
    }
    return false
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)

    val matrix = Array.ofDim[String](n)
    for (i <- 0 until n) {
      matrix(i) = next
    }
    val (startx, starty) = (nextInt - 1, nextInt - 1)
    val (endx, endy) = (nextInt - 1, nextInt - 1)

    var can_reach = 0
    for (i <- 0 until dx.length) {
      val nextx = endx + dx(i)
      val nexty = endy + dy(i)
      if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {
        can_reach += 1
      }
    }
    if (startx == endx && starty == endy) {
      if (can_reach != 0) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else if (matrix(endx)(endy) == 'X') {
      if (reach(matrix, startx, starty, endx, endy)) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else if (math.abs(startx - endx) + math.abs(starty - endy) == 1) {
      if (can_reach > 0) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else {
      if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    }
  }

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

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

import scala.collection.mutable

object C {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new Array[Array[Int]](n + 2)
    val d = new Array[Array[Int]](n + 2)
    for (i <- 0 until g.length) {
      g(i) = new Array[Int](m + 2)
      d(i) = new Array[Int](m + 2)
    }
    for (i <- 1 to n) {
      val in = next.toCharArray
      for (j <- 1 to m) {
        if (in(j - 1) == '.') {
          g(i)(j) = 1
        }
      }
    }
    val r1 = nextInt
    val c1 = nextInt
    val r2 = nextInt
    val c2 = nextInt
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    if (r1 == r2 && c1 == c2) {
      for (i <- 0 until 4) {
        val x1 = r1 + dx(i)
        val y1 = c1 + dy(i)
        if (g(x1)(y1) == 1) {
          out.println("YES")
          return 1
        }
      }
    } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {
      if (g(r2)(c2) == 0) {
        out.println("YES")
        return 1
      } else {
        var cnt = 0
        for (i <- 0 until 4) {
          val x1 = r2 + dx(i)
          val y1 = c2 + dy(i)
          if (g(x1)(y1) == 1) {
            cnt += 1
          }
        }
        if (cnt >= 1) {
          out.println("YES")
          return 1
        }
      }
    } else {
      val q = new mutable.Queue[(Int, Int)]()
      q.enqueue((r1, c1))

      while (!q.isEmpty) {
        val x = q.dequeue
        for (i <- 0 until 4) {
          val x1 = x._1 + dx(i)
          val y1 = x._2 + dy(i)
          if (x1 == r2 && y1 == c2) {
            if (g(r2)(c2) == 0) {
              out.println("YES")
              return 1
            } else {
              var cnt = 0
              for (i <- 0 until 4) {
                val x1 = r2 + dx(i)
                val y1 = c2 + dy(i)
                if (g(x1)(y1) == 1) {
                  cnt += 1
                }
              }
              if (cnt >= 2) {
                out.println("YES")
                return 1
              }
            }
          } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
            q.enqueue((x1, y1))
            d(x1)(y1) = d(x._1)(x._2) + 1
          }
        }
      }
    }
    out.println("NO")
    return 0
  }
}

import annotation.tailrec

object main extends App with fastIO {

  case class Point(x: Int, y: Int)

  val dx = Vector(-1, 0, 1, 0)
  val dy = Vector(0, -1, 0, 1)

  def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }

  def bfs(p: Point) {

    var q = scala.collection.mutable.Queue(p)

    def run(x: Int, y: Int) {
      if (!ok(x, y)) return
      if (a(x)(y) == 1) return
      if (used(x)(y)) return

      used(x)(y) = true
      for (i <- 0 until 4)
        q += Point(x + dx(i), y + dy(i))
    }

    while (!q.isEmpty) {
      val (x, y) = (q.front.x, q.front.y)
      q.dequeue; run(x, y)
    }
  }

  var Array(n, m) = readLine split(" ") map(_.toInt)
  var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)
  var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))
  var used = Array.ofDim[Boolean](n, m)

  a(p1.x)(p1.y) = 0
  var cnt = a(p2.x)(p2.y) * 2
  for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i)))
    cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))
  if (p1 == p2) cnt += 1

  a(p2.x)(p2.y) = 0
  for (i <- 0 until 4) bfs(Point(p1.x + dx(i), p1.y + dy(i)))

  println(if (cnt > 1 && used(p2.x)(p2.y)) "YES" else "NO")
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    Integer.parseInt(next)
  }

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  val dx = Array(0, 0, 1, -1)
  val dy = Array(1, -1, 0, 0)

  def check(n: Int, m: Int, x: Int, y: Int): Boolean = {
    0 <= x && x < n && 0 <= y && y < m
  }

  def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {
    val n = matrix.length
    val m = matrix(0).length
    val vst = Array.ofDim[Boolean](n, m)
    for (i <- 0 until n; j <- 0 until m) {
      vst(i)(j) = (matrix(i)(j) == 'X')
    }
    var queue = new mutable.Queue[(Int, Int)]()
    queue += Tuple2(startx, starty)
    while (queue.nonEmpty) {
      val front = queue.head
      queue = queue.tail
      for (i <- 0 until dx.length) {
        val nextx = front._1 + dx(i)
        val nexty = front._2 + dy(i)
        if (nextx == endx && nexty == endy) {
          return true
        }
        if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == '.') {
          vst(nextx)(nexty) = true
          queue += Tuple2(nextx, nexty)
        }
      }
    }
    return false
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)

    val matrix = Array.ofDim[String](n)
    for (i <- 0 until n) {
      matrix(i) = next
    }
    val (startx, starty) = (nextInt - 1, nextInt - 1)
    val (endx, endy) = (nextInt - 1, nextInt - 1)

    var can_reach = 0
    for (i <- 0 until dx.length) {
      val nextx = endx + dx(i)
      val nexty = endy + dy(i)
      if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {
        can_reach += 1
      }
    }
    if (startx == endx && starty == endy) {
      if (can_reach != 0) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else if (matrix(endx)(endy) == 'X') {
      if (reach(matrix, startx, starty, endx, endy)) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else {
      if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    Integer.parseInt(next)
  }

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  val dx = Array(0, 0, 1, -1)
  val dy = Array(1, -1, 0, 0)

  def check(n: Int, m: Int, x: Int, y: Int): Boolean = {
    0 <= x && x < n && 0 <= y && y < m
  }

  def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {
    val n = matrix.length
    val m = matrix(0).length
    val vst = Array.ofDim[Boolean](n, m)
    for (i <- 0 until n; j <- 0 until m) {
      vst(i)(j) = (matrix(i)(j) == 'X')
    }
    var queue = new mutable.Queue[(Int, Int)]()
    queue += Tuple2(startx, starty)
    while (queue.nonEmpty) {
      val front = queue.head
      queue = queue.tail
      for (i <- 0 until dx.length) {
        val nextx = front._1 + dx(i)
        val nexty = front._2 + dy(i)
        if (nextx == endx && nexty == endy) {
          return true
        }
        if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == false) {
          vst(nextx)(nexty) = true
          queue += Tuple2(nextx, nexty)
        }
      }
    }
    return false
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)

    val matrix = Array.ofDim[String](n)
    for (i <- 0 until n) {
      matrix(i) = next
    }
    val (startx, starty) = (nextInt - 1, nextInt - 1)
    val (endx, endy) = (nextInt - 1, nextInt - 1)

    var can_reach = 0
    for (i <- 0 until dx.length) {
      val nextx = endx + dx(i)
      val nexty = endy + dy(i)
      if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {
        can_reach += 1
      }
    }
    if (startx == endx && starty == endy) {
      if (can_reach != 0) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else if (matrix(endx)(endy) == 'X') {
      if (reach(matrix, startx, starty, endx, endy)) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else {
      if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    Integer.parseInt(next)
  }

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  val dx = Array(0, 0, 1, -1)
  val dy = Array(1, -1, 0, 0)

  def check(n: Int, m: Int, x: Int, y: Int): Boolean = {
    0 <= x && x < n && 0 <= y && y < m
  }

  def reach(matrix: Array[String], startx: Int, starty: Int, endx: Int, endy: Int): Boolean = {
    val n = matrix.length
    val m = matrix(0).length
    val vst = Array.ofDim[Boolean](n, m)
    for (i <- 0 until n; j <- 0 until m) {
      vst(i)(j) = (matrix(i)(j) == 'X')
    }
    var queue = new mutable.Queue[(Int, Int)]()
    queue += Tuple2(startx, starty)
    while (queue.nonEmpty) {
      val front = queue.head
      queue = queue.tail
      for (i <- 0 until dx.length) {
        val nextx = front._1 + dx(i)
        val nexty = front._2 + dy(i)
        if (nextx == endx && nexty == endy) {
          return true
        }
        if (check(n, m, nextx, nexty) && vst(nextx)(nexty) == false) {
          vst(nextx)(nexty) = true
          queue += Tuple2(nextx, nexty)
        }
      }
    }
    return false
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)

    val matrix = Array.ofDim[String](n)
    for (i <- 0 until n) {
      matrix(i) = next
    }
    val (startx, starty) = (nextInt - 1, nextInt - 1)
    val (endx, endy) = (nextInt - 1, nextInt - 1)

    var can_reach = 0
    for (i <- 0 until dx.length) {
      val nextx = endx + dx(i)
      val nexty = endy + dy(i)
      if (check(n, m, nextx, nexty) && matrix(nextx)(nexty) == '.') {
        can_reach += 1
      }
    }
    if (startx == endx && starty == endy) {
      if (can_reach != 0) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else if (math.abs(startx - endx) + math.abs(starty - endy) == 1) {
      if (can_reach > 0) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else if (matrix(endx)(endy) == 'X') {
      if (reach(matrix, startx, starty, endx, endy)) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    } else {
      if (reach(matrix, startx, starty, endx, endy) && can_reach > 1) {
        out.println("YES")
      } else {
        out.println("NO")
      }
    }
  }

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

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

import scala.collection.mutable

object C {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new Array[Array[Int]](n + 2)
    val d = new Array[Array[Int]](n + 2)
    for (i <- 0 until g.length) {
      g(i) = new Array[Int](m + 2)
      d(i) = new Array[Int](m + 2)
    }
    for (i <- 1 to n) {
      val in = next.toCharArray
      for (j <- 1 to m) {
        if (in(j - 1) == '.') {
          g(i)(j) = 1
        }
      }
    }
    val r1 = nextInt
    val c1 = nextInt
    val r2 = nextInt
    val c2 = nextInt
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    if (r1 == r2 && c1 == c2) {
      for (i <- 0 until 4) {
        val x1 = r1 + dx(i)
        val y1 = c1 + dy(i)
        if (g(x1)(y1) == 1) {
          out.println("YES")
          return 1
        }
      }
    } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {
      if (g(r2)(c2) == 1) {
        out.println("YES")
        return 1
      } else {
        for (i <- 0 until 4) {
          val x1 = r2 + dx(i)
          val y1 = c2 + dy(i)
          if (g(x1)(y1) == 1) {
            out.println("YES")
            return 1
          }
        }
      }
    } else {
      val q = new mutable.Queue[(Int, Int)]()
      q.enqueue((r1, c1))

      while (!q.isEmpty) {
        val x = q.dequeue
        for (i <- 0 until 4) {
          val x1 = x._1 + dx(i)
          val y1 = x._2 + dy(i)
          if (x1 == r2 && y1 == c2) {
            if (g(x1)(y1) == 0) {
              out.println("YES")
              return 1
            } else {
              for (i <- 0 until 4) {
                val x1 = r2 + dx(i)
                val y1 = c2 + dy(i)
                if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
                  out.println("YES")
                  return 1
                }
              }
              out.println("NO")
              return 1
            }
          } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
            q.enqueue((x1, y1))
            d(x1)(y1) = d(x._1)(x._2) + 1
          }
        }
      }
    }
    out.println("NO")
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new Array[Array[Int]](n + 2)
    val d = new Array[Array[Int]](n + 2)
    for (i <- 0 until g.length) {
      g(i) = new Array[Int](m + 2)
      d(i) = new Array[Int](m + 2)
    }
    for (i <- 1 to n) {
      val in = next.toCharArray
      for (j <- 1 to m) {
        if (in(j - 1) == '.') {
          g(i)(j) = 1
        }
      }
    }
    val r1 = nextInt
    val c1 = nextInt
    val r2 = nextInt
    val c2 = nextInt
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    if (r1 == r2 && c1 == c2) {
      for (i <- 0 until 4) {
        val x1 = r1 + dx(i)
        val y1 = c1 + dy(i)
        if (g(x1)(y1) == 1) {
          out.println("YES")
          return 1
        }
      }
    } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {
      if (g(r2)(c2) == 0) {
        out.println("YES")
        return 1
      } else {
        for (i <- 0 until 4) {
          val x1 = r2 + dx(i)
          val y1 = c2 + dy(i)
          if (g(x1)(y1) == 1) {
            out.println("YES")
            return 1
          }
        }
      }
    } else {
      val q = new mutable.Queue[(Int, Int)]()
      q.enqueue((r1, c1))

      while (!q.isEmpty) {
        val x = q.dequeue
        for (i <- 0 until 4) {
          val x1 = x._1 + dx(i)
          val y1 = x._2 + dy(i)
          if (x1 == r2 && y1 == c2) {
            if (g(x1)(y1) == 0) {
              out.println("YES")
              return 1
            } else {
              for (i <- 0 until 4) {
                val x1 = r2 + dx(i)
                val y1 = c2 + dy(i)
                if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
                  out.println("YES")
                  return 1
                }
              }
              out.println("NO")
              return 1
            }
          } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
            q.enqueue((x1, y1))
            d(x1)(y1) = d(x._1)(x._2) + 1
          }
        }
      }
    }
    out.println("NO")
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new Array[Array[Int]](n + 2)
    val d = new Array[Array[Int]](n + 2)
    for (i <- 0 until g.length) {
      g(i) = new Array[Int](m + 2)
      d(i) = new Array[Int](m + 2)
    }
    for (i <- 1 to n) {
      val in = next.toCharArray
      for (j <- 1 to m) {
        if (in(j - 1) == '.') {
          g(i)(j) = 1
        }
      }
    }
    val r1 = nextInt
    val c1 = nextInt
    val r2 = nextInt
    val c2 = nextInt
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    if (r1 == r2 && c1 == c2) {
      for (i <- 0 until 4) {
        val x1 = r1 + dx(i)
        val y1 = c1 + dy(i)
        if (g(x1)(y1) == 1) {
          out.println("YES")
          return 1
        }
      }
    } else if (r1 == r2 || c1 == c2) {
      if (g(r2)(c2) == 1) {
        out.println("YES")
        return 1
      } else {
        for (i <- 0 until 4) {
          val x1 = r2 + dx(i)
          val y1 = c2 + dy(i)
          if (g(x1)(y1) == 1) {
            out.println("YES")
            return 1
          }
        }
      }
    } else {
      val q = new mutable.Queue[(Int, Int)]()
      q.enqueue((r1, c1))

      while (!q.isEmpty) {
        val x = q.dequeue
        for (i <- 0 until 4) {
          val x1 = x._1 + dx(i)
          val y1 = x._2 + dy(i)
          if (x1 == r2 && y1 == c2) {
            if (g(x1)(y1) == 0) {
              out.println("YES")
              return 1
            } else {
              for (i <- 0 until 4) {
                val x1 = r2 + dx(i)
                val y1 = c2 + dy(i)
                if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
                  out.println("YES")
                  return 1
                }
              }
              out.println("NO")
              return 1
            }
          } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
            q.enqueue((x1, y1))
            d(x1)(y1) = d(x._1)(x._2) + 1
          }
        }
      }
    }
    out.println("NO")
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new Array[Array[Int]](n + 2)
    val d = new Array[Array[Int]](n + 2)
    for (i <- 0 until g.length) {
      g(i) = new Array[Int](m + 2)
      d(i) = new Array[Int](m + 2)
    }
    for (i <- 1 to n) {
      val in = next.toCharArray
      for (j <- 1 to m) {
        if (in(j - 1) == '.') {
          g(i)(j) = 1
        }
      }
    }
    val r1 = nextInt
    val c1 = nextInt
    val r2 = nextInt
    val c2 = nextInt
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    if (r1 == r2 && c1 == c2) {
      for (i <- 0 until 4) {
        val x1 = r1 + dx(i)
        val y1 = c1 + dy(i)
        if (g(x1)(y1) == 1) {
          out.println("YES")
          return 1
        }
      }
    } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {
      if (g(r2)(c2) == 0) {
        out.println("YES")
        return 1
      } else {
        var cnt = 0
        for (i <- 0 until 4) {
          val x1 = r2 + dx(i)
          val y1 = c2 + dy(i)
          if (g(x1)(y1) == 1) {
            cnt += 1
          }
        }
        if (cnt >= 2) {
          out.println("YES")
          return 1
        }
      }
    } else {
      val q = new mutable.Queue[(Int, Int)]()
      q.enqueue((r1, c1))

      while (!q.isEmpty) {
        val x = q.dequeue
        for (i <- 0 until 4) {
          val x1 = x._1 + dx(i)
          val y1 = x._2 + dy(i)
          if (x1 == r2 && y1 == c2) {
            if (g(x1)(y1) == 0) {
              out.println("YES")
              return 1
            } else {
              for (i <- 0 until 4) {
                val x1 = r2 + dx(i)
                val y1 = c2 + dy(i)
                if (g(x1)(y1) == 1) {
                  out.println("YES")
                  return 1
                }
              }
              out.println("NO")
              return 1
            }
          } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
            q.enqueue((x1, y1))
            d(x1)(y1) = d(x._1)(x._2) + 1
          }
        }
      }
    }
    out.println("NO")
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new Array[Array[Int]](n + 2)
    val d = new Array[Array[Int]](n + 2)
    for (i <- 0 until g.length) {
      g(i) = new Array[Int](m + 2)
      d(i) = new Array[Int](m + 2)
    }
    for (i <- 1 to n) {
      val in = next.toCharArray
      for (j <- 1 to m) {
        if (in(j - 1) == '.') {
          g(i)(j) = 1
        }
      }
    }
    val r1 = nextInt
    val c1 = nextInt
    val r2 = nextInt
    val c2 = nextInt
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    if (r1 == r2 && c1 == c2) {
      for (i <- 0 until 4) {
        val x1 = r1 + dx(i)
        val y1 = c1 + dy(i)
        if (g(x1)(y1) == 1) {
          out.println("YES")
          return 1
        }
      }
    } else if ((r1 == r2 && Math.abs(c1 - c2) == 1) || (c1 == c2 && Math.abs(r1 - r2) == 1)) {
      if (g(r2)(c2) == 0) {
        out.println("YES")
        return 1
      } else {
        var cnt = 0
        for (i <- 0 until 4) {
          val x1 = r2 + dx(i)
          val y1 = c2 + dy(i)
          if (g(x1)(y1) == 1) {
            cnt += 1
          }
        }
        if (cnt >= 2) {
          out.println("YES")
          return 1
        }
      }
    } else {
      val q = new mutable.Queue[(Int, Int)]()
      q.enqueue((r1, c1))

      while (!q.isEmpty) {
        val x = q.dequeue
        for (i <- 0 until 4) {
          val x1 = x._1 + dx(i)
          val y1 = x._2 + dy(i)
          if (x1 == r2 && y1 == c2) {
            if (g(r2)(c2) == 0) {
              out.println("YES")
              return 1
            } else {
              var cnt = 0
              for (i <- 0 until 4) {
                val x1 = r2 + dx(i)
                val y1 = c2 + dy(i)
                if (g(x1)(y1) == 1) {
                  cnt += 1
                }
              }
              if (cnt >= 2) {
                out.println("YES")
                return 1
              }
            }
          } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
            q.enqueue((x1, y1))
            d(x1)(y1) = d(x._1)(x._2) + 1
          }
        }
      }
    }
    out.println("NO")
    return 0
  }
}

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

import scala.collection.mutable

object C {

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new Array[Array[Int]](n + 2)
    val d = new Array[Array[Int]](n + 2)
    for (i <- 0 until g.length) {
      g(i) = new Array[Int](m + 2)
      d(i) = new Array[Int](m + 2)
    }
    for (i <- 1 to n) {
      val in = next.toCharArray
      for (j <- 1 to m) {
        if (in(j - 1) == '.') {
          g(i)(j) = 1
        }
      }
    }
    val r1 = nextInt
    val c1 = nextInt
    val r2 = nextInt
    val c2 = nextInt
    val dx = Array(-1, 1, 0, 0)
    val dy = Array(0, 0, -1, 1)
    if (r1 == r2 && c1 == c2) {
      for (i <- 0 until 4) {
        val x1 = r1 + dx(i)
        val y1 = c1 + dy(i)
        if (g(x1)(y1) == 1) {
          out.println("YES")
          return 1
        }
      }
    } else {
      val q = new mutable.Queue[(Int, Int)]()
      q.enqueue((r1, c1))

      while (!q.isEmpty) {
        val x = q.dequeue
        for (i <- 0 until 4) {
          val x1 = x._1 + dx(i)
          val y1 = x._2 + dy(i)
          if (x1 == r2 && y1 == c2) {
            if (g(x1)(y1) == 0) {
              out.println("YES")
              return 1
            } else {
              for (i <- 0 until 4) {
                val x1 = r2 + dx(i)
                val y1 = c2 + dy(i)
                if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
                  out.println("YES")
                  return 1
                }
              }
              out.println("NO")
              return 1
            }
          } else if (g(x1)(y1) == 1 && d(x1)(y1) == 0) {
            q.enqueue((x1, y1))
            d(x1)(y1) = d(x._1)(x._2) + 1
          }
        }
      }
    }
    out.println("NO")
    return 0
  }

}

object main extends App with fastIO {

  case class Point(x: Int, y: Int)

  val dx = Vector(-1, 0, 1, 0)
  val dy = Vector(0, -1, 0, 1)

  def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }

  def dfs(x: Int, y: Int) {
    if (!ok(x, y)) return
    if (a(x)(y) == 1) return
    if (used(x)(y)) return

    used(x)(y) = true
    for (i <- 0 until 4)
      dfs(x + dx(i), y + dy(i))
  }

  var Array(n, m) = readLine split(" ") map(_.toInt)
  var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)
  var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))
  var used = Array.ofDim[Boolean](n, m)

  var cnt = a(p2.x)(p2.y)
  for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i)))
    cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))

  a(p1.x)(p1.y) = 0
  a(p2.x)(p2.y) = 0
  dfs(p1.x, p1.y)

  println(if (cnt > 1 && used(p2.x)(p2.y)) "YES" else "NO")
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

object main extends App with fastIO {

  case class Point(x: Int, y: Int)

  val dx = Vector(-1, 0, 1, 0)
  val dy = Vector(0, -1, 0, 1)

  def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }

  def dfs(x: Int, y: Int) {
    if (!ok(x, y)) return
    if (a(x)(y) == 1) return
    if (used(x)(y)) return

    used(x)(y) = true
    for (i <- 0 until 4)
      dfs(x + dx(i), y + dy(i))
  }

  var Array(n, m) = readLine split(" ") map(_.toInt)
  var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)
  var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))
  var used = Array.ofDim[Boolean](n, m)

  var cnt = a(p2.x)(p2.y) * 2
  for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i)))
    cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))

  a(p1.x)(p1.y) = 0
  a(p2.x)(p2.y) = 0
  dfs(p1.x, p1.y)

  println(if (cnt > 1 && used(p2.x)(p2.y)) "YES" else "NO")
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

object main extends App with fastIO {

  case class Point(x: Int, y: Int)

  val dx = Vector(-1, 0, 1, 0)
  val dy = Vector(0, -1, 0, 1)

  def ok(x: Int, y: Int) = { x >= 0 && y >= 0 && x < n && y < m }

  def dfs(x: Int, y: Int) {
    if (!ok(x, y)) return
    if (a(x)(y) == 1) return
    if (used(x)(y)) return

    used(x)(y) = true
    for (i <- 0 until 4)
      dfs(x + dx(i), y + dy(i))
  }

  var Array(n, m) = readLine split(" ") map(_.toInt)
  var a = Array.fill(n)(readLine.map(c => if (c == '.') 0 else 1).toArray)
  var (p1, p2) = (Point(nextInt - 1, nextInt - 1), Point(nextInt - 1, nextInt - 1))
  var used = Array.ofDim[Boolean](n, m)

  var cnt = a(p2.x)(p2.y) * 2
  for (i <- 0 until 4) if (ok(p2.x + dx(i), p2.y + dy(i)))
    cnt += 1 - a(p2.x + dx(i))(p2.y + dy(i))

  a(p2.x)(p2.y) = 0
  for (i <- 0 until 4) dfs(p1.x + dx(i), p1.y + dy(i))

  println(if (cnt > 1 && used(p2.x)(p2.y)) "YES" else "NO")
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}


You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.

The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.

Print the lexicographically maximum subsequence of string s.

NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA

import java.util.Scanner

object Main {

   def main(args: Array[String]): Unit = {
      val scanner = new Scanner (System.in)
		val str = scanner nextLine () reverse

		println (solve (str) reverse)
   }

	def solve(str: String): String = {
		var prev = 0
		def f(c: Char): Boolean = {
			if (prev <= c) {
				prev = c
				true
			} else false
		}
		str filter f
	}

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val letters = Array.ofDim[Int](26)
  line.foreach {
    i => letters(i - 'a') += 1
  }

  val res = line.foldLeft(List.empty[Char], letters.indices.reverse.find(i => letters(i) > 0)) {
    case ((answer, Some(i)), el) if el - 'a' != i =>
      letters(el - 'a') -= 1
      if (letters(el - 'a') == 0)
        (answer, letters.indices.reverse.find(i => letters(i) > 0))
      else
        (answer, Some(i))
    case ((answer, Some(i)), el) =>
      letters(el- 'a') -= 1
      if (letters(el - 'a') == 0)
        (el :: answer, letters.indices.reverse.find(i => letters(i) > 0))
      else
        (el :: answer, Some(i))
  }
  println(res._1.reverse.mkString)
}


Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!

The first line contains integer n (1 ≤ n ≤ 105), showing how many numbers the array has. The next line contains integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the array elements.

Print a single integer — the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  in.next()
  val data = in.next().split(' ').map(_.toInt)
  val min = data.min
  if (data.forall(_ % min == 0))
    println(min)
  else
    println(-1)
}


Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ 105; xi ≠ yi) — the color numbers for the home and away kits of the i-th team.

For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map{_ => in.next().split(" ").map(_.toInt)}
  val homes = data.map(_.head).groupBy(x => x).map(x => x._1 -> x._2.length)

  val res = data.map{
    el =>
      val guest = el.last
      val x = (n - 1) + homes.getOrElse(guest, 0)
      s"$x ${(n - 1) * 2 - x}"
  }

  println(res.mkString("\n"))
}

import java.util.Scanner
import java.io.PrintWriter

/**
 * Created by hama_du on 2014/05/18.
 */
object ProblemB extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val n = in.nextInt()
  val colors = (0 until n).map(_ => (in.nextInt(), in.nextInt()) )
  val homeColor = new Array[Int](100001)
  val awayColor = new Array[Int](100001)
  for (i <- 0 until n) {
    val h = colors(i)._1
    val a = colors(i)._2
    homeColor(h) += 1
    awayColor(a) += 1
  }
  colors.foreach(z => {
    val matches = (n - 1)
    val d = homeColor(z._2)
    out.println((matches+d) + " " + (matches-d))
  })
  out.flush()
}


Each day in Berland consists of $$$n$$$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is either $$$0$$$ or $$$1$$$), where $$$a_i=0$$$ if Polycarp works during the $$$i$$$-th hour of the day and $$$a_i=1$$$ if Polycarp rests during the $$$i$$$-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.

The first line contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of hours per day. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i=0$$$ if the $$$i$$$-th hour in a day is working and $$$a_i=1$$$ if the $$$i$$$-th hour is resting. It is guaranteed that $$$a_i=0$$$ for at least one $$$i$$$.

Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.

NoteIn the first example, the maximal rest starts in last hour and goes to the first hour of the next day.In the second example, Polycarp has maximal rest from the $$$4$$$-th to the $$$5$$$-th hour.In the third example, Polycarp has maximal rest from the $$$3$$$-rd to the $$$5$$$-th hour.In the fourth example, Polycarp has no rest at all.

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 A = na(N).map(_ == 1)
    debug(A)
    var a = 0
    var cnt = 0
    REP(N) { i =>
      if (A(i)) cnt += 1
      else cnt = 0
      a = max(a, cnt)
    }
    val b = A.takeWhile(identity).length + A.reverse.takeWhile(identity).length
    debug(s"a:$a b:$b")
    val ans = max(a, b)
    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 io.Source
import io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()

    val list = StdIn.readLine().split(" ").map(_.toLong).toList
    val list2 = list ::: list
    var max = 0
    var t = 0
    for (a <- list2) {
      if (a == 1) {
        t += 1
      } else {
        max = Math.max(t, max)
        t = 0
      }
    }
    max = Math.max(t, max)
    println(max)
    //println(longs.reverse.map(t => math.sqrt(t)).mkString("\n"))
  }
}
/*

* */

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()

    val list = StdIn.readLine().split(" ").map(_.toLong).toList
    val list2 = list ::: list
    var max = 0
    var t = 0
    for (a <- list2) {
      if (a == 1) {
        t += 1
      } else {
        max = Math.max(t, max)
        t = 0
      }
    }
    max = Math.max(t, max)
    println(max)
  }
}

object _1141B extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val input = io.read[Vector[Boolean]]
    val isResting = input ++ input

    var i, ans = 0
    while(i < isResting.length) {
      val j = i
      while (i < isResting.length && isResting(i)) i += 1
      ans = ans max (i - j)
      i += 1
    }

    io.write(ans)
  }
}
/****************************[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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  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 writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): 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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    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
      }
    }
  }
}


A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).

The first and only line consists of a string $$$S$$$ ($$$ 1 \le |S| \le 5\,000 $$$). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.

Print "YES" or "NO", according to the condition.

NoteConsider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.Consider third example: the number of 'c' is equal to the number of 'b'.

object Solution {
  def main(args: Array[String]) = {
    val s = readLine.toList

    val as = s.filter(_ == 'a').length
    val bs = s.filter(_ == 'b').length
    val cs = s.filter(_ == 'c').length
    val d = s.dropWhile(_ == 'a').dropWhile(_ == 'b').dropWhile(_ == 'c').isEmpty

    println(if (d && as > 0 && bs > 0 && cs > 0 && (as == cs || bs == cs)) "YES" else "NO")
  }
}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.io.Codec

object CheckString {

  def solve(scanner: Scanner) = {
    val word = scanner.nextLine()
    try {
      val splitResult = word.split("b+")
      val aWord = splitResult(0)
      val cWord = splitResult(1)
      val bWord = word.substring(aWord.size, word.size - cWord.size)

      val aSet = aWord.toSet
      val bSet = bWord.toSet
      val cSet = cWord.toSet
      if (aSet.contains('a') && bSet.contains('b') && cSet.contains('c')) {
        if (aSet.size != 1 || bSet.size != 1 || cSet.size != 1) {
          println("NO")
        } else {
          if (aWord.size == cWord.size || bWord.size == cWord.size) {
            println("YES")
          } else {
            println("NO")
          }
        }
      } else {
        println("NO")
      }
    } catch {
      case t: Throwable =>
        println("NO")
        System.err.println(t)
    }
  }

  def main(args: Array[String]): Unit = {
    if (args.length > 0) {
      val filenameIn = args(0)
      System.setIn(new FileInputStream(filenameIn))
    }
    val scanner = new Scanner(System.in)
    if (args.length > 1) {
      val filename = args(1)
      System.setOut(new PrintStream(filename))
    }
    val start = System.currentTimeMillis
    solve(scanner)
    scanner.close()
    System.err.println("\n" + (System.currentTimeMillis - start) + " ms")
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

object Solution {
  def main(args: Array[String]) = {
    val s = readLine.toList

    val as = s.filter(_ == 'a').length
    val bs = s.filter(_ == 'b').length
    val cs = s.filter(_ == 'c').length
    val d = s.takeWhile(_ == 'a').takeWhile(_ == 'b').takeWhile(_ == 'c').isEmpty

    println(if (d && as > 0 && bs > 0 && cs > 0 && (as == cs || bs == cs)) "YES" else "NO")
  }
}


Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: The try operator. It opens a new try-catch-block.  The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.Your task is: given a program in VPL, determine, what message will be displayed on the screen.

The first line contains a single integer: n (1 ≤ n ≤ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces. The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark. The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols. Length of any line in the input file does not exceed 50 symbols.

Print the message the screen will show after the given program is executed.

8
try
    try
        throw ( AE )
    catch ( BE, "BE in line 3")

    try
    catch(AE, "AE in line 5")
catch(AE,"AE somewhere")

8
try
    try
        throw ( AE )
    catch ( AE, "AE in line 3")

    try
    catch(BE, "BE in line 5")
catch(AE,"AE somewhere")

8
try
    try
        throw ( CE )
    catch ( BE, "BE in line 3")

    try
    catch(AE, "AE in line 5")
catch(AE,"AE somewhere")

AE somewhere
AE in line 3
Unhandled Exception

NoteIn the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")In the third sample there is no blocks that can be activated by an exception of type CE.

import java.util.Scanner
object TryCatch {

  val scanner = new Scanner(System.in)

  def main(args: Array[String]): Unit = {
    val x = scanner.nextInt()
    scanner.nextLine()
    var level = 0
    var raiseLevel = -1
    var raisedExc = "";
    var skipLevels = 0;
    for (i <- 0 until x) {
      var line = scanner.nextLine().trim();
      if (line.equals("try")){
        level += 1
        if (raiseLevel >= 0)
          skipLevels += 1
      } else if (line.startsWith("throw")){
        line = line.replace("throw","").trim()
        line = line.substring(1,line.length()-1).trim();
        raisedExc = line;
        raiseLevel = level;
      } else if (line.startsWith("catch")) {
        level -= 1
        line = line.replace("catch","").trim()
        line = line.substring(1,line.length()-1).trim();
        var params : Array[String] = line.split(",")

        if (level <= raiseLevel && params(0).trim().equals(raisedExc) && skipLevels == 0){
          var message = params(1).trim()
          message = message.substring(1,message.length()-1)
          println(message)
          return
        }
        if (skipLevels > 0) {
          skipLevels -= 1
        }
      }
    }
    println("Unhandled Exception")
  }

}

import java.util.Scanner
object TryCatch {

  val scanner = new Scanner(System.in)

  def main(args: Array[String]): Unit = {
    val x = scanner.nextInt()
    scanner.nextLine()
    var level = 0
    var raiseLevel = 0
    var raisedExc = "";
    for (i <- 0 until x) {
      var line = scanner.nextLine().trim();
      if (line.equals("try")){
        level += 1
      } else if (line.startsWith("throw")){
        line = line.replace("throw","").trim()
        line = line.substring(1,line.length()-1).trim();
        raisedExc = line;
        raiseLevel = level;
      } else if (line.startsWith("catch")) {
        line = line.replace("catch","").trim()
        line = line.substring(1,line.length()-1).trim();
        var params : Array[String] = line.split(",")

        if (level <= raiseLevel && params(0).trim().equals(raisedExc)){
          var message = params(1).trim()
          message = message.substring(1,message.length()-1)
          println(message)
          return
        }
      }
    }
    println("Unhandled Exception")
  }

}


Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer $$$k$$$ and positive integer $$$n$$$, let $$$k\bmod n$$$ denote the remainder when $$$k$$$ is divided by $$$n$$$. More formally, $$$r=k\bmod n$$$ is the smallest non-negative integer such that $$$k-r$$$ is divisible by $$$n$$$. It always holds that $$$0\le k\bmod n\le n-1$$$. For example, $$$100\bmod 12=4$$$ and $$$(-1337)\bmod 3=1$$$.Then the shuffling works as follows. There is an array of $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$. Then for each integer $$$k$$$, the guest in room $$$k$$$ is moved to room number $$$k+a_{k\bmod n}$$$.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case, every guest is shifted by $$$14$$$ rooms, so the assignment is still unique.In the second test case, even guests move to the right by $$$1$$$ room, and odd guests move to the left by $$$1$$$ room. We can show that the assignment is still unique.In the third test case, every fourth guest moves to the right by $$$1$$$ room, and the other guests move to the right by $$$5$$$ rooms. We can show that the assignment is still unique.In the fourth test case, guests $$$0$$$ and $$$1$$$ are both assigned to room $$$3$$$.In the fifth test case, guests $$$1$$$ and $$$2$$$ are both assigned to room $$$2$$$.

object C extends App {
  private def mod(k: Int, n: Int): Int =
    if (k > 0) k % n else (n - k % n) % n

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val bm = an.zipWithIndex.map { case (a, i) => (n + (a + i) % n) % n }.distinct

    if (n == bm.length) println("YES")
    else println("NO")
  }
}

object ProblemC extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  import scala.collection.mutable
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val n = in.nextInt()

  for (_ <- 1 to n) {
    val n = in.nextInt()
    val arr = new Array[Boolean](n)
    var result = true
    for (j <- 0 until n) {
      val ak = in.nextInt()

      var place = (n + (j + ak) % n) % n

      if (arr(place)) {
        result = false
      }

      arr(place) = true
    }

    if (result) {
      println("YES")
    } else {
      println("NO")
    }
  }

}

object Codeforces1344a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach { _ =>
      if (test()) {
        writer.println("YES")
      } else {
        writer.println("NO")
      }
    }
  }

  def test()(implicit reader: BufferedReader): Boolean = {
    val n: Int = rl_int
    val a: Array[Int] = rll_int
    a.zipWithIndex.map(x => Math.floorMod(x._1 + x._2, n)).distinct.length == n
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

object C extends App {
  private def mod(k: Int, n: Int): Int =
    if (k > 0) k % n else (n - k % n) % n

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val bm = an.zipWithIndex.map { case (a, i) => mod(a + i, n) }.distinct

    if (n == bm.length) println("YES")
    else println("NO")
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val bn = an.zipWithIndex.map { case (a, i) => (a + i % n) % n }.distinct

    if (an.length == bn.length) println("YES")
    else println("NO")
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val bn = an.zipWithIndex.map { case (a, i) => (a + i) % n }.distinct

    if (an.length == bn.length) println("YES")
    else println("NO")
  }
}