Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!

The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi,  ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively.

If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line.

NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris.

object mishkaAndGame_703A extends App {

  val rounds = readLine().toInt
  var mishka = 0
  var chris = 0
  for (i <- 0 until rounds){
    val round = readLine().split(" ").toList
    if (round.head > round.last) mishka = mishka + 1
    else if (round.head < round.last) chris = chris + 1
  }

  if (mishka > chris) println("Mishka")
  else if (chris > mishka) println("Chris")
  else  println("Friendship is magic!^^")
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val (mish, chri) = lines.take(n).map(_.split(' ').map(_.toInt)).foldLeft((0, 0)) {
    case((mishka, chris), Array(m, c)) if m > c => (mishka + 1, chris)
    case((mishka, chris), Array(m, c)) if m < c => (mishka, chris + 1)
    case((mishka, chris), _) => (mishka, chris)
  }
  if (mish > chri)
    println("Mishka")
  else if (mish < chri)
    println("Chris")
  else
    println("Friendship is magic!^^")
}

object A703 {
  @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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(2)).filter(arr => arr(0) != arr(1))
    val m = input.count(arr => arr(0) > arr(1))
    val c = input.count(arr => arr(0) < arr(1))
    if(m == c) {
      println("Friendship is magic!^^")
    } else if (m > c) {
      println("Mishka")
    } else {
      println("Chris")
    }
  }
}

object A 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)

  var cnt = 0

  for (_ <- 0 until n) {
    val Array(a, b) = readInts(2)
    cnt += Integer.signum(b - a)
  }

  val res = if (cnt < 0) "Mishka"
  else if (cnt > 0) "Chris"
  else "Friendship is magic!^^"

  println(res)
}

/**
  * Created by BFD_299 on 2016/8/5.
  */

object code365A {
  def main(args:Array[String]): Unit ={
    var m = 0
    var c = 0
    val round = io.StdIn.readInt()
    for (i <- 1 to round){
      val cin = io.StdIn.readLine()
      val cins = cin.split(" ")
      if(cins(0) > cins(1)) m += 1
      if(cins(0) < cins(1)) c += 1
    }
    if(m > c) println("Mishka")
    if(m < c) println("Chris")
    if(m == c) println("Friendship is magic!^^")
  }
}

/**
  * Created by BFD_299 on 2016/8/5.
  */

object code365A {
  def main(args:Array[String]): Unit ={
    var m = 0
    var c = 0
    val round = io.StdIn.readInt()
    var cin: String = null
    var cins: Array[String] = null
    for (i <- 1 to round){
      cin = io.StdIn.readLine()
      cins = cin.split(" ")
      if(cins(0) > cins(1)) m += 1
      if(cins(0) < cins(1)) c += 1
    }
    if(m > c) println("Mishka")
    if(m < c) println("Chris")
    if(m == c) println("Friendship is magic!^^")
  }
}

object main extends App{
  val n = readInt
  println(List.range(0, n).foldLeft(Array(0,0))({ (res: Array[Int], i: Int) =>
    val Array(m, c) = readLine.split(" ").map(_.toInt)
    if (m>c) res(0) +=1 else if (m<c) res(1)+=1
    res
  }) match {
    case Array(m, c) => if (m > c) "Mishka" else if ( m<c ) "Chris" else "Friendship is magic!^^"
  })
}

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

object _703A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    var mishka, chris = 0
    repeat(n) {
      val m, c = read[Int]
      if (m < c) chris += 1 else if (m > c) mishka += 1
    }

    val ans = if (mishka < chris) {
      "Chris"
    } else if (chris < mishka) {
      "Mishka"
    } else {
      "Friendship is magic!^^"
    }

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

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

object Main extends App {
  import scala.io. { StdIn => In }
  val n = In.readInt
  var s = 0
  for(i <- 0 until n) {
    val Array(u,v) = In.readLine().split(" ").map(_.toInt)
    if (u < v) s -= 1
    else if (u > v) s += 1
  }
  if (s < 0) println ("Chris")
  else if (s > 0) println ("Mishka")
  else println("Friendship is magic!^^")
}

import scala.io.StdIn._

object A extends App {
  val t = readInt()
  var winner = 0
  1 to t foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toInt)
    if (a > b) winner += 1
    else if (b > a) winner -= 1
  }

  if (winner > 0) println("Mishka")
  else if (winner <0) print("Chris")
  else println("Friendship is magic!^^")
}

object mishkaAndGame_703A extends App {

  val rounds = readLine().toInt
  var mishka = 0
  var chris = 0
  for (i <- 0 until rounds){
    val round = readLine().split(" ").toList
    mishka = mishka + round.head.toInt
    chris = chris + round.last.toInt
  }
  if (mishka > chris) println("Mishka")
  else if (chris > mishka) println("Chris")
  else  println("Friendship is magic!^^")
}

object mishkaAndGame_703A extends App {

  val rounds = readLine().toInt
  var mishka = 0
  var chris = 0
  for (i <- 0 until rounds){
    val round = readLine().split(" ").toList
    if (round.head > round.last) mishka = mishka + 1
    else chris = chris + 1
  }
  if (mishka > chris) println("Mishka")
  else if (chris > mishka) println("Chris")
  else  println("Friendship is magic!^^")
}

object mishkaAndGame_703A extends App {

  val rounds = readLine().toInt
  var mishka = 0
  var chris = 0
  for (i <- 0 until rounds){
    val round = readLine().split(" ").toList
    if (round.head > round.last) mishka = mishka + 1
    else chris = chris + 1
  }
  if (mishka > chris) println("Mishka")
  else if (chris > mishka) println("Chris")
  else if (chris < mishka) println("Friendship is magic!^^")
}

object mishkaAndGame_703A extends App {

