Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.It is known that in a match between two players, the one whose skill is greater will win. The skill of the $$$i$$$-th player is equal to $$$s_i$$$ and all skill levels are pairwise different (i. e. there are no two identical values in the array $$$s$$$).The tournament is called fair if the two players with the highest skills meet in the finals.Determine whether the given tournament is fair.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. A single line of test case contains four integers $$$s_1, s_2, s_3, s_4$$$ ($$$1 \le s_i \le 100$$$) — skill of the players. It is guaranteed that all the numbers in the array are different.

For each testcase, output YES if the tournament is fair, or NO otherwise.

NoteConsider the example:  in the first test case, players $$$2$$$ and $$$3$$$ with skills $$$7$$$ and $$$9$$$ advance to the finals;  in the second test case, players $$$2$$$ and $$$4$$$ with skills $$$5$$$ and $$$9$$$ advance to the finals. The player with skill $$$6$$$ does not advance, but the player with skill $$$5$$$ advances to the finals, so the tournament is not fair;  in the third test case, players $$$1$$$ and $$$3$$$ with skills $$$5$$$ and $$$8$$$ advance to the finals;  in the fourth test case, players $$$1$$$ and $$$3$$$ with skills $$$6$$$ and $$$3$$$ advance to the finals. The player with skill $$$5$$$ does not advance, but the player with skill $$$3$$$ advances to the finals, so the tournament is not fair.

import scala.io.StdIn._

object A extends App {
  for (_ <- 0 until readInt) {
    val s @ Array(s1, s2, s3, s4) = readLine.split(" ").map(_.toInt)
    if (s.sortBy(-_).take(2).toSet == Set(s1.max(s2), s3.max(s4)))
      println("YES")
    else
      println("NO")
  }
}

import scala.io.StdIn._
import scala.collection.immutable._
import scala.annotation.tailrec
object test{
    def main(args: Array[String]): Unit = {
        var t = readInt

        while(t > 0) {
            val m = readLine.split(" ").map(_.toInt).toList
            if(m(0).min(m(1)) > m(2).max(m(3)) || m(2).min(m(3)) > m(0).max(m(1)))
                println("NO")
            else
                println("YES")

            t -= 1
        }
    }
}


Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $$$i$$$-th page contains some mystery that will be explained on page $$$a_i$$$ ($$$a_i \ge i$$$).Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $$$i$$$ such that Ivan already has read it, but hasn't read page $$$a_i$$$). After that, he closes the book and continues to read it on the following day from the next page.How many days will it take to read the whole book?

The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^4$$$) — the number of pages in the book. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$i \le a_i \le n$$$), where $$$a_i$$$ is the number of page which contains the explanation of the mystery on page $$$i$$$.

Print one integer — the number of days it will take to read the whole book.

NoteExplanation of the example test:During the first day Ivan will read only the first page. During the second day Ivan will read pages number $$$2$$$ and $$$3$$$. During the third day — pages $$$4$$$-$$$8$$$. During the fourth (and the last) day Ivan will read remaining page number $$$9$$$.

object Foo extends App {
  val Array(n) = readints
  val a = readints

  var r, days = 0
  for (i <- 0 until n) {
    if (a(i) > r)
      r = a(i)
    if (r == i + 1)
      days += 1
  }

  println(days)

  import scala.io.StdIn.readLine
  def readints() = readLine.split(" ").map(_.toInt)
}

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 java.util.Arrays

  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, -1)
    var ans = 0
    var p = 0
    var mys = 0
    while(p < N) {
      mys = A(p)
      while(mys > p) {
        p += 1
        mys = max(mys, A(p))
      }
      debug(s"p:$p mys:$mys")
      ans += 1
      p += 1
    }
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.collection.mutable

object A extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)
  val xs = Array.fill(n)(false)

  var i = 0
  var day = 0

  while (i < n) {
    day += 1
    val pending = mutable.Set.empty[Int]
    do {
      pending += (as(i) - 1)
      pending -= i
      i += 1
    } while (pending.nonEmpty)
  }

  println(day)

  Console.flush
}


You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters and an integer number $$$k$$$.Let's define a substring of some string $$$s$$$ with indices from $$$l$$$ to $$$r$$$ as $$$s[l \dots r]$$$.Your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ positions $$$i$$$ such that $$$s[i \dots i + n - 1] = t$$$. In other words, your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$.It is guaranteed that the answer is always unique.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 50$$$) — the length of the string $$$t$$$ and the number of substrings. The second line of the input contains the string $$$t$$$ consisting of exactly $$$n$$$ lowercase Latin letters.

Print such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$. It is guaranteed that the answer is always unique.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, K = sc.nextInt()
    val s = sc.next()
    var t = ""

    def find: Option[Int] = {
      rep_r(min(t.length, s.length)) { j =>
        if (s.substring(0, j) == t.substring(t.length - j)) return Some(j)
      }
      None
    }

    rep(K) { _ =>
      find match {
        case Some(j) => t += s.substring(j)
        case None => t += s
      }
    }

    out.println(t)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  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)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  var sameCount = (0 to n/2).filter(x => t.take(x) == t.takeRight(x)).last
  var s = t.dropRight(sameCount) * k + t.takeRight(sameCount)
  val lastStart = s.sliding(n).zipWithIndex.filter(_._1 == t).toList(k-1)._2
  s = s.take(lastStart + n)
  println(s)
}

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

object A extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val k = in.nextInt
    val s = in.next

    var maxLen = 0

    for (i <- 1 until n) {
      if (s.take(i) == s.takeRight(i)) {
        maxLen = i
      }
    }

    val suffix = s.drop(maxLen)
    print(s)
    for (_ <- 1 until k) {
      print(suffix)
    }
    println()
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

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

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

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

object A extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val k = in.nextInt
    val s = in.next
    val t = (0 until n).find { i =>
      s.substring(0, n - i - 1) == s.substring(i + 1)
    }.get
    print(s)
    (1 until k).foreach { _ =>
      print(s.substring(n - t - 1))
    }
    println
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

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

}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  val sameCount = t.take(n/2).zipWithIndex.takeWhile(x => t.charAt(n-1-x._2) == x._1).length
  println(t.dropRight(sameCount) * k + t.takeRight(sameCount))
}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  var sameCount = (0 to n/2).filter(x => t.take(x) == t.takeRight(x)).last

  if (sameCount == n/2 && t.forall(_ == t.head)) {
    // All chars the same
    sameCount = n - 1
  }
  println(t.dropRight(sameCount) * k + t.takeRight(sameCount))
}

object CF506A extends App {
  import scala.io.StdIn
  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val t = StdIn.readLine

  var sameCount = t.take(n/2).zipWithIndex.takeWhile(x => t.charAt(n-1-x._2) == x._1).length
  if (sameCount == n/2 && n > 1 && t.charAt(n/2) == t.charAt(n/2-1)) {
    // All chars the same
    sameCount = n - 1
  }
  println(t.dropRight(sameCount) * k + t.takeRight(sameCount))
}


You had $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle. For each pair of neighboring numbers ($$$a_1$$$ and $$$a_2$$$, $$$a_2$$$ and $$$a_3$$$, ..., $$$a_{n - 1}$$$ and $$$a_n$$$, and $$$a_n$$$ and $$$a_1$$$), you wrote down: are the numbers in the pair equal or not.Unfortunately, you've lost a piece of paper with the array $$$a$$$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $$$a$$$ which is consistent with information you have about equality or non-equality of corresponding pairs?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains a non-empty string $$$s$$$ consisting of characters E and/or N. The length of $$$s$$$ is equal to the size of array $$$n$$$ and $$$2 \le n \le 50$$$. For each $$$i$$$ from $$$1$$$ to $$$n$$$:    if $$$s_i =$$$ E then $$$a_i$$$ is equal to $$$a_{i + 1}$$$ ($$$a_n = a_1$$$ for $$$i = n$$$);  if $$$s_i =$$$ N then $$$a_i$$$ is not equal to $$$a_{i + 1}$$$ ($$$a_n \neq a_1$$$ for $$$i = n$$$).

