You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operations on it:  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(0 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j+x$$$ for all $$$(1 \le j \le i)$$$, which means add $$$x$$$ to all the elements in the prefix ending at $$$i$$$.  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(1 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j \% x$$$ for all $$$(1 \le j \le i)$$$, which means replace every element in the prefix ending at $$$i$$$ with the remainder after dividing it by $$$x$$$. Can you make the array strictly increasing in no more than $$$n+1$$$ operations?

The first line contains an integer $$$n$$$ $$$(1 \le n \le 2000)$$$, the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\dots$$$, $$$a_n$$$ $$$(0 \le a_i \le 10^5)$$$, the elements of the array $$$a$$$.

On the first line, print the number of operations you wish to perform. On the next lines, you should print the operations. To print an adding operation, use the format "$$$1$$$ $$$i$$$ $$$x$$$"; to print a modding operation, use the format "$$$2$$$ $$$i$$$ $$$x$$$". If $$$i$$$ or $$$x$$$ don't satisfy the limitations above, or you use more than $$$n+1$$$ operations, you'll get wrong answer verdict.

NoteIn the first sample, the array is already increasing so we don't need any operations.In the second sample:In the first step: the array becomes $$$[8,6,3]$$$.In the second step: the array becomes $$$[0,2,3]$$$.

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object EhabAndTwoOperationTask {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readIntArray(n: Int): Array[Int] = {
    val st = new StringTokenizer(br.readLine())

    val arr = new Array[Int](n)
    var i = 0
    while (st.hasMoreElements) {
      arr(i) = st.nextToken().toInt
      i += 1
    }

    arr
  }

  def readInt(): Int = {
    new StringTokenizer(br.readLine()).nextToken.toInt
  }

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val input: Array[Int] = readIntArray(n)
    val x = 3 * (input.length max input.max)

    println((1 to n).foldLeft(new StringBuilder().append(n+1).append('\n').append(s"1 $n $x\n"))((acc, i) => acc.append(s"2 $i " + (x + input(i-1) - i) + "\n")))
  }
}

//package codeforces

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object EhabAndTwoOperationTask {

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readIntArray(n: Int): Array[Int] = {
    val st = new StringTokenizer(br.readLine())

    val arr = new Array[Int](n)
    var i = 0
    while (st.hasMoreElements) {
      arr(i) = st.nextToken().toInt
      i += 1
    }

    arr
  }

  def readInt(): Int = {
    new StringTokenizer(br.readLine()).nextToken.toInt
  }

  def main(args: Array[String]): Unit = {
    val n = readInt()
    val input: Array[Int] = readIntArray(n)

    println(n + 1)

    val x = 3 * (input.length max input.max)

    println(s"1 $n $x")

    for (i <- 1 to n) {
      val currentValue = x + input(i-1)
      println(s"2 $i " + (currentValue - i))
    }

  }
}

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)
    var sum = 0L
    val ops = ArrayBuffer[(Int, Long)]()
    REP_r(N) { i =>
      val target = i
      val r = (sum + A(i)) % N
      if (target != r) {
        val x = (N + target - r) % N
        ops += ((i, x))
        sum += x
      }
    }

    out.println(ops.length + 1)
    ops.reverse.foreach { case (i, x) =>
      out.println(s"1 ${i+1} $x")
    }
    out.println(s"2 $N $N")
  }

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

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

  override def apply(io: IO): io.type = {
    val (n, as) = io.readAll[Long]
    val m = 5e5.toLong
    var s = 0L

    val ans = {
      for {
        i <- as.indices.reverse
      } yield {
        val x = m + (i + 1 - (as(i) + s))%m
        s += x
        s"1 ${i+1} $x"
      }
    } :+ s"2 $n $m"

    io.writeLine(ans.length).writeAll(ans , separator = "\n")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

object C extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)
  def readInt = StdIn.readInt()

  val n = readInt
  val A = readInts

//  val n = 3
//  val A = Array(7, 6, 3)

  def solve() = {
    var sum = 0
    println(n + 1)
    (0 until n).reverse.foreach { i =>
      val diff = (i - (A(i) + sum) % n + n) % n
      sum += diff
      println(s"1 ${i + 1} $diff")
    }
    println(s"2 $n $n")
  }

  solve()
}

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

  override def apply(io: IO): io.type = {
    val (n, as) = io.readAll[Long]
    val m = as.max + 1
    var s = 0L

    val ans = {
      for {
        i <- as.indices.reverse
      } yield {
        val x = m + (- as(i) - s + i+1)%m
        assert(x > 0)
        s = (s + x)%m
        s"1 ${i+1} $x"
      }
    } :+ s"2 $n $m"

    assert(ans.length <= n+1)

    io.writeLine(ans.length).writeAll(ans , separator = "\n")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

object C extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)
  def readInt = StdIn.readInt()