  val rounds = readLine().toInt
  var mishka = 0
  var chris = 0
  for (i <- 0 until rounds){
    val round = readLine().split(" ").toList
    if (round.head > round.last) mishka = mishka + 1
    else if (round.head > round.last) chris = chris + 1
  }
  if (mishka > chris) println("Mishka")
  else if (chris > mishka) println("Chris")
  else println("Friendship is magic!^^")
}

object A703 {
  @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))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(2)).count(arr => arr(0) > arr(1))
    if(input == n-input) {
      println("Friendship is magic!^^")
    } else if (input > n-input) {
      println("Mishka")
    } else {
      println("Chris")
    }
  }
}

object Main extends App {
  import scala.io. { StdIn => In }
  val n = In.readInt
  var s = 0
  for(i <- 0 until n) {
    val Array(u,v) = In.readLine().split(" ").map(_.toInt)
    if (u < v) s -= -1
    else if (u > v) s += 1
  }
  if (s < 0) println ("Chris")
  else if (s > 0) println ("Mishka")
  else println("Friendship is magic!^^")
}


You are given some Tetris field consisting of $$$n$$$ columns. The initial height of the $$$i$$$-th column of the field is $$$a_i$$$ blocks. On top of these columns you can place only figures of size $$$2 \times 1$$$ (i.e. the height of this figure is $$$2$$$ blocks and the width of this figure is $$$1$$$ block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one $$$a_i$$$ is greater than $$$0$$$:  You place one figure $$$2 \times 1$$$ (choose some $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with $$$a_i + 2$$$);  then, while all $$$a_i$$$ are greater than zero, replace each $$$a_i$$$ with $$$a_i - 1$$$. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of columns in the Tetris field. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the initial height of the $$$i$$$-th column of the Tetris field.

For each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.

NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process, the field becomes $$$[2, 0, 2]$$$. Then place the figure in the second column and after the second step of the process, the field becomes $$$[0, 0, 0]$$$.And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes $$$[0, 2]$$$. Then place the figure in the first column and after the second step of the process, the field becomes $$$[0, 0]$$$.In the fourth test case of the example, place the figure in the first column, then the field becomes $$$[102]$$$ after the first step of the process, and then the field becomes $$$[0]$$$ after the second step of the process.

import scala.io.StdIn

/**
  * @author hongchen.cao
  * @date 2020/03/15 17:55
  **/
object Test {
  def main(args: Array[String]): Unit = {
    val t: Int = StdIn.readInt()
    for (_ <- 1 to t) {
      val n = StdIn.readInt()

      val psum = StdIn.readLine().split(" ").map(_.toInt.%(2)).sum

      psum match {
        case s if s == 0 || s == n => println("YES")
        case _ => println("NO")
      }
    }
  }

}

import scala.io.StdIn

/**
  * @author hongchen.cao
  * @date 2020/03/15 17:55
  **/
object Test {
  def main(args: Array[String]): Unit = {
    val t: Int = StdIn.readInt()
    for (i <- 1 to t) {
      val n = StdIn.readInt()

      val psum = StdIn.readLine().split(" ").map(_.toInt % 2).sum

      psum match {
        case s if s == 0 || s == n => println("YES")
        case _ => println("NO")
      }
    }
  }

}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C627A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final 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)(f)
  }

  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 C627A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val a = na(n).toIndexedSeq.sorted

      var yes = true
      REP(n-1) { i =>
        val x = a(i+1) - a(i)
        yes = yes & (x % 2 == 0)
      }
      if(yes) out.println("YES") else out.println("NO")
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val as = io.read[Vector[Int]]

    val diffs = for {
      i <- as.indices.view
      j <- as.indices.drop(i + 1)
    } yield (as(j) - as(i))%2 == 0

    val ans = diffs.forall(identity)

    io.write(ans.toEnglish.toUpperCase)
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    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)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[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")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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


There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.

The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105).

Output a single integer — the optimal number of visible kangaroos.

import scala.io.Source

object Solution extends App {

  def count(small: List[Int], big: List[Int]): Int = {
    if (small.isEmpty || big.isEmpty) 0
    else if (small.head * 2 <= big.head) 1 + count(small.tail, big.tail)
    else count(small, big.tail)
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().toInt).sorted.toList
  println(n - count(data.take(n / 2), data.takeRight(n / 2)))
}

object A extends App {
  val n = readInt
  val sizes = for(i <- 0 until n) yield readInt
  val ss = sizes.sorted.toArray
  var canfit = 0
  var cantfit = n / 2 + 1
  while(canfit + 1 < cantfit) {
    val attempt = (canfit + cantfit) / 2
    var failed = false
    for(i <- 0 until attempt) {
      if(2 * ss(i) > ss(n-attempt+i)) {
        failed = true
      }
    }
    if(failed)
      cantfit = attempt
    else
      canfit = attempt
  }
  println(n - canfit)
}


The Berland language consists of words having exactly two letters. Moreover, the first letter of a word is different from the second letter. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland language.The Berland dictionary contains all words of this language. The words are listed in a way they are usually ordered in dictionaries. Formally, word $$$a$$$ comes earlier than word $$$b$$$ in the dictionary if one of the following conditions hold:  the first letter of $$$a$$$ is less than the first letter of $$$b$$$;  the first letters of $$$a$$$ and $$$b$$$ are the same, and the second letter of $$$a$$$ is less than the second letter of $$$b$$$. So, the dictionary looks like that:  Word $$$1$$$: ab  Word $$$2$$$: ac  ...  Word $$$25$$$: az  Word $$$26$$$: ba  Word $$$27$$$: bc  ...  Word $$$649$$$: zx  Word $$$650$$$: zy You are given a word $$$s$$$ from the Berland language. Your task is to find its index in the dictionary.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 650$$$) — the number of test cases. Each test case consists of one line containing $$$s$$$ — a string consisting of exactly two different lowercase Latin letters (i. e. a correct word of the Berland language).