For each test case, print YES if it's possible to choose array $$$a$$$ that are consistent with information from $$$s$$$ you know. Otherwise, print NO. It can be proved, that if there exists some array $$$a$$$, then there exists an array $$$a$$$ of positive integers with values less or equal to $$$10^9$$$.

NoteIn the first test case, you can choose, for example, $$$a_1 = a_2 = a_3 = 5$$$.In the second test case, there is no array $$$a$$$, since, according to $$$s_1$$$, $$$a_1$$$ is equal to $$$a_2$$$, but, according to $$$s_2$$$, $$$a_2$$$ is not equal to $$$a_1$$$.In the third test case, you can, for example, choose array $$$a = [20, 20, 4, 50, 50, 50, 20]$$$.In the fourth test case, you can, for example, choose $$$a = [1, 3, 3, 7]$$$.

import scala.io.StdIn._

object Main extends App {
    val nums = readInt()
    for (i <- 0 until nums) {
        val row  = readLine()
        if (row.count(_=='N') == 1) {
            println("NO")
        }
        else {
            println("YES")
        }
    }
}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        var s = readString()
        var cnt = 0
        for (c <- s) {
            if (c == 'N')
                cnt += 1
        }
        if (cnt == 1) {
            writer.println("NO")
        } else {
            writer.println("YES")
        }

        def check(kk: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(st))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(st, mid)
            else
                return bs(mid, en)
        }
    }
    writer.flush()
}


Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.

The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board.  Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.

Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n = r.read[Int]
    val b1, b2, b3, b4 = r.read[List[String]](n).mkString
    val n2 = n * n
    val sb = ("10" * n2).take(n2)
    val sw = ("01" * n2).take(n2)

    def m(s1: String, s2: String) =
      s1.zip(s2).foldLeft(0) {
        case (acc, (c, d)) => if (c == d) acc else acc + 1
      }

    val mb1 = m(b1, sb)
    val mb2 = m(b2, sb)
    val mb3 = m(b3, sb)
    val mb4 = m(b4, sb)

    val mw1 = m(b1, sw)
    val mw2 = m(b2, sw)
    val mw3 = m(b3, sw)
    val mw4 = m(b4, sw)

    println(List(mb1 + mb2 + mw3 + mw4,
                 mb1 + mw2 + mb3 + mw4,
                 mb1 + mw2 + mw3 + mb4,
                 mw1 + mb2 + mb3 + mw4,
                 mw1 + mb2 + mw3 + mb4,
                 mw1 + mw2 + mb3 + mb4).min)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object A {
    def main(args: Array[String]) {
        var n = scala.io.StdIn.readInt();
        var bs = Array.ofDim[Int](4, n, n);
        //println(bs(0)(1).getClass.toString())
        for(b <- 0 until 4){
            for(i <- 0 until n){
                bs(b)(i) = scala.io.StdIn.readLine().split("").map( _.toInt );
            }
            scala.io.StdIn.readLine();
        }

        val ps = List(0, 1, 2, 3).permutations
        var ans = n * n * 4;
        for(p <- ps){
            val t = cost(bs, p);
            ans = math.min(ans, t);
        }

        println(ans);
    }

    def cost(bs: Array[Array[Array[Int]]], p: List[Int]): Int = {
        //println(bs.size)
        //println(p)
        var same = 0;
        var diff = 0;
        val n = bs(0).size;
        for(b <- 0 until 4){
            for(i <- 0 until n){
                for(j <- 0 until n){
                    if(bs(p(b))(i)(j) == (i + j + (b % 2)) % 2) same += 1;
                    else diff += 1;
                }
            }
        }
        return math.min(same, diff);
    }
}


Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≤ i ≤ n) has a best friend p[i] (1 ≤ p[i] ≤ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm:   on the first day of revising each student studies his own Mathematical Analysis notes,  in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≤ i ≤ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising:  a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising;  b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≤ ai ≤ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≤ bi ≤ n).

Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≤ p[i] ≤ n). It is guaranteed that the solution exists and that it is unique.

import java.util.InputMismatchException
import java.util.Scanner
import java.io.InputStream
import java.io.PrintWriter

/**
 * Created with IntelliJ IDEA.
 */
object ProblemF extends App {
  val in = new InputReader(System.in)
  var out = new PrintWriter(System.out)
  val n = in.nextInt
  val data = new Array[Int](n+1)
  (1 to n).foreach(f => {
    data(in.nextInt) = f
  })
  (1 to n).foreach(x => {
    if (x > 1) {
      out.print(' ')
    }
    out.print(data(in.nextInt()))
  })
  out.println()
  out.flush()

  class InputReader(stream: InputStream) {
    val buf = new Array[Byte](1024)
    var curChar = 0
    var numChars = 0

    def next(): Int = {
      if (numChars == -1)
        throw new InputMismatchException();
      if (curChar >= numChars) {
        curChar = 0;
        numChars = stream.read(buf);
        if (numChars <= 0) {
          -1;
        }
      }
      val res = buf(curChar)
      curChar += 1
      res
    }

    def nextLong(): Long = {
      var c = next()
      while (isSpaceChar(c)) {
        c = next()
      }
      var sgn = 1
      if (c == '-') {
        sgn = -1
        c = next()
      }
      var res = 0L
      do {
        if (c < '0' || c > '9')
          throw new InputMismatchException()
        res *= 10
        res += c - '0'
        c = next()
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt(): Int = {
      nextLong.toInt
    }

    def isSpaceChar(c: Int) = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
  }
}


You are given a graph with $$$3 \cdot n$$$ vertices and $$$m$$$ edges. You are to find a matching of $$$n$$$ edges, or an independent set of $$$n$$$ vertices.A set of edges is called a matching if no two edges share an endpoint.A set of vertices is called an independent set if no two vertices are connected with an edge.

The first line contains a single integer $$$T \ge 1$$$ — the number of graphs you need to process. The description of $$$T$$$ graphs follows. The first line of description of a single graph contains two integers $$$n$$$ and $$$m$$$, where $$$3 \cdot n$$$ is the number of vertices, and $$$m$$$ is the number of edges in the graph ($$$1 \leq n \leq 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$). Each of the next $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \leq v_i, u_i \leq 3 \cdot n$$$), meaning that there is an edge between vertices $$$v_i$$$ and $$$u_i$$$. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all $$$n$$$ over all graphs in a single test does not exceed $$$10^{5}$$$, and the sum of all $$$m$$$ over all graphs in a single test does not exceed $$$5 \cdot 10^{5}$$$.

Print your answer for each of the $$$T$$$ graphs. Output your answer for a single graph in the following format. If you found a matching of size $$$n$$$, on the first line print "Matching" (without quotes), and on the second line print $$$n$$$ integers — the indices of the edges in the matching. The edges are numbered from $$$1$$$ to $$$m$$$ in the input order. If you found an independent set of size $$$n$$$, on the first line print "IndSet" (without quotes), and on the second line print $$$n$$$ integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size $$$n$$$, and an independent set of size $$$n$$$, then you should print exactly one of such matchings or exactly one of such independent sets.

Matching
2
IndSet
1
IndSet
2 4
Matching
1 15

NoteThe first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly $$$n$$$.The fourth graph does not have an independent set of size 2, but there is a matching of size 2.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  class Flag(n: Int) {
    val b = Array.ofDim[Boolean](n)
    val ix = Array.fill[Int](n)(-1)

    def is(i: Int, g: Int): Boolean = {
      if (ix(i) != g) {
        ix(i) = g
        b(i) = false
      }
      b(i)
    }

    def set(i: Int, g: Int, flg: Boolean): Unit = {
      b(i) = flg
      ix(i) = g
    }
  }