//  val n = readInt
//  val A = readInts

  val n = 3
  val A = Array(7, 6, 3)

  def solve() = {
    var sum = 0
    println(n + 1)
    (0 until n).reverse.foreach { i =>
      val diff = (i - (A(i) + sum) % n + n) % n
      sum += diff
      println(s"1 $i $diff")
    }
    println(s"2 $n $n")
  }

  solve()
}

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

object C extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)
  def readInt = StdIn.readInt()

  val n = readInt
  val A = readInts

//  val n = 3
//  val A = Array(7, 6, 3)

  def solve() = {
//    println(A.mkString(" "))
    var solution = ArrayBuffer[String]()

    (0 until n).reverse.foreach { i =>
      val diff = (n - A(i) % n + i) % n

//      println(diff)
      if (diff > 0) {
        (0 to i).foreach { j =>
          A(j) += diff
        }
        solution += s"1 $diff $i"
//        println(s"1 $diff i")
//        println(A.mkString(" "))
      }
    }

    (0 until n).foreach { i =>
      A(i) %= n
    }

    solution += s"2 ${n - 1} $n"
//    println(s"2 ${n - 1} $n")
//    println(A.mkString(" "))

    println(solution.length)
    println(solution.mkString("\n"))
  }

  solve()
}

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

object C extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)
  def readInt = StdIn.readInt()

  val n = readInt
  val A = readInts

//  val n = 3
//  val A = Array(7, 6, 3)

  def solve() = {
//    println(A.mkString(" "))
    var solution = ArrayBuffer[String]()

    (0 until n).reverse.foreach { i =>
      val diff = n - A(i) % n + i

//      println(diff)
      if (diff > 0) {
        (0 to i).foreach { j =>
          A(j) += diff
        }
        solution += s"1 $diff i"
//        println(s"1 $diff i")
//        println(A.mkString(" "))
      }
    }

    (0 until n).foreach { i =>
      A(i) %= n
    }

    solution += s"2 ${n - 1} $n"
//    println(s"2 ${n - 1} $n")
//    println(A.mkString(" "))

    println(solution.length)
    println(solution.mkString("\n"))
  }

  solve()
}

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

object C extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)
  def readInt = StdIn.readInt()

  val n = readInt
  val A = readInts

//  val n = 3
//  val A = Array(7, 6, 3)

  def solve() = {
//    println(A.mkString(" "))
    var solution = ArrayBuffer[String]()

    (0 until n).reverse.foreach { i =>
      val diff = (n - A(i) % n + i) % n

//      println(diff)
      if (diff > 0) {
        (0 to i).foreach { j =>
          A(j) += diff
        }
        solution += s"1 $diff i"
//        println(s"1 $diff i")
//        println(A.mkString(" "))
      }
    }

    (0 until n).foreach { i =>
      A(i) %= n
    }

    solution += s"2 ${n - 1} $n"
//    println(s"2 ${n - 1} $n")
//    println(A.mkString(" "))

    println(solution.length)
    println(solution.mkString("\n"))
  }

  solve()
}

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

object C extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)
  def readInt = StdIn.readInt()

//  val n = readInt
//  val A = readInts

  val n = 3
  val A = Array(7, 6, 3)

  def solve() = {
    var sum = 0
    println(n + 1)
    (0 until n).reverse.foreach { i =>
      val diff = (i - (A(i) + sum) % n + n) % n
      sum += diff
      println(s"1 ${i + 1} $diff")
    }
    println(s"2 $n $n")
  }

  solve()
}


Bob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.

The first line of input will contain two integers n and m (2 ≤ n, m ≤ 50), denoting the dimensions of the maze. The next n lines will contain exactly m characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string s (1 ≤ |s| ≤ 100) — the instructions given to the robot. Each character of s is a digit from 0 to 3.

Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.

NoteFor the first sample, the only valid mapping is , where D is down, L is left, U is up, R is right.

object B 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 maze = Array.fill(n){readLine}
  val moves = readLine.map(_ - '0')

  var r0, c0 = -1

  for {
    r <- 0 until n
    c <- 0 until m
  } {
    if (maze(r)(c) == 'S') {
      r0 = r
      c0 = c
    }
  }

  def check(mapping: Array[Int]): Boolean = {
    var r = r0
    var c = c0
    var ok = true

    var step = 0
    while (ok && step < moves.length) {

      mapping(moves(step)) match {
        case 0 =>
          r += 1
        case 1 =>
          c -= 1
        case 2 =>
          r -= 1
        case 3 =>
          c += 1
      }

      ok = r >= 0 && c >= 0 && r < n && c < m && maze(r)(c) != '#'

      if (ok && maze(r)(c) == 'E') return true

      step += 1
    }

    ok && maze(r)(c) == 'E'
  }

  val directions = Array(0, 1, 2, 3)

  var count = 0

  for {
    mapping <- directions.permutations
    if check(mapping)
  } count += 1

  println(count)
}