For each test case, print one integer — the index of the word $$$s$$$ in the dictionary.

 import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // ======================================
  def solve(x: String) = {
    val f = x(0)
    val s = x(1)
    val a = 'a'
    if (f < s) (f - a) * 25 + s - a
    else (f - a) * 25 + s - a + 1
  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt

    for (
      i <- 0 until cases;
      s = readLine()
    ) println(solve(s))
  }
}


Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.

The first line of the input contains two integers n and a (1 ≤ n ≤ 100 000,  - 1 000 000 ≤ a ≤ 1 000 000) — the number of checkpoints and Vasya's starting position respectively. The second line contains n integers x1, x2, ..., xn ( - 1 000 000 ≤ xi ≤ 1 000 000) — coordinates of the checkpoints.

Print one integer — the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.

NoteIn the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point  - 10.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, a) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt).sorted
  println(List(line.drop(1), line.dropRight(1)).filter(_.length > 0).map{ i =>
    i.last - i.head + Math.min(Math.abs(a - i.head), Math.abs(a - i.last))
  }.sorted.headOption.getOrElse(0))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, a) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt).sorted
  println(List(line.drop(1), line.dropRight(1)).filter(_.length > 1).map{ i =>
    i.last - i.head + Math.min(Math.abs(a - i.head), Math.abs(a - i.last))
  }.sorted.headOption.getOrElse(0))
}


You are given an array $$$a$$$ of $$$2n$$$ distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its $$$2$$$ neighbours.More formally, find an array $$$b$$$, such that: $$$b$$$ is a permutation of $$$a$$$.For every $$$i$$$ from $$$1$$$ to $$$2n$$$, $$$b_i \neq \frac{b_{i-1}+b_{i+1}}{2}$$$, where $$$b_0 = b_{2n}$$$ and $$$b_{2n+1} = b_1$$$. It can be proved that under the constraints of this problem, such array $$$b$$$ always exists.

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$ — the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(1 \leq n \leq 25)$$$. The second line of each testcase contains $$$2n$$$ integers $$$a_1, a_2, \ldots, a_{2n}$$$ $$$(1 \leq a_i \leq 10^9)$$$ — elements of the array. Note that there is no limit to the sum of $$$n$$$ over all testcases.

For each testcase, you should output $$$2n$$$ integers, $$$b_1, b_2, \ldots b_{2n}$$$, for which the conditions from the statement are satisfied.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val a2n = readLine().split(" ").map(_.toInt).sorted
    val b2n = (0 until (2 * n)).map {
      case i if i % 2 == 0 => a2n(i / 2)
      case i               => a2n(n + (i - 1) / 2)
    }

    println(b2n.mkString(" "))
  }
}


You have three piles of candies: red, green and blue candies:  the first pile contains only red candies and there are $$$r$$$ candies in it,  the second pile contains only green candies and there are $$$g$$$ candies in it,  the third pile contains only blue candies and there are $$$b$$$ candies in it. Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.

The first line contains integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given as a separate line of the input. It contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \le r, g, b \le 10^8$$$) — the number of red, green and blue candies, respectively.

Print $$$t$$$ integers: the $$$i$$$-th printed integer is the answer on the $$$i$$$-th test case in the input.

NoteIn the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.

object A {
  import InOut._
  def main(args: Array[String]): Unit = {}

  val t = nextInt
  for (_ <- 1 to t) {
    val xs = nextInts(3)
    val max = xs.max
    val min = xs.min
    val s = xs.sum
    val mid = s - max - min
    var h1, h2 = 0
    if (min >= max - mid) {
      h1 = max - mid + (min - (max - mid)) / 2
      h2 = min - h1
    } else {
      h1 = Math.min(min, Math.max((min + 1) / 2, max - mid))
      h2 = min - h1
    }
    val res = min + Math.min(max - h1, mid - h2)
    out.println(res)
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {}

  val t = nextInt
  for (_ <- 1 to t) {
    val xs = nextInts(3)
    val max = xs.max
    val min = xs.min
    val s = xs.sum
    val mid = s - max - min
    val h1 = Math.min(min, Math.max((min + 1) / 2, max - mid))
    val h2 = min - h1
    val res = min + Math.min(max - h1, mid - h2)
    out.println(res)
  }

  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


Gerald found a table consisting of n rows and m columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value — it seemed to be too small. And to make this value larger, he decided to crop the table a little: delete some columns on the left and some on the right, as well as some rows from the top and some from the bottom. Find what the maximum property of the table can be after such cropping. Note that the table should have at least two rows and at least two columns left in the end. The number of cropped rows or columns from each of the four sides can be zero.

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 1000). The following n lines describe the table. The i-th of these lines lists the space-separated integers ai, 1, ai, 2, ..., ai, m (0 ≤ ai, j ≤ 109) — the m numbers standing in the i-th row of the table.

NoteIn the first test case Gerald cannot crop the table — table contains only two rows and only two columns.In the second test case if we'll crop the table, the table will contain zero in some corner cell. Also initially it contains two zeros in the corner cells, so the answer is 0.

object D extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val a = Array.ofDim[Int](n, m)

  for (i <- 0 until n) a(i) = readInts

  val pair = Array.fill(m, m)(0)

  var max = 0
  var row = 0

  while (row < n) {
    var i = 0
    while (i < m - 1) {
      val ai = a(row)(i)
      if (ai > max) {
        var j = i + 1
        while (j < m) {
          val aj = a(row)(j)
          if (aj > max) {
            val aa = math.min(ai, aj)
            val result = math.min(pair(i)(j), aa)
            if (result > max) max = result
            if (aa > result) pair(i)(j) = aa
          }
          j += 1
        }
      }
      i += 1
    }
    row += 1
  }