  def solve(): Unit = {
    val fg = new Flag(3e5.toInt)
    REP(ni()) { t =>
      val N, M = ni()

      val mt = ArrayBuffer[Int]()
      REP(M) { i =>
        val u, v = ni() - 1
        if (!fg.is(u, t) && !fg.is(v, t)) {
          mt += i
          fg.set(u, t, flg = true)
          fg.set(v, t, flg = true)
        }
      }

      debug(mt.mkString(" "))
      DEBUG {
        debug(map(3 * N)(fg.is(_, t)))
      }

      if (mt.length >= N) {
        out.println("Matching")
        REP(N) { i =>
          out.print(s"${mt(i)+1} ")
        }
        out.println()
      } else {
        out.println("IndSet")
        var i = 0
        var cnt = 0
        while(cnt < N) {
          if (!fg.is(i, t)) {
            out.print(s"${i+1} ")
            cnt += 1
          }
          i += 1
        }
        out.println()
      }
    }
  }
}


There is an array $$$a$$$ with $$$n-1$$$ integers. Let $$$x$$$ be the bitwise XOR of all elements of the array. The number $$$x$$$ is added to the end of the array $$$a$$$ (now it has length $$$n$$$), and then the elements are shuffled.You are given the newly formed array $$$a$$$. What is $$$x$$$? If there are multiple possible values of $$$x$$$, you can output any of them.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of integers in the resulting array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 127$$$) — the elements of the newly formed array $$$a$$$. Additional constraint on the input: the array $$$a$$$ is made by the process described in the statement; that is, some value of $$$x$$$ exists.

For each test case, output a single integer — the value of $$$x$$$, as described in the statement. If there are multiple possible values of $$$x$$$, output any of them.

NoteIn the first test case, one possible array $$$a$$$ is $$$a=[2, 5, 4]$$$. Then $$$x = 2 \oplus 5 \oplus 4 = 3$$$ ($$$\oplus$$$ denotes the bitwise XOR), so the new array is $$$[2, 5, 4, 3]$$$. Afterwards, the array is shuffled to form $$$[4, 3, 2, 5]$$$.In the second test case, one possible array $$$a$$$ is $$$a=[1, 10, 6, 10]$$$. Then $$$x = 1 \oplus 10 \oplus 6 \oplus 10 = 7$$$, so the new array is $$$[1, 10, 6, 10, 7]$$$. Afterwards, the array is shuffled to form $$$[6, 1, 10, 7, 10]$$$.In the third test case, all elements of the array are equal to $$$6$$$, so $$$x=6$$$.In the fourth test case, one possible array $$$a$$$ is $$$a=[100, 100]$$$. Then $$$x = 100 \oplus 100 = 0$$$, so the new array is $$$[100, 100, 0]$$$. Afterwards, the array is shuffled to form $$$[100, 100, 0]$$$. (Note that after the shuffle, the array can remain the same.)

import scala.collection.mutable

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    var tokinizer = new StringTokenizer(input.readLine())
    val n = tokinizer.nextToken().toInt
    for (i <- 1 to n) {
      tokinizer = new StringTokenizer(input.readLine())
      val a = tokinizer.nextToken()
      tokinizer = new StringTokenizer(input.readLine())
      val b = tokinizer.nextToken()
      output.println(b)
    }
  }

}

import scala.collection.mutable

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    var tokinizer = new StringTokenizer(input.readLine())
    val n = tokinizer.nextToken().toInt
    for (i <- 1 to n) {
      tokinizer = new StringTokenizer(input.readLine())
      val a = tokinizer.nextToken()
      output.println(a)
    }
  }

}


A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?

The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.  The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.

Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print  - 1.

object A560 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n).toSet
    if(input.contains(1)) {
      println("-1")
    } else {
      println("1")
    }
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/560/A"/>
 *
 * @author pvasilyev
 * @since 10 Apr 2016
 */
object Problem148 extends App {

  private val n: Int = scala.io.StdIn.readInt()
  private var b: Boolean  = false
  private val line: String = scala.io.StdIn.readLine()
  private val a: Array[Int] = line.split(" ").map(_.toInt)
  for (i <- 0 until n) {
    val ai: Int = a(i)
    if (ai == 1) {
      b = true
    }
  }

  if (b) {
    println(-1)
  } else {
    println(1)
  }

}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    readInt()
    val b = readLine().split(" ")
    if (b.contains("1")) println(-1)
    else print(1)
  }
}

import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _560A extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val notes = List.fill(n)(nextInt)
  if (notes contains 1) -1 else 1
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final def isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None
  final def counter[A] = collection.mutable.Map.empty[A, Int] withDefaultValue 0
}

object A560 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n).toSet
    if(input.contains(1)) {
      if(input.contains(2)) {
        println("-1")
      } else {
        println("2")
      }
    } else {
      println("1")
    }
  }
}


A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $$$0$$$ are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars:  The leftmost figure is a star of size $$$1$$$, the middle figure is a star of size $$$2$$$ and the rightmost figure is a star of size $$$3$$$. You are given a rectangular grid of size $$$n \times m$$$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $$$1$$$ to $$$n$$$, columns are numbered from $$$1$$$ to $$$m$$$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $$$n \cdot m$$$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $$$n \cdot m$$$ stars.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$3 \le n, m \le 100$$$) — the sizes of the given grid. The next $$$n$$$ lines contains $$$m$$$ characters each, the $$$i$$$-th line describes the $$$i$$$-th row of the grid. It is guaranteed that grid consists of characters '*' and '.' only.

If it is impossible to draw the given grid using stars only, print "-1". Otherwise in the first line print one integer $$$k$$$ ($$$0 \le k \le n \cdot m$$$) — the number of stars needed to draw the given grid. The next $$$k$$$ lines should contain three integers each — $$$x_j$$$, $$$y_j$$$ and $$$s_j$$$, where $$$x_j$$$ is the row index of the central star character, $$$y_j$$$ is the column index of the central star character and $$$s_j$$$ is the size of the star. Each star should be completely inside the grid.

NoteIn the first example the output 23 4 13 5 2is also correct.

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 R, C = ni()
    val g = nm_c(R, C)
    val rowL, rowR = Array.ofDim[Int](R, C + 2) // 1-indexed
    val colT, colB = Array.ofDim[Int](C, R + 2)
    REP(R) { r =>
      REP(C) { c =>
        if (g(r)(c) == '*') rowL(r)(c + 1) = rowL(r)(c) + 1
      }
      REP_r(C) { c =>
        if (g(r)(c) == '*') rowR(r)(c + 1) = rowR(r)(c + 2) + 1
      }
    }

    REP(C) { c =>
      REP(R) { r =>
        if (g(r)(c) == '*') colT(c)(r + 1) = colT(c)(r) + 1
      }
      REP_r(R) { r =>
        if (g(r)(c) == '*') colB(c)(r + 1) = colB(c)(r + 2) + 1
      }
    }

    var cntStars = 0
    val stars = Array.ofDim[Int](R, C) // 中心も含めた長さ
    REP(R) { r =>
      REP(C) { c =>
        if (g(r)(c) == '*') {
          val len = min(min(rowL(r)(c + 1), rowR(r)(c + 1)), min(colT(c)(r + 1), colB(c)(r + 1)))
          if (len > 1) {
            stars(r)(c) = len
            cntStars += 1
          }
        }
      }
    }

    val paint = Array.fill[Char](R, C)('.')

    type StepFn = (Int, Int) => Unit
    def paintIt(acc: StepFn => Unit) = {
      var cnt = 0
      def step(r: Int, c: Int) = {
        cnt = max(stars(r)(c), cnt - 1)
        if (cnt > 0) paint(r)(c) = '*'
      }

      acc(step)
    }

    REP(R) { r =>
      paintIt(step => REP(C)(c => step(r, c)))
      paintIt(step => REP_r(C)(c => step(r, c)))
    }
    REP(C) { c =>
      paintIt(step => REP(R)(r => step(r, c)))
      paintIt(step => REP_r(R)(r => step(r, c)))
    }

    var ok = true
    REP(R) { r =>
      REP(C) { c =>
        ok &&= g(r)(c) == paint(r)(c)
      }
    }

    if (!ok) out.println(-1)
    else {
      out.println(cntStars)
      REP(R) { r =>
        REP(C) { c =>
          if (stars(r)(c) > 0) out.println(s"${r+1} ${c+1} ${stars(r)(c)-1}")
        }
      }
    }
  }

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

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

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

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

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

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