object B extends App {
  val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val a = for (_ <- 0 until n) yield scala.io.StdIn.readLine().split("")
  val s = scala.io.StdIn.readLine().split("").map(_.toInt)

  def D(c: (Int, Int)): (Int, Int) = (c._1, c._2 - 1)
  def U(c: (Int, Int)): (Int, Int) = (c._1, c._2 + 1)
  def L(c: (Int, Int)): (Int, Int) = (c._1 - 1, c._2)
  def R(c: (Int, Int)): (Int, Int) = (c._1 + 1, c._2)

  def check(c: (Int, Int)): Boolean =
    c._1 >= 0 && c._1 < m && c._2 >=0 && c._2 < n && a(c._2)(c._1) != "#"

  def S(c: (Int, Int) = (0, 0)): (Int, Int) =
    if (c._1 == m) S((0, c._2 + 1))
    else if (a(c._2)(c._1) == "S") c
    else S((c._1 + 1, c._2))

  val c = S()

//  def variant(d: Int, u: Int, l: Int, r: Int, c: (Int, Int) = c, s: Array[Int] = s): Boolean =
  def variant(codes: Array[Int], c: (Int, Int) = c, s: Array[Int] = s): Boolean =
    if (!check(c)) false
    else {
      val t = a(c._2)(c._1)
      if (t == "E") true
      else if (s.isEmpty) false
      else {
        val h = s.head
        if (h == codes(0)) variant(codes, D(c), s.tail)
        else if (h == codes(1)) variant(codes, U(c), s.tail)
        else if (h == codes(2)) variant(codes, L(c), s.tail)
        else variant(codes, R(c), s.tail)
      }
    }

  println(Array(0, 1, 2, 3).permutations.count(variant(_)))
}

import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks

object Main {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  def main (args: Array[String]){
    val H, W = in.next().toInt
    val field = new Array[String](H+1)
    for (i <- 1 to H) {
      field(i) = "#" + in.next()
    }
    val command = in.next()

    ///
    def isCorrect(p: (Int, Int)) = {
      val (x, y) = p
      1 <= x && x <= W && 1 <= y && y<= H
    }

    var start = (-1, -1)
    var goal = (-1, -1)
    for(y <- 1 to H; x <- 1 to W) {
      val now = field(y)(x)
      if(now == 'S')
        start = (x, y)
      else if(now == 'E')
        goal = (x, y)
    }

    val perm: List[List[(Int, Int)]] =
      List((1,0),(-1,0),(0,1),(0,-1)).permutations.toList
    var ans = 0

    val b = new Breaks  // instance of Breaks

    for (e <- perm) {
      var now: (Int, Int) = (start._1, start._2)
      b.breakable {
        for(c <- command) {
          val com = c.toString.toInt
          val (volx, voly) = e(com)
          val next: (Int, Int) = (now._1 + volx, now._2 + voly)
          now = next
          if(isCorrect(next)){
            if(next == goal) {
              ans += 1
              b.break
            }
            else if(field(next._2)(next._1) == '#')
              b.break
          }
          else {
            b.break
          }
        }
      }
    }
    println(ans)
  }
}

class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

object CF908B extends App {

  val sc = new java.util.Scanner(System.in)

  val Array(rows, cols) = io.StdIn.readLine split " " map (_.toInt)
  val robomap = for (r <- 1 to rows) yield io.StdIn.readLine
  val route = io.StdIn.readLine split "" map (_.toInt)

  val start = find('S')
  val end = find('E')

  val ans = Range(0, 3 + 1).permutations count solve

  print(ans)

  def solve(seq: Seq[Int]): Boolean = {
    val d = Seq((0, 1), (0, -1), (1, 0), (-1, 0))

    var current = start
    for (c <- route) {
      current = (current._1 + d(seq(c))._1, current._2 + d(seq(c))._2)
      if (current._1 < 0 ||
        current._2 < 0 ||
        current._1 >= rows ||
        current._2 >= cols || robomap(current._1)(current._2) == '#') return false
      if (current equals end) return true
    }
    false
  }

  def find(c: Char): (Int, Int) = {
    for (r <- 0 until rows) {
      val i = robomap(r).indexOf(c)
      if (i >= 0) return (r, i)
    }
    return (-1, -1)
  }

}

import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks

object Main {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  def main (args: Array[String]){
    val H, W = in.next().toInt
    val field = new Array[String](H+1)
    for (i <- 1 to H) {
      field(i) = "#" + in.next()
    }
    val command = in.next()