  println(max)
}

object D extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val a = Array.ofDim[Int](n, m)

  for (i <- 0 until n) a(i) = readInts

  val pair = Array.fill(m, m)(0)

  var row = 0
  var max = 0

  while (row < n) {
    var i = 0
    while (i < m - 1) {
      val ai = a(row)(i)
      if (ai > max) {
        var j = i + 1
        while (j < m) {
          val aj = a(row)(j)
          if (aj > max) {
            val aa = math.min(ai, aj)
            val result = math.min(pair(i)(j), aa)
            if (result > max) max = result
            if (aa > result) pair(i)(j) = aa
          }
          j += 1
        }
      }
      i += 1
    }
    row += 1
  }

  println(max)
}

object D extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val pair = Array.fill(m, m)(0)

  var max = 0
  var row = 0

  while (row < n) {
    val as = readInts
    var i = 0
    while (i < m - 1) {
      val ai = as(i)
      if (ai > max) {
        var j = i + 1
        while (j < m) {
          val aj = as(j)
          if (aj > max) {
            val aa = math.min(ai, aj)
            val result = math.min(pair(i)(j), aa)
            if (result > max) max = result
            if (aa > result) pair(i)(j) = aa
          }
          j += 1
        }
      }
      i += 1
    }
    row += 1
  }

  println(max)
}

object D extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts

  val a = Array.ofDim[Int](n, m)

  for (i <- 0 until n) a(i) = readInts

  val pair = Array.fill(m, m)(0)

  var row = 0
  var max = 0

  while (row < n) {
    var i = 0
    while (i < m - 1) {
      val ai = a(row)(i)
      if (ai > max) {
        var j = i + 1
        while (j < m) {
          val aj = a(row)(j)
          if (aj > max) {
            val aa = math.min(ai, aj)
            val result = math.min(pair(i)(j), aa)
            if (result > max) max = result
            pair(i)(j) = aa
          }
          j += 1
        }
      }
      i += 1
    }
    row += 1
  }

  println(max)
}


This is the easy version of the problem. The only difference between the two versions is the constraint on $$$n$$$. You can make hacks only if all versions of the problem are solved.A forest is an undirected graph without cycles (not necessarily connected).Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $$$1$$$ to $$$n$$$, and they would like to add edges to their forests such that:   After adding edges, both of their graphs are still forests.  They add the same edges. That is, if an edge $$$(u, v)$$$ is added to Mocha's forest, then an edge $$$(u, v)$$$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.

The first line contains three integers $$$n$$$, $$$m_1$$$ and $$$m_2$$$ ($$$1 \le n \le 1000$$$, $$$0 \le m_1, m_2 < n$$$) — the number of nodes and the number of initial edges in Mocha's forest and Diana's forest. Each of the next $$$m_1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Mocha's forest. Each of the next $$$m_2$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edges in Diana's forest.

The first line contains only one integer $$$h$$$, the maximum number of edges Mocha and Diana can add (in each forest). Each of the next $$$h$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) — the edge you add each time. If there are multiple correct answers, you can print any one of them.