import scala.collection.mutable.ListBuffer

object CF501E extends App {

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

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve = {
    val n = in.nextInt
    val m = in.nextInt
    val grid = new Array[Array[Boolean]](n).map(_ => in.next.toCharArray.map(_ == '*'))

    var stars = new ListBuffer[(Int,Int,Int)]()

    for (x <- 1 until n-1;
         y <- 1 until m-1) {
      if (grid(x)(y)) {
        val maxSize = findMaxSize(x, y, 0)
        if (maxSize > 0)
          stars += ((x, y, maxSize))
      }
    }

    def findMaxSize(x: Int, y: Int, currentMax: Int): Int = {
      try {
        if (grid(x)(y-currentMax-1) && grid(x)(y+currentMax+1) && grid(x-currentMax-1)(y) && grid(x+currentMax+1)(y)) {
          return findMaxSize(x, y, currentMax + 1)
        } else {
          return currentMax
        }
      } catch {
        case _: ArrayIndexOutOfBoundsException => return currentMax
      }
    }

    val newGrid = Array.ofDim[Boolean](n, m)
    for (star <- stars) {
      val (x, y, size) = star
      newGrid(x)(y) = true
      for (i <- 1 to size) {
        newGrid(x+i)(y) = true
        newGrid(x-i)(y) = true
        newGrid(x)(y+i) = true
        newGrid(x)(y-i) = true
      }
    }

    if (grid.deep == newGrid.deep) {
      out.println(stars.length)
      out.println(stars.map(s => (s._1+1) + " " + (s._2+1) + " " + s._3).mkString("\n"))
    } else {
      out.println("-1")
    }
  }

  solve
  out.flush
  out.close
}


DZY has a sequence a, consisting of n integers.We'll call a sequence ai, ai + 1, ..., aj (1 ≤ i ≤ j ≤ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.You only need to output the length of the subsegment you find.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In a single line print the answer to the problem — the maximum length of the required subsegment.

NoteYou can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 4.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val res = data.indices.tail.foldLeft((0, List.empty[(Int, Int)])) {
    case (acc@(first, list), i) if data(i) > data(i - 1) => acc
    case ((first, list), i) => (i, (first, i - 1) :: list)
  }
  val ans: Array[(Int, Int)] = ((res._1, n - 1) :: res._2).reverse.toArray
  if (ans.length == 1)
    println(n)
  else {
    val max = ans.map(i => i._2 - i._1).max + 2
    val t = ans.indices.foldLeft(max) {
      case (m, i) if i == ans.length - 1 => m
      case (m, i) =>
        val (s1, e1) = ans(i)
        val (s2, e2) = ans(i + 1)
        if (s1 == e1 || s2 == e2)
          if (i == ans.length - 2) m
          else {
            val (s3, e3) = ans(i + 2)
            if (data(e1) + 1 < data(s3))
              Math.max(m, s3 - e1)
            else
              m
          }
        else if (data(e1 - 1) + 1 < data(s2) || data(e1) + 1 < data(s2 + 1)) {
//          println("here")
          val t = Math.max(m, e2 - s1 + 1)
//          println(t)
          t
        }
        else
          m
    }
    println(t)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val a = in.next().split(' ').map(_.toInt)
  val l = Array.fill(n)(1)
  val r = Array.fill(n)(1)

  (1 until n).foreach { i =>
    if (a(i - 1) < a(i)) l(i) += l(i - 1)
  }
  (n - 2 until 0 by -1).foreach { i =>
    if (a(i + 1) > a(i)) r(i) += r(i + 1)
  }
  val m = l.max
  val s = m + (if (m < n) 1 else 0)
  println((1 until n - 1).foldLeft(s) {
    case (acc, i) if a(i - 1) + 1 < a(i + 1) => Math.max(acc, l(i - 1) + r(i + 1) + 1)
    case (acc, _) => acc
  })
}

object tmp extends App {

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

  class MyScanner(br: BufferedReader) {
    var st = new StringTokenizer("")

    def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))

    private def next() = {

      while (!st.hasMoreElements) {
        st = new StringTokenizer(br.readLine())
      }
      st.nextToken()
    }

    def nextInt() = java.lang.Integer.parseInt(next())

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

    def nextLine() = br.readLine()
  }

  val sc = new MyScanner(System.in)
  val n = sc.nextInt()
  var prevEnd = -1
  var prevLen = -1
  var prev = 0
  var curLen = 0
  var ans = 0
  val a = Array.fill(n)(0)
  for (i <- 0 until n) {
    a(i) = sc.nextInt()
    if (prev < a(i)) {
      curLen += 1
      prev = a(i)
    } else {
      if (prevEnd != -1) {
        ans = math.max(ans, prevLen + 1)
        ans = math.max(ans, curLen + 1)
        val left = a(prevEnd + 1) - 1
        val leftCan = prevLen == 1 || left > a(prevEnd - 1)
        val right = a(prevEnd) + 1
        val rightCan = curLen == 1 || right < a(prevEnd + 2)
        if (leftCan || rightCan) {
          ans = math.max(ans, prevLen + curLen)
        }
      }
      prevEnd = i - 1
      prevLen = curLen
      prev = a(i)
      curLen = 1

    }
  }
  if (prevEnd == -1) {
    ans = curLen
  } else {
    ans = math.max(ans, prevLen + 1)
    ans = math.max(ans, curLen + 1)
    val left = a(prevEnd + 1) - 1
    val leftCan = prevLen == 1 || left > a(prevEnd - 1)
    val right = a(prevEnd) + 1
    val rightCan = curLen == 1 || right < a(prevEnd + 2)
    if (leftCan || rightCan) {
      ans = math.max(ans, prevLen + curLen)
    }
  }
  println(ans)
}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object A446 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var max = 1
    val l: Array[Int] = Array.ofDim[Int](n)
    l(0) = 1
    for (i <- 1 until n) {
      // update l:
      if (a(i) > a(i - 1)) {
        l(i) = l(i - 1) + 1
      } else {
        l(i) = 1
      }
      max = math.max(max, l(i-1)+1)
    }
    val r: Array[Int] = Array.ofDim[Int](n)
    r(n - 1) = 1
    for (i <- (n - 2).to(0, -1)) {
      if (a(i) < a(i + 1)) {
        r(i) = r(i + 1) + 1
      } else {
        r(i) = 1
      }
      max = math.max(max, r(i+1)+1)
    }
    for (i <- 1 until n-1) {
      if (a(i - 1) + 1 < a(i + 1)) {
        max = math.max(max, l(i - 1) + 1 + r(i + 1))
      }
    }
    println(max)
  }

  solve()

}