    ///
    def isCorrect(p: (Int, Int)) = {
      val (x, y) = p
      1 <= x && x <= W && 1 <= y && y<= H
    }

    var start = (-1, -1)
    var goal = (-1, -1)
    for(y <- 1 to H; x <- 1 to W) {
      val now = field(y)(x)
      if(now == 'S')
        start = (x, y)
      else if(now == 'E')
        goal = (x, y)
    }

    val perm: List[List[(Int, Int)]] =
      List((1,0),(-1,0),(0,1),(0,-1)).permutations.toList
    var ans = 0

    val b = new Breaks  // instance of Breaks

    for (e <- perm) {
      var now: (Int, Int) = (start._1, start._2)
      b.breakable {
        for(c <- command) {
          val com = c.toString.toInt
          val (volx, voly) = e(com)
          val next: (Int, Int) = (now._1 + volx, now._2 + voly)
          now = next
          if(isCorrect(next)){
            if(next == goal) {
              ans += 1
              b.break
            }
          }
          else {
            b.break
          }
        }
      }
    }
    println(ans)
  }
}

class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}


Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x, y) — the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx, dy); using this move, the piece moves from the field (x, y) to the field (x + dx, y + dy). You can perform the move if the cell (x + dx, y + dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x, y) and (x + dx, y + dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.

The first line contains a single integer n (1 ≤ n ≤ 50). The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values:  o — in this case the field (i, j) is occupied by a piece and the field may or may not be attacked by some other piece; x — in this case field (i, j) is attacked by some piece; . — in this case field (i, j) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board.

If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n - 1) × (2n - 1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'.

NoteIn the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight.

import scala.io.StdIn

object D extends App {
  val n = StdIn.readInt()
  val f = Array.fill(n)(StdIn.readLine().toCharArray)

  def validateMove(dx: Int, dy: Int): Boolean = {
    (dx != 0 || dy != 0) &&
    (for (x <- 0 until n; y <- 0 until n; if x + dx >= 0 && x + dx < n && y + dy >= 0 && y + dy < n && f(x)(y) == 'o') yield f(x + dx)(y + dy) != '.').forall(identity)
  }

  val moves = for (x <- -n + 1 to n - 1; y <- -n + 1 to n - 1 if validateMove(x, y)) yield (x, y)

  for ((dx, dy) <- moves) {
    for (x <- 0 until n; y <- 0 until n; if x + dx >= 0 && x + dx < n && y + dy >= 0 && y + dy < n && f(x)(y) == 'o') {
      if (f(x + dx)(y + dy) == 'x') {
        f(x + dx)(y + dy) = '.'
      }
    }
  }

  if (f.forall(_.forall(_ != 'x'))) {
    println("YES")
    val f2 = Array.fill(2 * n - 1, 2 * n - 1)('.')
    f2(n - 1)(n - 1) = 'o'
    for ((dx, dy) <- moves) {
      f2(n - 1 + dx)(n - 1 + dy) = 'x'
    }
    f2.map(t => String.valueOf(t)).foreach(println)
  } else {
    println("NO")
  }
}

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

object D 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 as = Array.fill(n) { readLine.toCharArray }
  val isHit = Array.fill(n, n) { false }

  val validDxBuilder, validDyBuilder = new ArrayBuilder.ofInt

  for (dx <- -n + 1 to n - 1) {
    for (dy <- -n + 1 to n - 1) if (dx != 0 || dy != 0){
      var possible = true
      for (x <- 0 until n) {
        for (y <- 0 until n) {
          if (as(x)(y) == 'o') {
            val nx = x + dx
            val ny = y + dy
            if (nx >= 0 && ny >= 0 && nx < n && ny < n && as(nx)(ny) == '.') possible = false
          }
        }
      }
      if (possible) {
        validDxBuilder += dx
        validDyBuilder += dy
        for (x <- 0 until n) {
          for (y <- 0 until n) {
            if (as(x)(y) == 'o') {
              val nx = x + dx
              val ny = y + dy
              if (nx >= 0 && ny >= 0 && nx < n && ny < n) isHit(nx)(ny) = true
            }
          }
        }
      }
    }
  }

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

  var ok = true
  for (x <- 0 until n) {
    for (y <- 0 until n) {
      if (isHit(x)(y) && as(x)(y) == '.') ok = false
      if (!isHit(x)(y) && as(x)(y) == 'x') ok = false
    }
  }

  if (ok) {
    println("YES")
    val res = Array.fill(2 * n - 1, 2 * n - 1)('.')
    res(n - 1)(n - 1) = 'o'
    val validDx = validDxBuilder.result
    val validDy = validDyBuilder.result
    for (i <- 0 until validDx.size) {
      //println(validDx(i), validDy(i))
      res(n + validDx(i) - 1)(n + validDy(i) - 1) = 'x'
    }
    for (r <- res) println(r.mkString)
  } else println("NO")

  Console.flush
}


Haiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".Three phases from a certain poem are given. Determine whether it is haiku or not.

The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.

Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).

on  codeforces
beta round is running
   a rustling of keys

how many gallons
of edo s rain did you drink
                                cuckoo

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val vowel = List('a', 'e', 'i', 'o', 'u')
  if ((1 to 3).map(_ => in.next().count(vowel.contains)).toList == List(5, 7, 5))
    println("YES")
  else
    println("NO")
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P078A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val Poem = List.fill(3)(sc.nextLine)
  val isVowel = "aeiou".toSet
  val isHaiku = (lst: List[String]) => {
      lst.map(_.count(isVowel)) == List(5, 7, 5)
    }
  val res = if (isHaiku(Poem)) "YES" else "NO"

  out.println(res)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random
import scala.util.control.Breaks._

object P078A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val isVowel = "aeiou".toSet
  val isHaiku = List(5, 7, 5) == List.fill(3)(sc.nextLine).map(_.count(isVowel))
  val res = if (isHaiku) "YES" else "NO"

  out.println(res)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val s1 = readLine()
    val s2 = readLine()
    val s3 = readLine()

    val i1 = s1.count(c => c == 'a' || c == 'e' || c == 'o' || c == 'u' || c == 'i')
    val i2 = s2.count(c => c == 'a' || c == 'e' || c == 'o' || c == 'u' || c == 'i')
    val i3 = s3.count(c => c == 'a' || c == 'e' || c == 'o' || c == 'u' || c == 'i')

    if (i1 == 5 && i2 == 7 && i3 == 5) println("YES")
    else (println("NO"))
  }
}


Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of USB flash drives. The second line contains positive integer m (1 ≤ m ≤ 105) — the size of Sean's file. Each of the next n lines contains positive integer ai (1 ≤ ai ≤ 1000) — the sizes of USB flash drives in megabytes. It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.

Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.

NoteIn the first example Sean needs only two USB flash drives — the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive — the first or the second.

object Solution extends App {
val n = Console.readLine() toInt;
var m = Console.readLine() toInt;
var count = 0;
for (a <- ((for { i <- 1 to n } yield
    Console.readLine() toInt
  ).toList.sorted.reverse) if m > 0) {
  m = m - a;
  count = count + 1;
}
println(count)
}

import scala.io.StdIn

/**
  * Created by Buffalo on 16/1/3.
  */
object cf_609a {
  def main(args : Array[String]) = {
    val n :: m :: l = Iterator.continually(StdIn readLine()).takeWhile(_ != null).map(_.toInt).toList

    def fun  (list: List[Int], rem: Int, cnt:Int):Int = {
      if (rem <= 0) {
        cnt
      } else {
        fun(list.tail, rem - list.head, cnt + 1)
      }
    }
    println(fun(l.sortBy(-_), m, 0))

//    println(n + " " + m + " " + l)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val m = in.next().toInt
  val res = (1 to n).map(_ => in.next().toInt).sorted.reverse.foldLeft((0, 0)) {
    case ((sum, count), el) if sum >= m => (sum, count)
    case ((sum, count), el) => (sum + el, count + 1)
  }
  println(res._2)

}

object A609 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val Array(m) = readInts(1)
    val in = Array.fill(n)(readInts(1)).map(_(0)).sorted.reverse
    var i = 0
    var curr = 0
    while(curr < m) {
      curr += in(i)
      i += 1
    }
    println(i)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

import java.util.Arrays.sort
import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val scanner = new Scanner(System.in)
    def next = scanner.next.toInt

    val size = next
    val sum = next
    val capacities = 0.to(size - 1).map(x => next).toArray

    println(countMinVolumes(capacities, sum))
  }

  def countMinVolumes(capacities: IndexedSeq[Int], targetSum: Int) : Int = {
    val sorted = capacities.sorted(Ordering[Int].reverse)
    var count = 0
    var sum = 0
    for (capacity <- sorted) {
      count = count + 1
      sum = sum + capacity
      if (sum >= targetSum)
        return count
    }
    assert(false)
    0
  }
}

object A extends App {
 val n = readInt
 var m = readInt
 var l = List[Int]()

 def getNum : Int = {
     for(i <- 0 until n)
       l = l :+ readInt

     var i = 0
     for(f <- l.sorted.reverse) {
       m = m - f
       i = i + 1

       if (m <= 0)
        return i
     }
     i
 }

 println(getNum)
}

import io.StdIn._

object tmp extends App {
  val n = readInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

import scala.io.Codec
import scala.io.StdIn._

object tmp extends App {