NoteIn the first example, we cannot add any edge.In the second example, the initial forests are as follows.We can add an edge $$$(2, 4)$$$.

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

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

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

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

    def dfs(u: Int, e: Array[ArrayBuffer[Int]], ch: Array[Boolean], f: Array[Int]): Unit = {
        for (v <- e(u) if !ch(v)) {
            ch(v) = true
            f(v) = f(u)
            dfs(v, e, ch, f)
        }
    }

    def root(u: Int, f: Array[Int]): Int = {
        if (f(u) < 0) return u
        f(u) = root(f(u), f)
        f(u)
    }

    def join(u: Int, v: Int, f: Array[Int]): Unit = {
        var x = root(u, f)
        var y = root(v, f)
        if (x == y) return

        if (f(y) < f(x)) {
            val t = x
            x = y
            y = t
        }
        f(x) += f(y)
        f(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val Array(n,m1,m2) = readArrayInt()
        //val e1 = Array.fill(n)(new ArrayBuffer[Int]())
        //val e2 = Array.fill(n)(new ArrayBuffer[Int]())

        val f1 = new Array[Int](n)
        val f2 = new Array[Int](n)

        for (i <- 0 until n) {
            f1(i) = -1
            f2(i) = -1
        }

        for (_ <- 0 until m1) {
            val Array(u,v) = readArrayInt()
            //e1(u - 1) += v - 1
            //e1(v - 1) += u - 1
            join (u - 1, v - 1, f1)
        }

        for (_ <- 0 until m2) {
            val Array(u,v) = readArrayInt()
           // e2(u - 1) += v - 1
            //e2(v - 1) += u - 1
            join (u - 1, v - 1, f2)
        }

        /*val f1 = new Array[Int](n)
        val f2 = new Array[Int](n)
        var ch = Array.fill[Boolean](n)(false)
        var c = 1
        for (i <- 0 until n if !ch(i)) {
            f1(i) = c
            dfs(i, e1, ch, f1)
            c += 1
        }

        ch = Array.fill[Boolean](n)(false)
        c = 1
        for (i <- 0 until n if !ch(i)) {
            f2(i) = c
            dfs(i, e2, ch, f2)
            c += 1
        }*/

        val rs = new ArrayBuffer[(Int, Int)]()

        for (i <- 0 until n - 1; j <- i + 1 until n) {
            if (root(i, f1) != root(j, f1) && root(i, f2) != root(j, f2)) {
                rs += ((i + 1, j + 1))
                join(i, j, f1)
                join(i, j, f2)
            }
        }

        println(rs.length)

        for ((u,v) <- rs)
            writer.println(s"$u $v")
    }

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

import java.io.PrintWriter
import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

// if there is k1 left in G1 and k2 left in G2 and k1 > 0 & k2 > 0 then
//   if we can prove that edge exist which satisfies problem
//   we can add it and move problem to k1-1 & k2-1
//   let's assume that's true
object Solution {
  def solve(input: Int): Int = {
    input
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    output.println(solve(1))
  }

  def connect(colors: Array[Int], v: Int, u: Int): Unit = {
    val toMatch = colors(v)
    colors.indices.foreach { idx =>
      if (colors(idx) == toMatch) colors(idx) = colors(u)
    }
  }

  def connected(colors: Array[Int], v: Int, u: Int): Boolean = colors(v) == colors(u)

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

    val c1 = (0 until n).toArray
    val c2 = (0 until n).toArray

    (1 to m1).foreach { _ =>
      val u = input.nextInt() - 1
      val v = input.nextInt() - 1
      connect(c1, u, v)
    }
    (1 to m2).foreach { _ =>
      val u = input.nextInt() - 1
      val v = input.nextInt() - 1
      connect(c2, u, v)
    }

    val ans = ArrayBuffer[(Int, Int)]()
    (0 until (n - 1)).foreach { u =>
      (u + 1).until(n).foreach { v =>
        if (!connected(c1, u, v) && !connected(c2, u, v)) {
          ans.append((u + 1, v + 1))
          connect(c1, u, v)
          connect(c2, u, v)
        }
      }
    }

    output.println(ans.length)
    ans.foreach { case (u, v) =>
      output.println(u + " " + v)
    }
    output.flush()
  }

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


You are given a binary string $$$s$$$ of length $$$n$$$.Let's define $$$d_i$$$ as the number whose decimal representation is $$$s_i s_{i+1}$$$ (possibly, with a leading zero). We define $$$f(s)$$$ to be the sum of all the valid $$$d_i$$$. In other words, $$$f(s) = \sum\limits_{i=1}^{n-1} d_i$$$.For example, for the string $$$s = 1011$$$:   $$$d_1 = 10$$$ (ten);  $$$d_2 = 01$$$ (one)  $$$d_3 = 11$$$ (eleven);  $$$f(s) = 10 + 01 + 11 = 22$$$. In one operation you can swap any two adjacent elements of the string. Find the minimum value of $$$f(s)$$$ that can be achieved if at most $$$k$$$ operations are allowed.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. First line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$0 \le k \le 10^9$$$) — the length of the string and the maximum number of operations allowed. The second line of each test case contains the binary string $$$s$$$ of length $$$n$$$, consisting of only zeros and ones. It is also given that sum of $$$n$$$ over all the test cases doesn't exceed $$$10^5$$$.

For each test case, print the minimum value of $$$f(s)$$$ you can obtain with at most $$$k$$$ operations.

Note  For the first example, you can't do any operation so the optimal string is $$$s$$$ itself. $$$f(s) = f(1010) = 10 + 01 + 10 = 21$$$.  For the second example, one of the optimal strings you can obtain is "0011000". The string has an $$$f$$$ value of $$$22$$$.  For the third example, one of the optimal strings you can obtain is "00011". The string has an $$$f$$$ value of $$$12$$$.

import scala.collection.mutable
import scala.io.StdIn

object Sol {
  def main(args: Array[String]): Unit = {
    val tests = StdIn.readLine().toInt
    (0 until tests).foreach { _ =>
      val Array(count, moves) = StdIn.readLine().split(" ").map(_.toInt)
      val numbers = StdIn.readLine().split("").map(_.toInt)

      if(!numbers.contains(1)) {
        println(0)
      } else {
        val lastOne = numbers.lastIndexOf(1)
        val firstOne = numbers.indexOf(1)

        var score = 0
        for(i <- numbers.indices.drop(1)) {
          score += numbers(i - 1) * 10 + numbers(i)
        }

        val modifier = if(moves >= (count - (lastOne + 1)) + firstOne && firstOne != lastOne && firstOne != 0 && lastOne != count - 1) {
          -11
        } else if(moves >= (count - (lastOne + 1)) && lastOne != count - 1) {
          if(lastOne == 0) {
            -9
          } else {
            -10
          }
        } else if(moves >= firstOne && firstOne != 0 && firstOne != count - 1) {
          -1
        } else {
          0
        }

        println(score + modifier)

      }
    }
  }
}

import scala.io.StdIn

object Sol {
  def main(args: Array[String]): Unit = {
    val tests = StdIn.readLine().toInt
    (0 until tests).foreach { _ =>
      val Array(count, moves) = StdIn.readLine().split(" ").map(_.toInt)
      val numbers = StdIn.readLine().split("").map(_.toInt)

      if(!numbers.contains(1)) {
        println(0)
      } else {
        val lastOne = numbers.lastIndexOf(1)
        val firstOne = numbers.indexOf(1)

        var score = 0
        for(i <- numbers.indices.drop(1)) {
          score += numbers(i - 1) * 10 + numbers(i)
        }

        val modifier = if(moves >= (count - (lastOne + 1)) + firstOne && firstOne != lastOne && firstOne != 0 && lastOne != count - 1) {
          -11
        } else if(moves >= (count - (lastOne + 1)) && lastOne != count - 1) {
          -10
        } else if(moves >= firstOne && firstOne != 0 && firstOne != count - 1) {
          -1
        } else {
          0
        }

        println(score + modifier)

      }
    }
  }
}

import scala.collection.mutable
import scala.io.StdIn

object Sol {
  def main(args: Array[String]): Unit = {
    val tests = StdIn.readLine().toInt
    (0 until tests).foreach { _ =>
      val Array(count, moves) = StdIn.readLine().split(" ").map(_.toInt)
      val numbers = StdIn.readLine().split("").map(_.toInt)

      if(!numbers.contains(1)) {
        println(0)
      } else {
        val lastOne = numbers.lastIndexOf(1)
        val firstOne = numbers.indexOf(1)

        var score = 0
        for(i <- numbers.indices.drop(1)) {
          score += numbers(i - 1) * 10 + numbers(i)
        }

        val modifier = if(moves >= (count - (lastOne + 1)) + firstOne && firstOne != lastOne && firstOne != 0 && lastOne != count - 1) {
          -11
        } else if(moves >= (count - (lastOne + 1)) && lastOne != count - 1) {
          -10
        } else if(moves >= firstOne && firstOne != 0) {
          -1
        } else {
          0
        }

        println(score + modifier)

      }
    }
  }
}


Polycarp has guessed three positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$.You have to guess three numbers $$$a$$$, $$$b$$$ and $$$c$$$ using given numbers. Print three guessed integers in any order.Pay attention that some given numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (it is also possible that $$$a=b=c$$$).

The only line of the input contains four positive integers $$$x_1, x_2, x_3, x_4$$$ ($$$2 \le x_i \le 10^9$$$) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number $$$x_1, x_2, x_3, x_4$$$.

Print such positive integers $$$a$$$, $$$b$$$ and $$$c$$$ that four numbers written on a board are values $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$ written in some order. Print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.

object Example extends App {
  def greater(i: Int, j : Int): Int =
    i > j match {
      case true => i
      case _ => j
    }

  def myPrint (g :Int, b :Int) =
    g == b match {
      case false => print( g - b + " ")
      case _ =>
    }

  var lol = scala.io.StdIn.readLine().split(" ")
  var a = lol(0).toInt
  var b = lol(1).toInt
  var c = lol(2).toInt
  var d = lol(3).toInt

  var g = greater(greater(c,d), greater(a,b))
  myPrint (g, a)
  myPrint (g, b)
  myPrint (g, c)
  myPrint (g, d)

}

object Example extends App {
  def greater(i: Int, j : Int): Int =
    i > j match {
      case true => i
      case _ => j
    }

  def myPrint (g : Int, b :Int) =
    g == b match {
      case false => print( g.toInt - b.toInt + " ")
      case _ =>
    }

  var input = scala.io.StdIn.readLine().split(" ")
  var r = input.map(e => e.toInt)
  var g = greater(greater(r(0), r(1)), greater(r(2) , r(3)))
  input.map( e => myPrint(g, e.toInt))
}

object Example extends App {
  def greater(i: Int, j : Int): Int =
    i > j match {
      case true => i
      case _ => j
    }

  def myPrint (g : Int, b :Int) =
    g == b match {
      case false => print( g.toInt - b.toInt + " ")
      case _ =>
    }

  var input = scala.io.StdIn.readLine().split(" ")
  var r = input.map(e => e.toInt)
  var g = greater(greater(r(0), r(1)), greater(r(2) , r(3)))
  r.map( e => myPrint(g, e))
}

object Example extends App {
  def greater(i: Int, j : Int): Int =
    i > j match {
      case true => i
      case _ => j
    }

  def myPrint (g : Int, b :Int) =
    g == b match {
      case false => print( g - b + " ")
      case _ =>
    }

  var input = scala.io.StdIn.readLine().split(" ")
  var r = input.map(e => e.toInt)
  var g = greater(greater(r(0), r(1)), greater(r(2) , r(3)))
  r.map( e => myPrint(g, e))
}

 /**
  * @author ShankarShastri
  *         Algorithm: RestoringThreeNumbers
  */

import scala.io.StdIn._
import scala.annotation.tailrec

object RestoringThreeNumbers {
  def main(args: Array[String]): Unit = {
    val l = readLine.split(" ").map(_.toInt)
    val abc = l.max
    println(l.filter(abc - _ != 0).map(abc - _).mkString(" "))
  }
}

object Puzzle {
  def main(args: Array[String]): Unit = {
    val Array(a, b, c, d) = scala.io.StdIn.readLine()
      .split(" ")
      .map(_.toInt)
      .sorted
    print(d - a + " ")
    print(d - b + " ")
    print(d - c)
  }
}

import java.util.Scanner

object Solution {
  def main(args : Array[String]) : Unit = {
    val scanner = new Scanner(System.in)
    val x_1 = scanner.nextInt()
    val x_2 = scanner.nextInt()
    val x_3 = scanner.nextInt()
    val x_4 = scanner.nextInt()
    val xs = Seq(x_1, x_2, x_3, x_4)
    val m = xs.max
    val ms = Seq(m)
    val xs_minus_ms = xs.diff(ms)
    for (x <- xs_minus_ms) {
      val a = m - x
      print(s"${a} ")
    }
    println()
  }
}

import scala.io.StdIn

object Codeforces1154A extends App {
  var Array(x1, x2, x3, x4) = StdIn.readLine().split("\\s").map(s => s.toLong)

  var abc = math.max(x1, math.max(x2, math.max(x3, x4)))
  if (x1 != abc) print((abc - x1) + " ")
  if (x2 != abc) print((abc - x2) + " ")
  if (x3 != abc) print((abc - x3) + " ")
  if (x4 != abc) print((abc - x4) + " ")
}

import scala.io.StdIn._

object Main2 extends App {
  val numbers = readLine().split(" ").map(_.toLong).sorted
  println(s"${numbers(3) - numbers(1)} ${numbers(3) - numbers(2)} ${numbers(3) - numbers(0)}")
}

object Demo {
  def main(args: Array[String]): Unit
  =
  {
    var arr = new Array[Int](4)

      //arr = readLine.split(" ").map(_.toInt)
      val Array(a,b,c,d)=readLine.split(" ").map(_.toInt)
    arr(0)=a
    arr(1)=b
    arr(2)=c
    arr(3)=d
   // arr.sorted
    for(i<-0 to 3)
      {
        for(j<-i+1 to 3)
          {
            if(arr(i)>arr(j))
              {
                var temp=arr(i)
                arr(i)=arr(j)
                arr(j)=temp
              }
          }
      }
    println((arr(3)-arr(0))+" "+(arr(3)-arr(1))+" "+(arr(3)-arr(2)))
    /*for(i<-0 to 3)
      println(arr(i))*/
  }
}

object Puzzle {
  def main(args: Array[String]): Unit = {
    val Array(a, b, c, d) = scala.io.StdIn.readLine()
      .split(" ")
      .map(_.toInt)
      .sorted
    print(d - a + " ")
    print(d - b + " ")
    print(d - a)
  }
}


You are given array $$$a$$$ of length $$$n$$$. You can choose one segment $$$[l, r]$$$ ($$$1 \le l \le r \le n$$$) and integer value $$$k$$$ (positive, negative or even zero) and change $$$a_l, a_{l + 1}, \dots, a_r$$$ by $$$k$$$ each (i.e. $$$a_i := a_i + k$$$ for each $$$l \le i \le r$$$).What is the maximum possible number of elements with value $$$c$$$ that can be obtained after one such operation?

The first line contains two integers $$$n$$$ and $$$c$$$ ($$$1 \le n \le 5 \cdot 10^5$$$, $$$1 \le c \le 5 \cdot 10^5$$$) — the length of array and the value $$$c$$$ to obtain. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5 \cdot 10^5$$$) — array $$$a$$$.