object Main {
  def main (args: Array[String]) {
    val n=io.StdIn.readLine().toInt
    val v=io.StdIn.readLine().split(" ").map(_.toInt)
    val s=Array.fill(n)(1)
    val t=Array.fill(n)(1)
    (1 until n).foreach(i=>if (v(i-1)<v(i)) s(i)+=s(i-1))
    (n-2 until -1 by -1).foreach(i=>if (v(i)<v(i+1)) t(i)+=t(i+1))

    var res=math.min(2,n)
    (0 until n).foreach(i=> {
      var cur = 1
      if (i > 0 && i  < n-1 && v(i - 1) + 1 >= v(i + 1))
        cur += math.max(s(i - 1), t(i + 1))
      else{
        if (i>0) cur+=s(i-1)
        if (i+1<n) cur+=t(i+1)
      }
      res =math.max(res,cur)
    })
    println(res)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val res = data.indices.tail.foldLeft((0, List.empty[(Int, Int)])) {
    case (acc@(first, list), i) if data(i) > data(i - 1) => acc
    case ((first, list), i) => (i, (first, i - 1) :: list)
  }
  val ans: Array[(Int, Int)] = ((res._1, n - 1) :: res._2).reverse.toArray
  if (ans.length == 1)
    println(n)
  else {
    val max = ans.map(i => i._2 - i._1).max + 2
    val t = ans.indices.foldLeft(max) {
      case (m, i) if i == ans.length - 1 => m
      case (m, i) =>
        val (s1, e1) = ans(i)
        val (s2, e2) = ans(i + 1)
        if (s1 == e1 || s2 == e2)
          if (i == ans.length - 2) m
          else {
            val (s3, e3) = ans(i + 2)
            if (data(e1) + 1 < data(s3))
              Math.max(m, s3 - e1 + 1)
            else
              m
          }
        else if (data(e1 - 1) + 1 < data(s2) || data(e1) + 1 < data(s2 + 1)) {
//          println("here")
          val t = Math.max(m, e2 - s1 + 1)
//          println(t)
          t
        }
        else
          m
    }
    println(t)
  }
}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object A446 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val r: Array[Int] = Array.ofDim[Int](n)
    r(0) = 1
    val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)
    s(0) = (1, a(0)-1)
    var max = 1
    for (i <- 1 until n) {
      // update r:
      if (a(i) > a(i - 1)) {
        r(i) = r(i - 1) + 1
      } else {
        r(i) = 1
      }
      // update s:
      if (a(i) > s(i - 1)._2) {
        s(i) = (s(i - 1)._1 + 1, a(i))
      } else {
        s(i) = (r(i - 1) + 1, a(i-1) + 1)
      }
      max = math.max(max, math.max(r(i), s(i)._1))
    }

    println(max)
  }

  solve()

}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object A446 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    var max = 1
    val l: Array[Int] = Array.ofDim[Int](n)
    l(0) = 1
    for (i <- 1 until n) {
      // update l:
      if (a(i) > a(i - 1)) {
        l(i) = l(i - 1) + 1
      } else {
        l(i) = 1
      }
      max = math.max(max, l(i))
    }
    val r: Array[Int] = Array.ofDim[Int](n)
    r(n - 1) = 1
    for (i <- (n - 2).to(0, -1)) {
      if (a(i) < a(i + 1)) {
        r(i) = r(i + 1) + 1
      } else {
        r(i) = 1
      }
      max = math.max(max, r(i))
    }
    max += 1
    for (i <- 1 until n-1) {
      if (a(i - 1) + 1 < a(i + 1)) {
        max = math.max(max, l(i - 1) + 1 + r(i + 1))
      }
    }
    println(max)
  }

  solve()

}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object A446 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val r: Array[Int] = Array.ofDim[Int](n)
    r(0) = 1
    val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)
    s(0) = (1, -1)
    var max = 1
    for (i <- 1 until n) {
      // update r:
      if (a(i) > a(i - 1)) {
        r(i) = r(i - 1) + 1
      } else {
        r(i) = 1
      }
      // update s:
      if (a(i) > s(i - 1)._2) {
        s(i) = (s(i - 1)._1 + 1, a(i))
      } else {
        s(i) = (r(i - 1) + 1, a(i-1) + 1)
      }
      max = math.max(max, math.max(r(i), s(i)._1))
    }

    println(max)
  }

  solve()

}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object A446 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val r: Array[Int] = Array.ofDim[Int](n)
    r(0) = 1
    val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)
    s(0) = (1, -1)
    var max = 1
    for (i <- 1 until n) {
      // update r:
      if (a(i) > a(i - 1)) {
        r(i) = r(i - 1) + 1
      } else {
        r(i) = 1
      }
      // update s:
      if (a(i) > s(i - 1)._2) {
        s(i) = (s(i - 1)._1 + 1, a(i))
      } else if (a(i-1) > a(i) && (i < 2 || a(i-2) < a(i)-1)) {
        // change previous:
        s(i) = (r(i - 1) + 1, a(i))
      } else {
        // change current
        s(i) = (r(i - 1) + 1, a(i-1) + 1)
      }
      max = math.max(max, math.max(r(i), s(i)._1))
    }

    println(max)
  }

  solve()

}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object A446 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val r: Array[Int] = Array.ofDim[Int](n)
    r(0) = 1
    val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)
    s(0) = (1, a(0))
    var max = 0
    for (i <- 1 until n) {
      // update r:
      if (a(i) > a(i - 1)) {
        r(i) = r(i - 1) + 1
      } else {
        r(i) = 1
      }
      // update s:
      if (a(i) > s(i - 1)._2) {
        s(i) = (s(i - 1)._1 + 1, a(i))
      } else {
        s(i) = (r(i - 1) + 1, a(i-1) + 1)
      }
      max = math.max(max, math.max(r(i), s(i)._1))
    }

    println(max)
  }

  solve()

}

/**
 * @author pvasilyev
 * @since 14 Aug 2016
 */
object A446 extends App {

  def solve() = {
    val n = scala.io.StdIn.readInt()
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val r: Array[Int] = Array.ofDim[Int](n)
    r(0) = 1
    val s: Array[(Int, Int)] = Array.ofDim[(Int, Int)](n)
    s(0) = (1, a(0))
    var max = 1
    for (i <- 1 until n) {
      // update r:
      if (a(i) > a(i - 1)) {
        r(i) = r(i - 1) + 1
      } else {
        r(i) = 1
      }
      // update s:
      if (a(i) > s(i - 1)._2) {
        s(i) = (s(i - 1)._1 + 1, a(i))
      } else {
        s(i) = (r(i - 1) + 1, a(i-1) + 1)
      }
      max = math.max(max, math.max(r(i), s(i)._1))
    }

    println(max)
  }

  solve()

}

object Main {
  def main (args: Array[String]) {
    val n=io.StdIn.readLine().toInt
    val v=io.StdIn.readLine().split(" ").map(_.toInt)
    val s=Array.fill(n)(1)
    val t=Array.fill(n)(1)
    (1 until n).foreach(i=>if (v(i-1)<v(i)) s(i)+=s(i-1))
    (n-2 until -1 by -1).foreach(i=>if (v(i)<v(i+1)) t(i)+=t(i+1))

    var res=math.min(2,n)
    (0 until n).foreach(i=> {
      var cur = 1
      if (i > 0 && i + 1 < n-1 && v(i - 1) + 1 >= v(i + 1))
        cur += math.max(s(i - 1), t(i + 2))
      else{
        if (i>0) cur+=s(i-1)
        if (i+1<n) cur+=t(i+1)
      }
      res =math.max(res,cur)
    })
    println(res)
  }
}