  class Scanner(reader: java.io.LineNumberReader) extends Iterator[String] with AutoCloseable {
    type StringTokenizer = java.util.StringTokenizer

    def this(reader: java.io.BufferedReader) = this(new java.io.LineNumberReader(reader))

    def this(reader: java.io.Reader) = this(new java.io.BufferedReader(reader))

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

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

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

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

    def nextString(): String = next()

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

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

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

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

    override def hasNext = tokenizer().nonEmpty

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

  val n = readInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).toArray.sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

import scala.io.Codec

object tmp extends App {

  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    //    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

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

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

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

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

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

    def nextString(): String = next()

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

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

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

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

    override def hasNext = tokenizer().nonEmpty

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

  val s = new Scanner(System.in)

  //  val n = readInt()
  val n = s.nextInt()
  //  var m = readInt()
  var m = s.nextInt()
  val a = (for (_ <- 0 until n) yield s.nextInt()).toArray.sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

object tmp extends App {

  import scala.io.Codec
  import scala.io.StdIn._

  class Scanner(reader: java.io.LineNumberReader) extends Iterator[String] with AutoCloseable {
    type StringTokenizer = java.util.StringTokenizer

    def this(reader: java.io.BufferedReader) = this(new java.io.LineNumberReader(reader))

    def this(reader: java.io.Reader) = this(new java.io.BufferedReader(reader))

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

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

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

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

    def nextString(): String = next()

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

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

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

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

    override def hasNext = tokenizer().nonEmpty

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

  val n = readInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).toArray.sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

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

    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 s = new MyScanner(System.in)

  val n = s.nextInt()
  var m = s.nextInt()
  val a = (for (_ <- 0 until n) yield s.nextInt()).toArray.sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

import scala.io.StdIn._

object tmp extends App {

  //  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  //    def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  //
  //    def this(reader: Reader) = this(new BufferedReader(reader))
  //
  //    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  //
  //    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  //
  //
  //    private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  //    private[this] var current: Option[StringTokenizer] = None
  //
  //    private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
  //      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
  //      current
  //    }
  //
  //    def nextString(): String = next()
  //
  //    def nextChar(): Char = next().ensuring(_.length == 1).head
  //
  //
  //    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  //
  //    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  //
  //
  //    override def next() = tokenizer().get.nextToken()
  //
  //    override def hasNext = tokenizer().nonEmpty
  //
  //    override def close() = reader.close()
  //  }

  //  val r = new Scanner(io.Source.stdin.bufferedReader())
  //  val n = r.nextInt()
  val n = readInt()
  //  var m = r.nextInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

import io.StdIn._

object tmp extends App {
  val n = readInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).sorted.reverse
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

import scala.io.StdIn._

object tmp extends App {
  val n = readInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).view.toArray.sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

import scala.io.StdIn._

object tmp extends App {
  val n = readInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).toArray.sortBy(-_)
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}

/*
 * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/
 */

object Main extends App {
  import java.{util => ju}
  import scala.annotation._
  import scala.collection._
  import scala.collection.{mutable => mu}
  import scala.collection.JavaConverters._
  import scala.math._

  val sc = new ju.Scanner(System.in)
  val n,m = sc.nextInt
  val a = Array.fill(n)(sc.nextInt).sortWith(_ > _).inits.map(_.sum)
  println(n + 1 - a.count(_ >= m))

}

import io.StdIn._

object tmp extends App {
  println("hello")
  val n = readInt()
  var m = readInt()
  val a = (for (_ <- 0 until n) yield readInt()).sorted.reverse
  val result = a.indexWhere((i: Int) => {
    m -= i
    m <= 0
  }) + 1
  println(result)
}


A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.

For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.

NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.

import scala.io.StdIn._

object A extends App {
  val t = readInt()

  def isPossible(x: Array[Char], n: Int): Boolean = {
    for (i <- 0 to n - 11) {
      if (x(i) == '8') return true
    }
    false
  }