Print one integer — the maximum possible number of elements with value $$$c$$$ which can be obtained after performing operation described above.

NoteIn the first example we can choose any segment and $$$k = 0$$$. The array will stay same.In the second example we can choose segment $$$[1, 3]$$$ and $$$k = -4$$$. The array will become $$$[2, -2, 2]$$$.

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, K = ni()
    val A = na(N)

    val M = 5e5.toInt + 1
    val cnt = Array.ofDim[Int](M)
    val P = Array.ofDim[Array[Int]](M) // 数値毎の配列
    rep(N) { i =>
      val m = A(i)
      if (m != K) cnt(m) += 1
    }

    rep(M) { m =>
      P(m) = new Array(cnt(m))
    }

    rep_r(N) { i =>
      val m = A(i)
      if (m != K) {
        cnt(m) -= 1
        P(m)(cnt(m)) = i
      }
    }

    // Kが見つかった累積数
    val cum = Array.ofDim[Int](N + 1)
    rep(N) { i =>
      cum(i + 1) = cum(i) + (if(A(i) == K) 1 else 0)
    }

    val S = cum(N)
    var ans = S
    rep(M) { m =>
      val p = P(m)
      val n = p.length
      if (n > 0) {
        var sum = 0
        var prev = 0
        var mx = 0
        var ms = 0
        rep(n) { i =>
          sum -= cum(p(i) + 1) - cum(prev)
          ms = min(ms, sum)
          sum += 1
          mx = max(mx, sum - ms) // これまでのminと現在地の差が最大になる場所を探す
          prev = p(i)
        }
        // 最後に現れる位置を超える意味がない

        ans = max(ans, S + mx)
      }
    }

    out.println(ans)
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