object Main {
  def main (args: Array[String]) {
    val n=io.StdIn.readLine().toInt
    val v=io.StdIn.readLine().split(" ").map(_.toInt)
    val s=Array.fill(n)(1)
    val t=Array.fill(n)(1)
    (1 until n).foreach(i=>if (v(i-1)<v(i)) s(i)+=s(i-1))
    (n-2 until -1 by -1).foreach(i=>if (v(i)<v(i+1)) t(i)+=t(i+1))

    var res=math.min(2,n)
    (0 until n).foreach(i=> {
      var cur = 1
      if (i > 0 && i  < n-2 && v(i - 1) + 1 >= v(i + 1))
        cur += math.max(s(i - 1), t(i + 1))
      else{
        if (i>0) cur+=s(i-1)
        if (i+1<n) cur+=t(i+1)
      }
      res =math.max(res,cur)
    })
    println(res)
  }
}


Alice and Bob are playing a game on a matrix, consisting of $$$2$$$ rows and $$$m$$$ columns. The cell in the $$$i$$$-th row in the $$$j$$$-th column contains $$$a_{i, j}$$$ coins in it.Initially, both Alice and Bob are standing in a cell $$$(1, 1)$$$. They are going to perform a sequence of moves to reach a cell $$$(2, m)$$$.The possible moves are:   Move right — from some cell $$$(x, y)$$$ to $$$(x, y + 1)$$$;  Move down — from some cell $$$(x, y)$$$ to $$$(x + 1, y)$$$. First, Alice makes all her moves until she reaches $$$(2, m)$$$. She collects the coins in all cells she visit (including the starting cell).When Alice finishes, Bob starts his journey. He also performs the moves to reach $$$(2, m)$$$ and collects the coins in all cells that he visited, but Alice didn't.The score of the game is the total number of coins Bob collects.Alice wants to minimize the score. Bob wants to maximize the score. What will the score of the game be if both players play optimally?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of the testcase contains a single integer $$$m$$$ ($$$1 \le m \le 10^5$$$) — the number of columns of the matrix. The $$$i$$$-th of the next $$$2$$$ lines contain $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$1 \le a_{i,j} \le 10^4$$$) — the number of coins in the cell in the $$$i$$$-th row in the $$$j$$$-th column of the matrix. The sum of $$$m$$$ over all testcases doesn't exceed $$$10^5$$$.

For each testcase print a single integer — the score of the game if both players play optimally.

NoteThe paths for the testcases are shown on the following pictures. Alice's path is depicted in red and Bob's path is depicted in blue.

object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val m     = readInt()
    val apref = readLine().split(" ").map(_.toInt).scanLeft(0)(_ + _)
    val bpref = readLine().split(" ").map(_.toInt).scanLeft(0)(_ + _)

    def score: Int => Int = i => bpref(i) max (apref(m) - apref(i + 1))

    val ans = (1 until m).foldLeft(score(0))(_ min score(_))

    println(ans)
  }
}

object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val m  = readInt()
    val am = readLine().split(" ").map(_.toInt)
    val bm = readLine().split(" ").map(_.toInt)

    val (ans, _, _) = (1 until m).foldLeft((am.tail.sum, am.tail.sum, 0)) { case ((score, a, b), i) =>
      val (c, d) = (a - am(i), b + bm(i - 1))
      (score min (c max d), c, d)
    }

    println(ans)
  }
}

object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val m     = readInt()
    val apref = readLine().split(" ").map(_.toInt).scanLeft(0)(_ + _)
    val bpref = readLine().split(" ").map(_.toInt).scanLeft(0)(_ + _)

    def score(i: Int): Int = (apref(m) - apref(i + 1)) max bpref(i)

    val ans = (1 until m).foldLeft(score(0))((s, i) => s min score(i))

    println(ans)
  }
}

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

object Solution {
  def solve(m: Int, l1: Array[Int], l2: Array[Int]): Int = {
    // if Alice moved from l1 to l2 at point x then she:
    // collect from [0 to x] on line 1
    // from [x to m] on line 2

    // now bob can move to live 2 at y
    // x == y doesn't make sense
    // y < x the score is line 2 [y..x) which means it's [0..x)
    // y > x the score is line 1 (x..y] which means it's (x..m)

    // so for each x Bob will choose max of (v1) [0..x) in line 2 and (v2) (x..m) in line 1

    val partials1 = l1.reverse.scanLeft(0)(_ + _).tail.reverse
    val partials2 = l2.scanLeft(0)(_ + _).tail

    val bobsCounts = (0 until m).map { x =>
      val v1 = if (x == 0) 0 else partials2(x - 1)
      val v2 = if (x == m - 1) 0 else partials1(x + 1)
      Math.max(v1, v2)
    }.toArray

    bobsCounts.min
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val m = input.nextInt()
    val l1 = (1 to m).map { _ => input.nextInt() }.toArray
    val l2 = (1 to m).map { _ => input.nextInt() }.toArray
    output.println(solve(m, l1, l2))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

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


You and your friends live in $$$n$$$ houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.

First line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 1000)$$$. Next $$$n$$$ lines describe the positions of the houses $$$(x_i, y_i)$$$ $$$(0 \leq x_i, y_i \leq 10^9)$$$. It's guaranteed that the sum of all $$$n$$$ does not exceed $$$1000$$$.

For each test case output a single integer - the number of different positions for the exhibition. The exhibition can be built in the same point as some house.

NoteHere are the images for the example test cases. Blue dots stand for the houses, green — possible positions for the exhibition.First test case.Second test case. Third test case. Fourth test case. Fifth test case. Sixth test case. Here both houses are located at $$$(0, 0)$$$.

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object BEasternExhibition {
  def solve(xs: ArrayBuffer[Long], ys: ArrayBuffer[Long]): Long = {
    def count(list: ArrayBuffer[Long], size: Int): Long = {
      if (size % 2 == 1) 1 else list(size/2) - list(size/2-1) + 1
    }
    count(xs, xs.size)*count(ys, ys.size)
  }

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//"6\n3\n0 0\n2 0\n1 2\n4\n1 0\n0 2\n2 3\n3 1\n4\n0 0\n0 1\n1 0\n1 1\n2\n0 0\n1 1\n2\n0 0\n2 0\n2\n0 0\n0 0".getBytes)))
//"1\n3\n853308909 201424080\n881046497 871539684\n161055688 504667277".getBytes)))
    val inputs = file.readLine.toInt
    var i = 0
    while (i < inputs) {
      val p = file.readLine.toInt; var j = 0
      val xs = ArrayBuffer[Long]()
      val ys = ArrayBuffer[Long]()
      while (j < p) {
        val arr = file.readLine.split(" ").map(_.toLong)
        xs += arr(0)
        ys += arr(1)
        j += 1
      }
      println(solve(xs.sorted, ys.sorted))
      i += 1
    }
  }
}

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import scala.collection.mutable

object BEasternExhibition {
  def solve(xs: List[Long], ys: List[Long]): Long = {
    def count(list: List[Long], size: Int): Long = {
      if (size % 2 == 1) 1 else list(size/2) - list(size/2-1) + 1
    }
    count(xs, xs.size)*count(ys, ys.size)
  }

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//"6\n3\n0 0\n2 0\n1 2\n4\n1 0\n0 2\n2 3\n3 1\n4\n0 0\n0 1\n1 0\n1 1\n2\n0 0\n1 1\n2\n0 0\n2 0\n2\n0 0\n0 0".getBytes)))
//"1\n3\n853308909 201424080\n881046497 871539684\n161055688 504667277".getBytes)))
    val inputs = file.readLine.toInt
    var i = 0
    while (i < inputs) {
      val p = file.readLine.toInt; var j = 0
      val xs = mutable.TreeSet[Long]()
      val ys = mutable.TreeSet[Long]()
      while (j < p) {
        val arr = file.readLine.split(" ").map(_.toLong)
        xs += arr(0)
        ys += arr(1)
        j += 1
      }
      println(solve(xs.toList, ys.toList))
      i += 1
    }
  }
}

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import scala.collection.mutable.ArrayBuffer