  1 to t foreach { _ =>
    val n = readInt()
    val x = readLine().toArray
    if (isPossible(x, n)) println("YES") else println("NO")
  }
}

import scala.io.StdIn

object MyScalaApp {
  def main(args: Array[String]): Unit = {

    val t = StdIn.readInt()

    for(x <- 1 to  t){
      val n = StdIn.readInt()
      val s = StdIn.readLine()

      if(s.indexOf('8') != -1 && (n - s.indexOf("8") >= 11)){
        println("YES")
      } else{
        println("NO")
      }

    }
  }
}

import scala.io.StdIn

object MyScalaApp {
  def main(args: Array[String]): Unit = {

    val t = StdIn.readInt()

    for(x <- 1 to  t){
      val n = StdIn.readInt()
      val s = StdIn.readLine()

      if(s.indexOf("8") != -1 && (n - s.indexOf("8") >= 11)){
        println("YES")
      } else{
        println("NO")
      }

    }
  }
}

import scala.io.StdIn

object MyScalaApp {
  def main(args: Array[String]): Unit = {

    val t = StdIn.readInt()
    var idx = 0

    while(idx < t){
      val n = StdIn.readInt()
      val s = StdIn.readLine()

      if(s.indexOf("8") != -1 && (n - s.indexOf("8") >= 11)){
        println("YES")
      } else{
        println("NO")
      }
      idx = idx + 1
    }
  }
}

import scala.io.StdIn

object MyScalaApp {
  def main(args: Array[String]): Unit = {

    val t = StdIn.readInt()

    for(x <- 1 to  t){
      val n = StdIn.readInt()
      val s = StdIn.readLine()

      if(s.indexOf('8') != -1 && (n - s.indexOf('8') >= 11)){
        println("YES")
      } else{
        println("NO")
      }

    }
  }
}

import scala.io.StdIn

object Codeforces1167A {

  def isPhoneNumber(number: String): Boolean = {
    val findResult = number.zipWithIndex.find { case (digit, _) => digit == '8' }
    if (findResult.isDefined) {
      val index = findResult.get._2
      number.length - index >= 11
    } else false
  }