object Main
{
    def main(args:Array[String])
        {
            val n = readInt
            val iNums = readLine.split(" ").map(i => i.toInt)
            var iMin = 1001;
            for (i <- (1 until iNums.length))
            {
                iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
            }
            println(List(iMin, iNums(0), iNums.last).min)
        }
}

object Main
{
    def main(args:Array[String])
        {
            val n = readInt
            val iNums = (readLine + " 1000").split(" ").map(i => i.toInt)
            /*var iMin = 1001;
            for (i <- (1 until iNums.length))
            {
                iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
            }
            println(List(iMin, iNums(0), iNums.last).min)*/
            var iMin = (1 to n).map(i => List(iNums(i), iNums(i - 1)).max).min;
            println(List(iMin, iNums(0), iNums(n - 1)).min)
        }
}

object Main
{
	def main(args:Array[String])
		{
			val n = readInt
			val iNums = readLine.split(" ").map(i => i.toInt)
			/*var iMin = 1001;
			for (i <- (1 until iNums.length))
			{
				iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
			}
			println(List(iMin, iNums(0), iNums.last).min)*/
			var iMin = 1001;
			for (i <- (1 until iNums.length))
			{
				iMin = List(iMin, List(iNums(i), iNums(i - 1)).max).min;
			}
			println(List(iMin, iNums(0), iNums.last).min)
		}
}

import scala.io.Source
import scala.math._

import java.util.BitSet

object B extends App {
  def go = main(Array())

  val in = Source.stdin.getLines.toList
  val n = in(0).toInt
  val destr = in(1).split(" ").map(_.toInt).zipWithIndex.groupBy(_._1)

  val broken = new BitSet(n)

  val eventfulDays = destr.keySet.toList.sorted

  def solve: Int = {
    eventfulDays.foreach ( day => {
      destr(day).foreach { case (_, tile) => {
	if (tile == 0 || tile == (n-1)) return day
	if (broken.get(tile-1) || broken.get(tile+1)) return day
	broken.set(tile)
      }}
    })
    return eventfulDays.last
  }

  println (solve)
}