object BEasternExhibition {
  def solve(xs: ArrayBuffer[Long], ys: ArrayBuffer[Long]): Long = {
    val l = xs.size
    if (l == 1) 1
    else if (l == 2) (Math.abs(xs(0) - xs(1)) + 1)*(1 + Math.abs(ys(0) - ys(1)))
    else {
//      def countMinPos(ys: ArrayBuffer[Long]): Long = {
//        var min = Long.MaxValue
//        var countMin = 0
//        var yd = 0L
//        for (p <- ys) {
//          yd += Math.abs(ys(0) - p)
//        }
//        var curr = 1
//        for (y <- ys(1) to ys.last) {
//          while (ys(curr) < y) {
//            curr += 1
//          }
//          val delta = curr - l + curr
//          yd += delta
//          if (yd < min) {
//            min = yd
//            countMin = 1
//          } else if (yd == min) countMin += 1
//        }
//        countMin
//      }
      def countMinPos2(ys: ArrayBuffer[Long]): Long = {
        var yd = 0L
        for (p <- ys) {
          yd += Math.abs(ys(0) - p)
        }
        var min = yd
        var countMin = 1L
        for (i <- 1 until ys.size) {
          val delta = i - l + i
          yd += delta
          val diff = ys(i) - ys(i - 1)
          if (yd < min) {
            min = yd
            countMin = if (diff == 0) 1 else diff
          } else if (yd == min) countMin += (if (diff == 0) 1 else diff)
        }
        countMin
      }
      val mc = Math.min(countMinPos2(xs), countMinPos2(ys))
      mc * mc
    }
  }

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//"6\n3\n0 0\n2 0\n1 2\n4\n1 0\n0 2\n2 3\n3 1\n4\n0 0\n0 1\n1 0\n1 1\n2\n0 0\n1 1\n2\n0 0\n2 0\n2\n0 0\n0 0".getBytes)))
    //              "1\n3\n0 0 3".getBytes)))
    val inputs = file.readLine.toInt
    var i = 0
    while (i < inputs) {
      val p = file.readLine.toInt; var j = 0
      val xs = ArrayBuffer[Long]()
      val ys = ArrayBuffer[Long]()
      while (j < p) {
        val arr = file.readLine.split(" ").map(_.toLong)
        xs += arr(0)
        ys += arr(1)
        j += 1
      }
      println(solve(xs.sorted, ys.sorted))
      i += 1
    }
  }
}


A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti:   If Petya has visited this room before, he writes down the minute he was in this room last time;  Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?

The first line contains a single integer n (1 ≤ n ≤ 2·105) — then number of notes in Petya's logbook. The second line contains n non-negative integers t1, t2, ..., tn (0 ≤ ti < i) — notes in the logbook.

In the only line print a single integer — the minimum possible number of rooms in Paris catacombs.

NoteIn the first sample, sequence of rooms Petya visited could be, for example 1 → 1 → 2, 1 → 2 → 1 or 1 → 2 → 3. The minimum possible number of rooms is 2.In the second sample, the sequence could be 1 → 2 → 3 → 1 → 2 → 1.

import scala.collection.mutable.ArrayBuffer

object C extends App {

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

  val Array(n) = readInts(1)
  val ts = readInts(n)

  val roomByMinute = Array.fill(n + 1)(-1)
  val lastVisit = ArrayBuffer.empty[Int]

  roomByMinute(0) = 1
  lastVisit += 0
  lastVisit += 0
  var maxRoom = 1

  var now = 1
  for (t <- ts) {
    val r = roomByMinute(t)
    if (lastVisit(r) == t) {
      lastVisit(r) = now
      roomByMinute(now) = r
    } else {
      maxRoom += 1
      lastVisit += now
      roomByMinute(now) = maxRoom
    }
    now += 1
  }

  println(maxRoom)
}

object C extends App {

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

  val Array(n) = readInts(1)
  val ts = readInts(n)

  val zeros = ts.count(_ == 0)
  val max = ts.max

  val res = zeros max max

  println(res)
}


You are given two strings $$$s$$$ and $$$t$$$ both of length $$$2$$$ and both consisting only of characters 'a', 'b' and 'c'.Possible examples of strings $$$s$$$ and $$$t$$$: "ab", "ca", "bb".You have to find a string $$$res$$$ consisting of $$$3n$$$ characters, $$$n$$$ characters should be 'a', $$$n$$$ characters should be 'b' and $$$n$$$ characters should be 'c' and $$$s$$$ and $$$t$$$ should not occur in $$$res$$$ as substrings.A substring of a string is a contiguous subsequence of that string. So, the strings "ab", "ac" and "cc" are substrings of the string "abacc", but the strings "bc", "aa" and "cb" are not substrings of the string "abacc".If there are multiple answers, you can print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of characters 'a', 'b' and 'c' in the resulting string. The second line of the input contains one string $$$s$$$ of length $$$2$$$ consisting of characters 'a', 'b' and 'c'. The third line of the input contains one string $$$t$$$ of length $$$2$$$ consisting of characters 'a', 'b' and 'c'.

If it is impossible to find the suitable string, print "NO" on the first line.  Otherwise print "YES" on the first line and string $$$res$$$ on the second line. $$$res$$$ should consist of $$$3n$$$ characters, $$$n$$$ characters should be 'a', $$$n$$$ characters should be 'b' and $$$n$$$ characters should be 'c' and $$$s$$$ and $$$t$$$ should not occur in $$$res$$$ as substrings. If there are multiple answers, you can print any of them.

//package codeforces.contest1213

object TwoSmallStrings {
  def categoriseInput(): (Int, (String, String, String)) = {
    val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)
    val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)

    val all = Set("a", "b", "c")

    if (l1 == l2 && r1 == r2) { // both same
      if (l1 == r1)
        (9, (l1, (all - l1).toList.head, (all - l1).toList.last))
      else
        (10, (l1, r1, (all - l1 - r1).head))
    } else if (l1 == l2) {
      if (l1 == r1)
        (1, (l1, r2, (all - l1 - r2).head))
      else if (l1 == r2)
        (1, (l1, r1, (all - l1 - r1).head))
      else
        (2, (l1, r1, r2))
    } else {
      if (l1 == r1 && l2 == r2)
        (6, (l1, l2, (all - l1 - l2).head))
      else if (l1 == r1) {
        if (l1 == r2)
          (5, (l1, l2, (all - l1 - l2).head))
        else
          (4, (l1, l2, r2))
      } else if (l2 == r2) {
        if (l2 == r1)
          (5, (l2, l1, (all - l1 - l2).head))
        else
          (4, (l2, l1, r1))
      } else {
        if (l2 == r1 && l1 == r2)
          (8, (l1, r1, (all - l1 - l2).head))
        else if (l2 == r1)
          (3, (l1, r1, r2))
        else if (l1 == r2)
          (3, (l2, r2, r1))
        else
          (7, (l1, r1, l2)) // r1 ==r2
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val (i, (x, y, z)) = categoriseInput()

    println(s"YES")
    println {
      i match {
        case 1 | 3 | 4 | 5 | 8 | 9 | 10 => (x + z) * n + y * n
        case 2                          => y * n + z * n + x * n
        case 6                          => (x + y) * n + z * n
        case 7                          => y * n + (x + z) * n
      }
    }
  }

}

//package codeforces.contest1213

object TwoSmallStrings {