  def main(args: Array[String]): Unit = {
    val totalTestCase = StdIn.readLine().toInt
    for (_ <- 1 to totalTestCase) {
      val _ = StdIn.readLine().trim
      val number = StdIn.readLine().trim
      val result = isPhoneNumber(number)
      println(if (result) "YES" else "NO")
    }
  }
}


Maria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competition — determine the number of dangerous turns on the track.

The first line of the input contains an integer n (4 ≤ n ≤ 1000) — the number of straight sections of the track. The following (n + 1)-th line contains pairs of integers (xi, yi) ( - 10 000 ≤ xi, yi ≤ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi, yi) and ends at the point (xi + 1, yi + 1). It is guaranteed that:   the first straight section is directed to the north;  the southernmost (and if there are several, then the most western of among them) point of the track is the first point;  the last point coincides with the first one (i.e., the start position);  any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point);  no pair of points (except for the first and last one) is the same;  no two adjacent straight sections are directed in the same direction or in opposite directions.

Print a single integer — the number of dangerous turns on the track.

NoteThe first sample corresponds to the picture:  The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((n - 4) / 2)
}

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

object _659D extends CodeForcesApp {
  override def apply(io: IO) = {
    val path = io[Vector[(Int, Int)]]

    val lake = {
      val (xs, ys) = path.unzip
      new java.awt.Polygon(xs.toArray, ys.toArray, path.length)
    }

    val ans = path sliding 2 count {case Vector((x1, y1), (x2, y2)) =>
      val (dx, dy) = ((x1 - x2).signum, (y1 - y2).signum)
      val (x, y) = (x1.toDouble + 0.5*dx, y1.toDouble + 0.5*dy)
      lake.contains(x, y)
    }

    io += 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 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 = t.head.ensuring(t.size == 1)
    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 sum[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
  }
  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 PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).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 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 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 LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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 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(n.min(x, y), n.max(x, y), n.one)
  }
  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] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline 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)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val newLine: String = "\n"
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def appendNewLine(): this.type = {
    println()
    this
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

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

object _659D extends CodeForcesApp {
  override def apply(io: IO) = {
    val path = io[Vector[(Int, Int)]]
    val n = path.length
    val dirs = (path.sliding(2) map {case Vector((x1, y1), (x2, y2)) =>
      ((x2 - x1).signum, (y2 - y1).signum) match {
        case ( 1, _) => Dir.East
        case (-1, _) => Dir.West
        case (_,  1) => Dir.North
        case (_, -1) => Dir.South
      }
    }).toIndexedSeq

    val lake = {
      val (xs, ys) = path.unzip
      new java.awt.Polygon(xs.toArray, ys.toArray, n)
    }

    val ans = (1 until n) count {i =>
      val x = path(i)._1.toDouble
      val y = path(i)._2.toDouble
      val (nx, ny) = dirs(i - 1) match {
        case Dir.North => (x, y + 0.5)
        case Dir.East => (x + 0.5, y)
        case Dir.West => (x - 0.5, y)
        case Dir.South => (x, y - 0.5)
      }
      //debug(x, y, dirs(i-1), nx, ny, lake.contains(nx, ny))
      lake.contains(nx, ny)
    }

    io += ans
  }

  object Dir extends Enumeration {
    val North, East, West, South = Value
  }
}
/****************************[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 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 = t.head.ensuring(t.size == 1)
    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 sum[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
  }
  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 PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).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 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 SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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 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(n.min(x, y), n.max(x, y), n.one)
  }
  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] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline 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)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val newLine: String = "\n"
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def appendNewLine(): this.type = {
    println()
    this
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


Given a set of integers (it can contain equal elements).You have to split it into two subsets $$$A$$$ and $$$B$$$ (both of them can contain equal elements or be empty). You have to maximize the value of $$$mex(A)+mex(B)$$$.Here $$$mex$$$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:   $$$mex(\{1,4,0,2,2,1\})=3$$$  $$$mex(\{3,3,2,1,3,0,0\})=4$$$  $$$mex(\varnothing)=0$$$ ($$$mex$$$ for empty set) The set is splitted into two subsets $$$A$$$ and $$$B$$$ if for any integer number $$$x$$$ the number of occurrences of $$$x$$$ into this set is equal to the sum of the number of occurrences of $$$x$$$ into $$$A$$$ and the number of occurrences of $$$x$$$ into $$$B$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\leq n\leq 100$$$) — the size of the set. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots a_n$$$ ($$$0\leq a_i\leq 100$$$) — the numbers in the set.

For each test case, print the maximum value of $$$mex(A)+mex(B)$$$.

NoteIn the first test case, $$$A=\left\{0,1,2\right\},B=\left\{0,1,5\right\}$$$ is a possible choice.In the second test case, $$$A=\left\{0,1,2\right\},B=\varnothing$$$ is a possible choice.In the third test case, $$$A=\left\{0,1,2\right\},B=\left\{0\right\}$$$ is a possible choice.In the fourth test case, $$$A=\left\{1,3,5\right\},B=\left\{2,4,6\right\}$$$ is a possible choice.

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

  val t = readInt()

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

    @annotation.tailrec
    def go(an: Seq[Int], a: Int, b: Int): Int =
      an match {
        case Seq() => a + b + 2
        case Seq(h, t @ _*) =>
          if (a + 1 == h) go(t, h, b)
          else if (b + 1 == h) go(t, a, h)
          else if (a == h || b == h) go(t, a, b)
          else go(Seq.empty[Int], a, b)
      }

    val ans = go(an.sorted, -1, -1)

    println(ans)
  }
}

object AFunctional extends App {

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

  for (_ <- (0 until t)) {
    val n = scala.io.StdIn.readInt()

    val arrStr = scala.io.StdIn.readLine()
    val stdInArr: Array[Int] = arrStr.split(" ").map(_.toInt)

    println(mex(stdInArr))

  }

  def mex(stdInArr: Array[Int]): Int = {
    val n = stdInArr.length

    val intMap = stdInArr.foldLeft(Map.empty[Int, Int]) {
      (map: Map[Int, Int], b: Int) => {
        map - b + (b -> (map.getOrElse(b, 0) + 1))
      }
    }

    val startAdder = 2
    (0 until n).foldLeft((0, startAdder)) {
      (mexSum_adder: (Int, Int), k: Int) => {
        val mexSum = mexSum_adder._1
        val adder = mexSum_adder._2

        val newAdder = intMap.get(k) match {
          case Some(count) if count >= 2 =>
            adder
          case Some(count) if count == 1 =>
            if (adder > 1) {
              1
            } else adder
          case _ => 0
        }

        (mexSum + newAdder, newAdder)

      }
    }
  }._1

}

object A extends App {
  import scala.collection.mutable

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

  for (_ <- (0 until  t)) {
    val n = scala.io.StdIn.readInt()

    val arrStr = scala.io.StdIn.readLine()
    val stdInArr = arrStr.split(" ").map(_.toInt)

    val intMap = mutable.Map.empty[Int, Int]

    for (a <- stdInArr) {
      intMap.put(a, intMap.getOrElse(a, 0) + 1)
    }

    var mexSum = 0

    var breakIf = false

    var adder = 2

    for (k <- 0 until n) {
        intMap.get(k) match {
          case Some(count) if count >= 2 =>

          case Some(count) if count == 1 =>
            if(adder>1){
              adder = 1
            }
          case _ =>
            adder = 0
        }

        mexSum += adder
    }

    println(mexSum)

  }

}

import scala.collection.mutable.ArrayBuffer

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m    = in.nextInt()
      val data = in.nextLineInt(m).sorted
      val map  = data.groupBy(x => x).map(x => (x._1 -> x._2.length))
//      println(map)
      val n1 = 0.to(100).find(x => map.get(x).isEmpty).getOrElse(0)
      val map2 = map
        .collect {
          case (n, v) if n < n1 => (n -> (v - 1))
          case (n, v)           => (n -> v)
        }
        .filter(x => x._2 > 0)

//      println(map2)
      val n2 = 0.to(100).find(x => map2.get(x).isEmpty).getOrElse(0)
//      println(n1, n2)
      println(n1 + n2)
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

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

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

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

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

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

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

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

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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