object Main {
    def main(args: Array[String]) {

        val n = readInt
        val a = readLine.split(' ').map(_.toInt)

        val r = (1 to n).map(i => (i, a(i-1))).toArray.sortBy(_._2)

        var i = 1
        if(r(0)._1 != 1 && r(0)._1 != n) {
            while(i < n && r(i)._1 != 1 && r(i)._1 != n && r(i)._1 != r(i-1)._1+1) i += 1
            println(r(i)._2)
        } else {
            println(r(0)._1)
        }
    }
}

object Main {
    def main(args: Array[String]) {

        val n = readInt
        val a = readLine.split(' ').map(_.toInt)

        val r = (1 to n).map(i => (i, a(i-1))).toArray.sortBy(_._2)

        var i = 1
        if(r(0)._1 != 1 && r(0)._1 != n) {
            while(i < n && r(i)._1 != 1 && r(i)._1 != n && r(i)._1 != r(i-1)._1+1) i += 1
            println(r(i)._2)
        } else {
            println(r(0)._2)
        }
    }
}


New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.  He lifts all the books above book x.  He pushes book x out of the stack.  He puts down the lifted books without changing their order.  After reading book x, he puts book x on the top of the stack.  He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.

NoteHere's a picture depicting the example. Each vertical column presents the stacked books.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val weight = in.next().split(' ').map(_.toInt)
  val order = in.next().split(' ').map(_.toInt - 1)
  var distinct = order.distinct.toList
  println(order.foldLeft(0) {
    case (acc, i) if distinct.head == i => acc
    case (acc, i) =>
      var sum = acc
      val firstPart = distinct.takeWhile(_ != i)
      val secondPart = distinct.dropWhile(_ != i).tail
      distinct = i :: (firstPart ::: secondPart)
      acc + firstPart.map(weight).sum
  })

}

import scala.collection._

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, m) = readInts(2)
  val ws = readLongs(n)
  val bs = readInts(m).map(_ - 1)

  val first = Array.fill(n)(Int.MaxValue)
  for (i <- bs.indices) if (first(bs(i)) == Int.MaxValue) first(bs(i)) = i

  val stack = (0 until n).sortBy(first).toArray
  var res = 0L

  for (b <- bs) {
    var i = 0
  //println(b+1, stack.map(_ + 1).mkString(" "))
    while (stack(i) != b) {
      res += ws(stack(i))
      i += 1
    }
    while (i > 0) {
      stack(i) = stack(i - 1)
      i -= 1
    }
    stack(0) = b
  }

  println(res)
}

object P500C {
	@inline def readInts : Array[Int] = {
		scala.io.StdIn.readLine.split(" ").map(_.toInt)
	}

	def solve(ws: Array[Int])(s: List[Int], bs: List[Int]) : Int = {
		if (bs.isEmpty) {
			0
		} else {
			val (top, rest) = s.splitAt(s.indexOf(bs.head))
			val stack = rest.head :: top ::: rest.tail
			val lifted = top.foldLeft(0)((x, y) => x + ws(y - 1))
			lifted + solve(ws)(stack, bs.tail)
		}
	}

	def main(args: Array[String]) {
		val Array(n, m) = readInts
		val ws = readInts
		val bs = readInts.toList
		println(solve(ws)(bs.distinct, bs))
	}
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val weight = in.next().split(' ').map(_.toInt)
  val order = in.next().split(' ').map(_.toInt)
  var distinct = order.distinct.toList
  println(order.foldLeft(0) {
    case (acc, i) if distinct.head == i => acc
    case (acc, i) =>
      var sum = acc
      val firstPart = distinct.takeWhile(_ != i)
      val secondPart = distinct.dropWhile(_ != i).tail
      distinct = i :: (firstPart ::: secondPart)
      acc + firstPart.sum
  })

}

import scala.collection._

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, m) = readInts(2)
  val ws = readLongs(n)
  val bs = readInts(m).map(_ - 1)

  val first = Array.fill(n)(-1)
  for (i <- bs.indices) if (first(bs(i)) < 0) first(bs(i)) = i

  val stack = (0 until n).sortBy(first).toArray
  var res = 0L

  for (b <- bs) {
    var i = 0
  //println(b+1, stack.map(_ + 1).mkString(" "))
    while (stack(i) != b) {
      res += ws(stack(i))
      i += 1
    }
    while (i > 0) {
      stack(i) = stack(i - 1)
      i -= 1
    }
    stack(0) = b
  }

  println(res)
}


You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — elements of the array $$$a$$$.

Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $$$a$$$.

NoteIn the first example you can remove $$$7$$$ then instability of the remaining array will be $$$3 - 1 = 2$$$.In the second example you can remove either $$$1$$$ or $$$100000$$$ then instability of the remaining array will be $$$100000 - 100000 = 0$$$ and $$$1 - 1 = 0$$$ correspondingly.

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)
    sort(A)

    val ans = min(A(N - 1) - A(1), A(N - 2) - A(0))
    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.quickSort(a)
    a
  }

  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[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.io.StdIn

object ArrayStabilization extends App {

  val n = StdIn.readLine().toInt
  val xs = StdIn.readLine().split(" ").map(_.toInt)

  println(findSol(xs))

  def findSol(xs: Array[Int]) = {
    val revSorted = xs.sorted(Ordering[Int].reverse)

    val rem1 = revSorted.drop(1)
    val min1 = rem1.head - rem1.last

    val rem2 = revSorted.take(xs.length - 1)
    val min2 = rem2.head - rem2.last

    math.min(min1, min2)
  }
}

object CF_529_3_B {

  type In = (Int, Seq[Int])
  type Out = Int

  def solve(in: In): Out = {
    val (n, xs) = in
    n match {
      case 2 => 0
      case _ =>
        val sort = xs.sorted
        val (min1, min2) = (sort(0), sort(1))
        val (max1, max2) = (sort.last, sort.init.last)
        if(min2 - min1 > max1 - max2) max1 - min2
        else max2 - min1
    }
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}