  def categoriseInput(): (Int, (String, String, String)) = {
    val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)
    val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)

    val all = Set("a", "b", "c")

    if (l1 == l2 && r1 == r2) {
      if (l1 == r1)
        (7, (l1, (all - l1).toList.head, (all - l1).toList.last))
      else
        (8, (l1, r1, (all - l1 - r1).head))
    } else if (l1 == l2) {
      if (l1 == r1)
        (1, (l1, r2, (all - l1 - r2).head))
      else if (l1 == r2)
        (1, (l1, r1, (all - l1 - r2).head))
      else
        (2, (l1, r1, r2))
    } else {
      if (l1 == r1 && l2 == r2)
        (6, (l1, l2, (all - l1 - l2).head))
      else if (l1 == r1) {
        if (l1 == r2)
          (5, (l1, l2, (all - l1 - l2).head))
        else
          (4, (l1, l2, r2))
      } else if (l2 == r2) {
        if (l2 == r1)
          (5, (l2, l1, (all - l1 - l2).head))
        else
          (4, (l2, l1, r1))
      } else {
        if (l2 == r1)
          (3, (l1, r1, r2))
        else
          (3, (l2, r2, r1))
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val (i, (x, y, z)) = categoriseInput()

    println(s"YES")
    println {
      i match {
        case 1 | 3 | 4 | 5 | 7 | 8 => (x + z) * n + y * n
        case 2                     => y * n + z * n + x * n
        case 6                     => (x + y) * n + z * n
      }
    }
  }

}

//package codeforces.contest1213

object TwoSmallStrings {
  val base: Map[Char, Set[Char]] = Map(
    'a' -> Set('a', 'b', 'c'),
    'b' -> Set('a', 'b', 'c'),
    'c' -> Set('a', 'b', 'c')
  )

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val graph = {
      val Array(l1, r1) = io.StdIn.readLine.toCharArray
      val Array(l2, r2) = io.StdIn.readLine.toCharArray

      base + (l1 -> (base(l1) - r1)) + (l2 -> (base(l2) - r2))
    }

    def dfs(c: Char,
            available: Vector[Int], // size 3
            res: Vector[Char]): Option[Vector[Char]] =
      if (available.forall(_ == 0)) Some(res)
      else if (available(c - 'a') <= 0) None
      else {
        val updatedRes = res :+ c
        val updatedAvailable =
          available.updated(c - 'a', available(c - 'a') - 1)

        graph(c).foldLeft(Option.empty[Vector[Char]])(
          (acc, next) =>
            if (acc.isDefined) acc else dfs(next, updatedAvailable, updatedRes)
        )
      }

    println {
      List('a', 'b', 'c').foldLeft(Option.empty[Vector[Char]])(
        (acc, next) =>
          if (acc.isDefined) acc else dfs(next, Vector(n, n, n), Vector.empty)
      ) match {
        case Some(value) => "YES\n" + value.mkString
        case None        => "NO"
      }
    }
  }
}

//package codeforces.contest1213

object TwoSmallStrings {
  def categoriseInput(): (Int, (String, String, String)) = {
    val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)
    val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)

    val all = Set("a", "b", "c")

    if (l1 == l2 && r1 == r2) {
      if (l1 == r1)
        (8, (l1, (all - l1).toList.head, (all - l1).toList.last))
      else
        (9, (l1, r1, (all - l1 - r1).head))
    } else if (l1 == l2) {

      if (l1 == r1)
        (1, (l1, r2, (all - l1 - r2).head))
      else if (l1 == r2)
        (1, (l1, r1, (all - l1 - r1).head))
      else
        (2, (l1, r1, r2))

    } else {
      if (l1 == r1 && l2 == r2)
        (6, (l1, l2, (all - l1 - l2).head))
      else if (l1 == r1) {
        if (l1 == r2)
          (5, (l1, l2, (all - l1 - l2).head))
        else
          (4, (l1, l2, r2))
      } else if (l2 == r2) {
        if (l2 == r1)
          (5, (l2, l1, (all - l1 - l2).head))
        else
          (4, (l2, l1, r1))
      } else {
        if (l2 == r1)
          (3, (l1, r1, r2))
        else if (l1 == r2)
          (3, (l2, r2, r1))
        else
          (7, (l1, r1, l2))
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val (i, (x, y, z)) = categoriseInput()

    println(s"YES")
    println {
      i match {
        case 1 | 3 | 4 | 5 | 8 | 9 => (x + z) * n + y * n
        case 2                     => y * n + z * n + x * n
        case 6                     => (x + y) * n + z * n
        case 7                     => y * n + (x + z) * n
      }
    }
  }

}

//package codeforces.contest1213

object TwoSmallStrings {
  def categoriseInput(): (Int, (String, String, String)) = {
    val Array(l1, r1) = io.StdIn.readLine.toCharArray.map(_.toString)
    val Array(l2, r2) = io.StdIn.readLine.toCharArray.map(_.toString)

    val all = Set("a", "b", "c")

    if (l1 == l2 && r1 == r2) {
      if (l1 == r1)
        (8, (l1, (all - l1).toList.head, (all - l1).toList.last))
      else
        (9, (l1, r1, (all - l1 - r1).head))
    } else if (l1 == l2) {
      if (l1 == r1)
        (1, (l1, r2, (all - l1 - r2).head))
      else if (l1 == r2)
        (1, (l1, r1, (all - l1 - r2).head))
      else
        (2, (l1, r1, r2))
    } else {
      if (l1 == r1 && l2 == r2)
        (6, (l1, l2, (all - l1 - l2).head))
      else if (l1 == r1) {
        if (l1 == r2)
          (5, (l1, l2, (all - l1 - l2).head))
        else
          (4, (l1, l2, r2))
      } else if (l2 == r2) {
        if (l2 == r1)
          (5, (l2, l1, (all - l1 - l2).head))
        else
          (4, (l2, l1, r1))
      } else {
        if (l2 == r1)
          (3, (l1, r1, r2))
        else if (l1 == r2)
          (3, (l2, r2, r1))
        else
          (7, (l1, r1, l2))
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val (i, (x, y, z)) = categoriseInput()

    println(s"YES")
    println {
      i match {
        case 1 | 3 | 4 | 5 | 8 | 9 => (x + z) * n + y * n
        case 2                     => y * n + z * n + x * n
        case 6                     => (x + y) * n + z * n
        case 7                     => y * n + (x + z) * n
      }
    }
  }

}


On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last.  The red stripe was painted after the blue one, so the answer is R.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.

For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).

NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.

object HelloWorld {

  def main(args: Array[String]): Unit = {
    val tests = scala.io.StdIn.readInt()
    for (t <- 1 to tests) {
      scala.io.StdIn.readLine()

      val arr = Array.fill(8){scala.io.StdIn.readLine().toCharArray}

      if (arr.exists(_.forall(_ == 'R'))) println("R")
      else println("B")

    }
  }
}

object Stripes {

    def solve_test() = {
        val _ = scala.io.StdIn.readLine()
        if ((0 until 8).map(_ => scala.io.StdIn.readLine().count(_ == 'R')).max == 8)
            printf ("R\n")
        else
            printf ("B\n")
    }

    def main (args: Array[String]): Unit = {
        val test = scala.io.StdIn.readInt()
        for (i <- 0 until test) solve_test()
    }
}

object HelloWorld {

  def main(args: Array[String]): Unit = {
    val tests = scala.io.StdIn.readInt()
    for (t <- 1 to tests) {
      scala.io.StdIn.readLine()

      val arr = Array.fill(8){scala.io.StdIn.readLine().toCharArray}
      val arr2 = arr.transpose

      if (arr.exists(_.forall(_ == 'R')) || arr2.exists(_.forall(_ == 'R'))) println("R")
      else println("B")

    }
  }
}