In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.

The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.

In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.

NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.

import scala.collection.mutable.ListBuffer

object E {
  def main(args: Array[String]) {
    var Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val a = scala.io.StdIn.readLine.split(" ").map(_.toInt).sorted
    var k = 1
    val res = ListBuffer[Int]()
    var t = a(0)
    var i = 0
    while (k <= m){
      if (k != t){
        res += k
        m -= k
      } else {
        i += 1
        if (i < a.length){
          t = a(i)
        }
      }
      k += 1
    }
    val rr = res.result()
    println(rr.length)
    println(rr.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt).toSet
  var result = List.empty[Int]
  var i = 1
  while (m >= i) {
    if (!data.contains(i)) {
      result ::= i
      m -= i
    }
    i += 1
  }
  println(result.length)
  println(result.mkString(" "))
}

object C659 {

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

  def main(args: Array[String]): Unit = {
    var Array(n, m) = readInts(2)
    val a = Array(0) ++ readInts(n).sorted
    val res = cu.ArrayBuffer.empty[Int]

    var curr = 0L
    var max = a.max + 1
    for(i <- 1 to n if m > 0) {
      if(a(i) > a(i-1)+1) {
        var x = a(i-1)+1
        while(x < a(i) && curr + x <= m) {
          res.append(x)
          m -= x
          x += 1
        }
      }
    }
    while(max + curr <= m) {
      res.append(max)
      m -= max
      max += 1
    }
    println(res.length)
    println(res.mkString(" "))
  }

  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 scala.io.StdIn
import scala.collection.mutable.ListBuffer

object Main {
  def main(args: Array[String]) {
    val (n, m) = StdIn.readLine.split(" ").map(_.toInt) match {
      case xy: Array[Int] => (xy(0), xy(1))
    }
    val a = StdIn.readLine.split(" ").map(_.toInt).toSet
    var picks = new ListBuffer[Int]()
    var cost = 0
    var i = 1
    while (cost <= m) {
      // println(i, cost)
      if (!a.contains(i)) { // pick
        picks.append(i)
        cost += i
      }
      i += 1
    }
    val ans = picks.init.toList
    println(ans.length)
    println(ans.mkString(" "))
  }

}

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

object _659C extends CodeForcesApp {
  override def apply(io: IO) = {
    var n, m = io[Int]
    val has = io[Set, Int](n)
    var ans = Vector.empty[Int]

    var t = 1
    while(m >= t) {
      if(!has(t)) {
        ans = ans :+ t
        m -= t
      }
      t += 1
    }

    io.+=(ans.length).appendNewLine().+=(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)
  }
  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 scala.collection.mutable.ListBuffer

object E {
  def main(args: Array[String]) {
    var Array(n, m) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val a = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    var suma = a.sum
    var k = 1
    val res = ListBuffer[Int]()
    var t = a(0)
    var i = 0
    while (k <= m){
      if (k != t){
        res += k
        m -= k
      } else {
        i += 1
        if (i < a.length){
          t = a(i)
        }
      }
      k += 1
    }
    val rr = res.result()
    println(rr.length)
    println(rr.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  var Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt).toSet
  var result = List.empty[Int]
  var i = 1
  while (m >= i) {
    if (!data.contains(i)) {
      result ::= i
      m -= i
    }
    i += 1
  }
  println(result.mkString(" "))
}

object C659 {

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

  def main(args: Array[String]): Unit = {
    var Array(n, m) = readInts(2)
    val a = Array(0) ++ readInts(n).sorted
    val res = cu.ArrayBuffer.empty[Int]

    var curr = 0L
    var max = a.max + 1
    for(i <- 1 until n if m > 0) {
      if(a(i) > a(i-1)+1) {
        var x = a(i-1)+1
        while(x < a(i) && curr + x <= m) {
          res.append(x)
          m -= x
          x += 1
        }
      }
    }
    while(max + curr <= m) {
      res.append(max)
      m -= max
      max += 1
    }
    println(res.length)
    println(res.mkString(" "))
  }

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

}


Paprika loves permutations. She has an array $$$a_1, a_2, \dots, a_n$$$. She wants to make the array a permutation of integers $$$1$$$ to $$$n$$$.In order to achieve this goal, she can perform operations on the array. In each operation she can choose two integers $$$i$$$ ($$$1 \le i \le n$$$) and $$$x$$$ ($$$x > 0$$$), then perform $$$a_i := a_i \bmod x$$$ (that is, replace $$$a_i$$$ by the remainder of $$$a_i$$$ divided by $$$x$$$). In different operations, the chosen $$$i$$$ and $$$x$$$ can be different.Determine the minimum number of operations needed to make the array a permutation of integers $$$1$$$ to $$$n$$$. If it is impossible, output $$$-1$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output the minimum number of operations needed to make the array a permutation of integers $$$1$$$ to $$$n$$$, or $$$-1$$$ if it is impossible.

NoteFor the first test, the only possible sequence of operations which minimizes the number of operations is:   Choose $$$i=2$$$, $$$x=5$$$. Perform $$$a_2 := a_2 \bmod 5 = 2$$$. For the second test, it is impossible to obtain a permutation of integers from $$$1$$$ to $$$n$$$.

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val integerNumber = readInt()
    val numbers = readInts()

    val remainingNumbers = new MutableMultiSet[Int](numbers)

    @tailrec
    def findAnswer(testNumber: Int, answer: Int): Int = (testNumber, answer) match {
      case (0, answer) => answer
      case (testNumber, -1) => findAnswer(testNumber - 1, -1)
      case (testNumber, answer) => if (remainingNumbers.contains(testNumber)) {
        remainingNumbers.remove(testNumber)
        findAnswer(testNumber - 1, answer)
      } else {
        val maxValue = remainingNumbers.max
        if (maxValue >= testNumber * 2 + 1) {
          remainingNumbers.remove(maxValue)
          findAnswer(testNumber - 1, answer + 1)
        } else {
          findAnswer(testNumber - 1, - 1)
        }
      }
    }

    println(findAnswer(integerNumber, 0))
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $$$n$$$ high school students numbered from $$$1$$$ to $$$n$$$. Initially, each student $$$i$$$ is on position $$$i$$$. Each student $$$i$$$ is characterized by two numbers — $$$a_i$$$ and $$$b_i$$$. Dissatisfaction of the person $$$i$$$ equals the product of $$$a_i$$$ by the number of people standing to the left of his position, add the product $$$b_i$$$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $$$i$$$, which is on the position $$$j$$$, equals $$$a_i \cdot (j-1) + b_i \cdot (n-j)$$$.The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.Although Stas is able to solve such problems, this was not given to him. He turned for help to you.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of people in the queue. Each of the following $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 10^8$$$) — the characteristic of the student $$$i$$$, initially on the position $$$i$$$.

Output one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.

NoteIn the first example it is optimal to put people in this order: ($$$3, 1, 2$$$). The first person is in the position of $$$2$$$, then his dissatisfaction will be equal to $$$4 \cdot 1+2 \cdot 1=6$$$. The second person is in the position of $$$3$$$, his dissatisfaction will be equal to $$$2 \cdot 2+3 \cdot 0=4$$$. The third person is in the position of $$$1$$$, his dissatisfaction will be equal to $$$6 \cdot 0+1 \cdot 2=2$$$. The total dissatisfaction will be $$$12$$$.In the second example, you need to put people in this order: ($$$3, 2, 4, 1$$$). The total dissatisfaction will be $$$25$$$.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer
  import java.util.Arrays.sort

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N = ni()
    val (a, b) = na2(N)
    case class Entry(v: Int, pos: Int)

    val E = Array.ofDim[Entry](N)
    REP(N) { i =>
      E(i) = Entry(b(i) - a(i), i)
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o1.v, o2.v)
    })
    debug(E.mkString(" "))

    var ans = 0L
    REP(N) { i =>
      val p = E(i).pos
      val j = i + 1
      debug(s"a:${a(p)} b:${b(p)}, j:$j (j - 1):${(j - 1)} (N - j):${(N - j)}")
      ans += a(p).toLong * (j - 1) + b(p).toLong * (N - j)
      debug(s"ans:$ans")
    }
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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


For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \le j < d$$$ and $$$d < j \le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \le j \le n$$$.Help mayor find the earliest not-so-rainy day of summer.

The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le x, y \le 7$$$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains $$$n$$$ distinct integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ denotes the rain amount on the $$$i$$$-th day.

Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.

NoteIn the first example days $$$3$$$ and $$$8$$$ are not-so-rainy. The $$$3$$$-rd day is earlier.In the second example day $$$3$$$ is not not-so-rainy, because $$$3 + y = 6$$$ and $$$a_3 > a_6$$$. Thus, day $$$8$$$ is the answer. Note that $$$8 + y = 11$$$, but we don't consider day $$$11$$$, because it is not summer.

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

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

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

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

  def solve(): Unit = {
    val N, X, Y = ni()
    val A = na(N)
    REP(N) { i =>
      var ok = true
      REP(X, 1) { j =>
        if (i - j >= 0) {
          ok &&= A(i) < A(i - j)
        }
      }
      REP(Y, 1) { j =>
        if (i + j < N) {
          ok &&= A(i) < A(i + j)
        }
      }
      if (ok) {
        out.println(i + 1)
        return
      }
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val n, x, y = io.read[Int]
    val as = io.read[Vector, Int](n)

    val ans = as.indices find {i =>
      val a = as(i)
      (max(i - x, 0) until i).forall(j => a < as(j)) &&
      ((i+1) to min(i + y, n - 1)).forall(j => a < as(j))
    }

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

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

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

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

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

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

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

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

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

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

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

import scala.math.min
import scala.math.max
import scala.util.control.Breaks._

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

object A{
	def main(args: Array[String]) = {
		var br = new BufferedReader(new InputStreamReader(System.in));
        	var a = br.readLine().split(" ")
		var n: Int = a(0).toInt
		var x: Int = a(1).toInt
		var y: Int = a(2).toInt
		var b = br.readLine().split(" ")
		var c: Array[Int] = new Array[Int](n)
		var i = 0
		for(i <- 0 to n-1)
		{
			c(i) = b(i).toInt
		}
		var ans: Int = -1
		for(i <- 0 to n-1)
		{
			var f: Int = 0
			var j: Int = 0
			for(j <- max(0,i-x) to min(i+y,n-1) )
			{
				if(j!=i && c(i)>=c(j))
					f=1
			}
			if(f==0)
			{
				if(ans equals -1)
					ans = i
			}
		}
		println(ans+1)
	}
}


You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val ps = nextInts(n)
      val res = new mutable.ArrayBuilder.ofInt

      val sorted = new java.util.TreeMap[Int, Int]
      for (i <- ps.indices) {
        sorted.put(ps(i), i)
      }
      var right = n
      while (!sorted.isEmpty) {
        val idx = sorted.lastEntry().getValue
        for (i <- idx until right) {
          res += ps(i)
          sorted.remove(ps(i))
        }
        right = idx
      }

      out.println(res.result().mkString(" "))
    }

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


In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.

The first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John. The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.

Print the minimum possible distance between Farmer John's room and his farthest cow.

NoteIn the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.

object E {
  def main(args: Array[String]) {
    val Array(n, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val hotel = scala.io.StdIn.readLine.zipWithIndex
    val rooms = hotel.filter(_._1 == '0').map(_._2)
    var s = 0
    var e = k
    var x1 = 0
    var x2 = 1
    var zeros = 0
    var mmin = 100000
    while (s < rooms.length - k){
      while (!((2*rooms(x1) < rooms(s)+rooms(e)) && (2*rooms(x2) >= rooms(s)+rooms(e)))){
        x1 += 1
        x2 += 1
      }
      if ((rooms(e) - rooms(x1)) < mmin){
        mmin = rooms(e)-rooms(x1)
      }
      if ((rooms(x2) - rooms(s)) < mmin){
        mmin = rooms(x2) - rooms(s)
      }
      e += 1
      s += 1
    }
    println(mmin)
  }
}

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, k) = readInts(2)
  val rooms = readLine

  var min = Int.MaxValue
  var left = 0

  while (rooms(left) == '1') left += 1
  var right = left
  var mid = left
  var cnt = 0

  while (cnt < k) {
    right += 1
    if (rooms(right) == '0') cnt += 1
  }

  def toLeft = mid - left
  def toRight = right - mid

  while (toLeft < toRight) {
    mid += 1
    if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
  }
  while (mid < n && rooms(mid) == '1') mid += 1

  while (right < n) {
    if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
    right += 1
    while (right < n && rooms(right) == '1') right += 1
    if (right < n) {
      left += 1
      while (rooms(left) == '1') left += 1
      if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
      while (toLeft < toRight) {
        mid += 1
        if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
      }
      while (mid < n && rooms(mid) == '1') mid += 1
    }
  }

  if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))

  println(min)
}

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, k) = readInts(2)
  val rooms = readLine

  var min = Int.MaxValue
  var left = 0

  while (rooms(left) == '1') left += 1
  var right = left
  var mid = left
  var cnt = 0

  while (cnt < k) {
    right += 1
    if (rooms(right) == '0') cnt += 1
  }

  def toLeft = mid - left
  def toRight = right - mid

  while (toLeft < toRight || rooms(mid) == '1') mid += 1

  while (right < n) {
    if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
    right += 1
    while (right < n && rooms(right) == '1') right += 1
    if (right < n) {
      left += 1
      if (rooms(mid) == '0') while (rooms(left) == '1') left += 1
      min = math.min(min, math.max(toLeft, toRight))
      while (toLeft < toRight) {
        mid += 1
        if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
      }
    }
  }

  if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))

  println(min)
}

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, k) = readInts(2)
  val rooms = readLine

  var min = Int.MaxValue
  var left = 0

  while (rooms(left) == '1') left += 1
  var right = left
  var mid = left
  var cnt = 0

  while (cnt < k) {
    right += 1
    if (rooms(right) == '0') cnt += 1
  }

  def toLeft = mid - left
  def toRight = right - mid

  while (toLeft < toRight || rooms(mid) == '1') mid += 1

  while (right < n) {
    min = math.min(min, math.max(toLeft, toRight))
    right += 1
    while (right < n && rooms(right) == '1') right += 1
    if (right < n) {
      left += 1
      while (rooms(left) == '1') left += 1
      min = math.min(min, math.max(toLeft, toRight))
      while (toLeft < toRight || rooms(mid) == '1') mid += 1
    }
  }

  min = math.min(min, math.max(toLeft, toRight))

  println(min)
}

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, k) = readInts(2)
  val rooms = readLine

  var min = Int.MaxValue
  var left = 0

  while (rooms(left) == '1') left += 1
  var right = left
  var mid = left
  var cnt = 0

  while (cnt < k) {
    right += 1
    if (rooms(right) == '0') cnt += 1
  }

  def toLeft = mid - left
  def toRight = right - mid

  while (toLeft < toRight || rooms(mid) == '1') mid += 1

  while (right < n) {
    if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
    right += 1
    while (right < n && rooms(right) == '1') right += 1
    if (right < n) {
      left += 1
      if (rooms(mid) == '0') while (rooms(left) == '1') left += 1
      min = math.min(min, math.max(toLeft, toRight))
      while (toLeft < toRight) {
        mid += 1
        if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))
      }
      while (mid < n && rooms(mid) == '1') mid += 1
    }
  }

  if (rooms(mid) == '0') min = math.min(min, math.max(toLeft, toRight))

  println(min)
}


Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types:   easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem;  hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then:  if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems;  if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems;  if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$);  if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;  if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them;  if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam.

The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases.  The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$.

Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam.

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

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

  private[this] val oj = System.getenv("MY_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = {
    if (!oj){ System.err.println(s) }
  }
  def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

    private[this] 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
  }
}

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

  class Entry(var easy: Int, var hard: Int)
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, T = ni()
      val A, B = nl()
      val isEasy = na(N).map(_ == 0)
      val cntE = isEasy.count(identity)
      val cntH = N - cntE
      val E = new java.util.TreeMap[Int, Entry]
      REP(N) { i =>
        val t = ni()
        if (!E.containsKey(t)) {
          E.put(t, new Entry(0, 0))
        }
        if (isEasy(i)) E.get(t).easy += 1
        else E.get(t).hard += 1
      }

      val n = E.size()
      val cumE, cumH = Array.ofDim[Int](n + 1)
      var i = 0
      val it = E.entrySet().iterator()
      val time = Array.ofDim[Int](n)
      while(it.hasNext) {
        val e = it.next()
        cumE(i + 1) = cumE(i) + e.getValue.easy
        cumH(i + 1) = cumH(i) + e.getValue.hard
        time(i) = e.getKey
        i += 1
      }
      debug(cumE)
      debug(cumH)
      debug(time)

      var ans = 0

      def calc(lst: Int, manT: Long, cumE: Int, cumH: Int): Int = {
        var remainT = lst - manT
        var v = cumE + cumH
        debug(s"manT:$manT lst:$lst remainT:$remainT v:$v")
        if (remainT >= 0) {
          val remainE = cntE - cumE
          val cnt = min(remainE, (remainT / A).toInt)
          v += cnt
          remainT -= A * cnt
          if (remainT >= 0) {
            val remainH = cntH - cumH
            val cnt = min(remainH, (remainT / B).toInt)
            v += cnt
            remainT -= B * cnt
          }
          v
        } else {
          0
        }
      }

      // [0, t1)のケース
      ans = max(ans, calc(time(0)-1, 0, 0, 0))
      REP(n) { i =>
        val manT = cumE(i + 1) * A + cumH(i + 1) * B
        val lst = if (i == n - 1) T else time(i + 1) - 1
        ans = max(ans, calc(lst, manT, cumE(i + 1), cumH(i + 1)))
      }
      out.println(ans)
    }
  }
}


Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

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

/**
 * Created by arseny on 15.08.14.
 */
object B extends App {

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val bs = Array.fill(n)(0L)
    (0 until n).foreach(i => bs(i) = nextLong)
    val sorted = bs.sorted
    val minBeauty = sorted(0)
    val maxBeauty = sorted(n - 1)
    var maxDiff = maxBeauty - minBeauty
    var minCount = 0L
    var maxCount = 0L
    while (minCount < n && sorted(minCount.toInt) == minBeauty) {
      minCount += 1L
    }
    while (maxCount < n && sorted(n - 1 - maxCount.toInt) == maxBeauty) {
      maxCount += 1L
    }
    val maxDiffCount = if(minBeauty == maxBeauty) n.toLong * (n.toLong - 1) / 2L else maxCount * minCount
    out.print(maxDiff + " " + maxDiffCount)
  }

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

import java.util.StringTokenizer

object _459B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val max = a.max
  val min = a.min
  if (max == min) {
    println("%d %d".format(0, 1L * a.length * (a.length - 1) / 2))
  } else {
    println("%d %d".format(max - min, 1L * a.count(i => i == max) * a.count(i => i == min)))
  }
}

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

  val Array(n) = readInts(1)
  val b = readInts(n.toInt)

  val maxb = b.max
  val minb = b.min

  val nmax:Long = b.filter(_ == maxb).length
  val nmin:Long = b.filter(_ == minb).length

  val r:Long = maxb - minb
  val result = nmax * nmin

  val rcases:Long = if(maxb != minb){
    nmax * nmin
  } else {
    nmax * (nmax - 1) / 2L
  }
  println(s"$r $rcases")
}

object B459 {
  @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 = readInts(n)

    val max = input.max
    val min = input.min

    val ways = if(min == max) {
      val count = input.count(_ == max).toLong
      (count*(count-1))/2L
    } else {
      input.count(_ == max).toLong * input.count(_ == min).toLong
    }

    println(s"${max-min} $ways")
  }
}

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object B459 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var min = Integer.MAX_VALUE
  var minCount = 1
  var max = 0
  var maxCount = 1
  a.foreach(b => {
    if (min > b) {
      min = b
      minCount = 1
    } else if (min == b) {
      minCount += 1
    }
    if (max < b) {
      max = b
      maxCount = 1
    } else if (max == b) {
      maxCount += 1
    }
  })

  print(max - min)
  print(" ")
  if (max == min) {
    println(1L * maxCount * (maxCount - 1) / 2)
  } else {
    println(1L * maxCount * minCount)
  }

}

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val b = new Array[Long](n)
    var max: Long = Long.MinValue
    var min: Long = Long.MaxValue
    for (i <- 0 until n) {
      b(i) = nextLong
      max = Math.max(max, b(i))
      min = Math.min(min, b(i))
    }
    var maxN: Long = 0L
    var minN: Long = 0L
    out.print(Math.abs(max - min) + " ")
    for (i <- 0 until n) {
      if (b(i) == max) {
        maxN += 1
      }
      if (b(i) == min) {
        minN += 1
      }
    }
    if (max != min) {
      out.print(maxN * minN * 1L)
    } else {
      out.print((maxN * 1L * (maxN * 1L - 1L)) / 2L)
    }
    return 1
  }

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

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val b = new Array[Int](n)
    var max = Int.MinValue
    var min = Int.MaxValue
    for (i <- 0 until n) {
      b(i) = nextInt
      max = Math.max(max, b(i))
      min = Math.min(min, b(i))
    }
    var maxN = 0
    var minN = 0
    out.print(Math.abs(max - min) + " ")
    for (i <- 0 until n) {
      if (b(i) == max) {
        maxN += 1
      }
      if (b(i) == min) {
        minN += 1
      }
    }
    if (max != min) {
      out.print(maxN.toLong * minN.toLong)
    } else {
      out.print((maxN.toLong * (maxN.toLong - 1)) / 2)
    }
    return 1
  }

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

import scala.io.StdIn
import scala.util.Sorting

object PashmakFlowers {

  def pashmakFlowers(inputA:Array[Int]):String = {
    Sorting.quickSort(inputA)
    val cnt:Int = inputA.length
    if (cnt>1){
      val small = inputA(0);
      val large = inputA(cnt-1)
      if (small == large){
        0 + " " + cnt.toLong*(cnt-1).toLong/2
      }else{
        var sc=0
        while(inputA(sc)==small){
          sc = sc + 1
        }
        var lc=0
        while(inputA(cnt-1-lc)==large){
          lc = lc + 1
        }
        val comb:Long = sc.toLong * lc.toLong
        large-small + " " + comb
      }
    }else{
      "Error Input: Input has less then 2 numbers"
    }
  }

  def pashmakFlowers(num:Int, ln2:String):String = {
    val input = ln2.split(" ");
    val inputA:Array[Int] = new Array(num);
    for (a<-1 to num){
      inputA(a-1)=input(a-1).toInt
    }
    pashmakFlowers(inputA)
  }
  def main(args: Array[String]) {
    val ln1:String = StdIn.readLine()
    val ln2:String = StdIn.readLine()
    val num = ln1.toInt
    println(pashmakFlowers(num, ln2))
  }

}

import java.util.InputMismatchException
import java.io.InputStream

/**
 * Created by hama_du on 2014/08/24.
 */
object ProblemB extends App {
  val in = new InputReader(System.in)

  val n = in.nextInt()
  val f = (0 until n).map(_ => in.nextInt())
  val min = f.min
  val max = f.max
  val minCount: Long = f.count(b => b == min)
  val maxCount: Long = f.count(b => b == max)
  if (min == max) {
    println(0 + " " + (1L * n * (n - 1) / 2))
  } else {
    println((max - min) + " " + minCount * maxCount)
  }
}

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

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

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

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

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

object Main {
  def main(args: Array[String]): Unit = {
    io.StdIn.readLine()
    sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))
  }

  def sol(bs: Array[Int]): Unit = {
    def extrema(nums: List[Int]): (Int, Int, Int, Int) = {
      ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>
        val _min = math.min(e._1, b)
        val _max = math.max(e._3, b)
        val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2
        val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4
        (_min, minCount, _max, maxCount)
      }
    }
    extrema(bs.toList) match {
      case (x, y, z, w) =>
        println(s"${z-x} ${if (z == x) y.toLong * (y - 1) / 2  else y.toLong * w}")
    }
  }
}

object main extends App with fastIO {

  val Array(n) = readLine split(" ") map(_.toLong)
  var a = readLine split(" ") map(_.toInt)

  val (max, min) = (a.max, a.min)
  val res = if (max == min) n * (n - 1) / 2 else
    a.count(_ == min).toLong * a.count(_ == max).toLong

  println((max - min) + " " + res)
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

  val Array(n) = readInts(1)
  val b = readInts(n.toInt)

  val maxb = b.max
  val minb = b.min

  val nmax = b.filter(_ == maxb).length
  val nmin = b.filter(_ == minb).length

  val r = maxb - minb
  val rcases = if(maxb != minb){
    nmax * nmin
  } else {
    nmax * (nmax - 1) / 2
  }
  println(s"$r $rcases")
}

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

  val Array(n) = readInts(1)
  val b = readInts(n.toInt)

  val maxb = b.max
  val minb = b.min

  val nmax = b.filter(_ == maxb).length
  val nmin = b.filter(_ == minb).length

  val r:Long = maxb - minb
  val result = nmax * nmin

  if(n==200000){
    println(s"$maxb $minb $nmax $nmin $r $result")
    println(result)
  }

  val rcases:Long = if(maxb != minb){
    nmax * nmin
  } else {
    nmax * (nmax - 1) / 2L
  }
  println(s"$r $rcases")
}

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

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

  val maxb = b.max
  val minb = b.min

  val nmax = b.filter(_ == maxb).length
  val nmin = b.filter(_ == minb).length

  val r = maxb - minb
  val rcases = nmax * nmin
  println(s"$r $rcases")
}

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

  val Array(n) = readInts(1)
  val b = readInts(n.toInt)

  val maxb = b.max
  val minb = b.min

  val nmax = b.filter(_ == maxb).length
  val nmin = b.filter(_ == minb).length

  val r:Long = maxb - minb

  val rcases:Long = if(maxb != minb){
    nmax * nmin
  } else {
    nmax * (nmax - 1) / 2L
  }
  println(s"$r $rcases")
}

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_2 extends App {
  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)

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

  val Array(n) = readInts(1)
  val b = readInts(n.toInt)

  val maxb = b.max
  val minb = b.min

  val nmax = b.filter(_ == maxb).length
  val nmin = b.filter(_ == minb).length

  val r:Long = maxb - minb
  if(n==200000){
    println(s"$maxb $minb $nmax $nmin $r")
  }

  val rcases:Long = if(maxb != minb){
    nmax * nmin
  } else {
    nmax * (nmax - 1) / 2L
  }
  println(s"$r $rcases")
}

object B459 {
  @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 = readInts(n)

    val max = input.max
    val min = input.min

    val ways = if(min == max) {
      val count = input.count(_ == max).toLong
      (count*count-1)/2L
    } else {
      input.count(_ == max).toLong * input.count(_ == min).toLong
    }

    println(s"${max-min} $ways")
  }
}

object B459 {
  @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 = readInts(n)

    val max = input.max
    val min = input.min

    val ways = input.count(_ == max) * input.count(_ == min)

    println(s"${max-min} $ways")
  }
}

object B459 {
  @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 = readInts(n)

    val max = input.max
    val min = input.min

    val ways = input.count(_ == max).toLong * input.count(_ == min).toLong

    println(s"${max-min} $ways")
  }
}

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object B459 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var min = Integer.MAX_VALUE
  var minCount = 1
  var max = 0
  var maxCount = 1
  a.foreach(b => {
    if (min > b) {
      min = b
      minCount = 1
    } else if (min == b) {
      minCount += 1
    }
    if (max < b) {
      max = b
      maxCount = 1
    } else if (max == b) {
      maxCount += 1
    }
  })

  print(max - min)
  print(" ")
  println(1L * maxCount * minCount)

}

/**
 * @author pvasilyev
 * @since 05 May 2016
 */
object B459 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  var min = Integer.MAX_VALUE
  var minCount = 1
  var max = 0
  var maxCount = 1
  a.foreach(b => {
    if (min > b) {
      min = b
      minCount = 1
    } else if (min == b) {
      minCount += 1
    }
    if (max < b) {
      max = b
      maxCount = 1
    } else if (max == b) {
      maxCount += 1
    }
  })

  print(max - min)
  print(" ")
  println(maxCount * minCount)

}

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val b = new Array[Int](n)
    var max = Int.MinValue
    var min = Int.MaxValue
    for (i <- 0 until n) {
      b(i) = nextInt
      max = Math.max(max, b(i))
      min = Math.min(min, b(i))
    }
    var maxN = 0
    var minN = 0
    out.print((max - min) + " ")
    for (i <- 0 until n) {
      if (b(i) == max) {
        maxN += 1
      }
      if (b(i) == min) {
        minN += 1
      }
    }
    if (max - min > 0) {
      out.print(maxN * minN * 1L)
    } else {
      out.print((maxN * 1L * (maxN * 1L - 1L)) / 2L)
    }
    return 1
  }

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

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val b = new Array[Int](n)
    var max = Int.MinValue
    var min = Int.MaxValue
    for (i <- 0 until n) {
      b(i) = nextInt
      max = Math.max(max, b(i))
      min = Math.min(min, b(i))
    }
    var maxN = 0
    var minN = 0
    out.print(Math.abs(max - min) + " ")
    for (i <- 0 until n) {
      if (b(i) == max) {
        maxN += 1
      }
      if (b(i) == min) {
        minN += 1
      }
    }
    if (max != min) {
      out.print(maxN * minN * 1L)
    } else {
      out.print((maxN * 1L * (maxN * 1L - 1L)) / 2L)
    }
    return 1
  }

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

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

object B {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def solve: Int = {
    val n = nextInt
    val b = new Array[Int](n)
    var max = Int.MinValue
    var min = Int.MaxValue
    for (i <- 0 until n) {
      b(i) = nextInt
      max = Math.max(max, b(i))
      min = Math.min(min, b(i))
    }
    var maxN = 0
    var minN = 0
    out.print((max - min) + " ")
    for (i <- 0 until n) {
      if (b(i) == max) {
        maxN += 1
      }
      if (b(i) == min) {
        minN += 1
      }
    }
    if (max - min > 0) {
      out.print(maxN * minN * 1L)
    } else {
      out.print(maxN * 1L * (maxN - 1) / 2L)
    }
    return 1
  }

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

import scala.io.StdIn
import scala.util.Sorting

object PashmakFlowers {

  def pashmakFlowers(inputA:Array[Int]):String = {
    Sorting.quickSort(inputA)
    val cnt:Int = inputA.length
    if (cnt>1){
      val small = inputA(0);
      val large = inputA(cnt-1)
      if (small == large){
        0 + " " + cnt*(cnt-1)/2
      }else{
        var sc=0
        while(inputA(sc)==small){
          sc = sc + 1
        }
        var lc=0
        while(inputA(cnt-1-lc)==large){
          lc = lc + 1
        }
        large-small + " " + sc*lc
      }
    }else{
      "Error Input: Input has less then 2 numbers"
    }
  }

  def main(args: Array[String]) {
    val ln1:String = StdIn.readLine()
    val ln2:String = StdIn.readLine()
    val num = ln1.toInt
    val input = ln2.split(" ");
    val inputA:Array[Int] = new Array(num);
    for (a<-1 to num){
      inputA(a-1)=input(a-1).toInt
    }
    println(pashmakFlowers(inputA))
  }

}

import scala.io.StdIn
import scala.util.Sorting

object PashmakFlowers {

  def pashmakFlowers(inputA:Array[Int]):String = {
    Sorting.quickSort(inputA)
    val cnt:Int = inputA.length
    if (cnt>1){
      val small = inputA(0);
      val large = inputA(cnt-1)
      if (small == large){
        0 + " " + cnt*(cnt-1)/2
      }else{
        var sc=0
        while(inputA(sc)==small){
          sc = sc + 1
        }
        var lc=0
        while(inputA(cnt-1-lc)==large){
          lc = lc + 1
        }
        val comb:Long = sc.toLong * lc.toLong
        large-small + " " + comb
      }
    }else{
      "Error Input: Input has less then 2 numbers"
    }
  }

  def pashmakFlowers(num:Int, ln2:String):String = {
    val input = ln2.split(" ");
    val inputA:Array[Int] = new Array(num);
    for (a<-1 to num){
      inputA(a-1)=input(a-1).toInt
    }
    pashmakFlowers(inputA)
  }
  def main(args: Array[String]) {
    val ln1:String = StdIn.readLine()
    val ln2:String = StdIn.readLine()
    val num = ln1.toInt
    println(pashmakFlowers(num, ln2))
  }

}

object Main {
  def main(args: Array[String]): Unit = {
    io.StdIn.readLine()
    sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))
  }

  def sol(bs: Array[Int]): Unit = {
    def extrema(nums: List[Int]): (Int, Int, Int, Int) = {
      ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>
        val _min = math.min(e._1, b)
        val _max = math.max(e._3, b)
        val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2
        val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4
        (_min, minCount, _max, maxCount)
      }
    }
    extrema(bs.toList) match {
      case (x, y, z, w) =>
        println(s"${z-x} ${if (z == x) (if (y == 2) 1 else y.toLong*y/2) else y.toLong * w}")
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    io.StdIn.readLine()
    sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))
  }

  def sol(bs: Array[Int]): Unit = {
    def extrema(nums: List[Int]): (Int, Int, Int, Int) = {
      ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>
        val _min = math.min(e._1, b)
        val _max = math.max(e._3, b)
        val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2
        val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4
        (_min, minCount, _max, maxCount)
      }
    }
    extrema(bs.toList) match {
      case (x, y, z, w) =>
        println(s"${z-x} ${if (z == x) (if (y == 2) 1 else y) else y.toLong * w}")
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    io.StdIn.readLine()
    sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))
  }

  def sol(bs: Array[Int]): Unit = {
    def extrema(nums: List[Int]): (Int, Int, Int, Int) = {
      ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>
        val _min = math.min(e._1, b)
        val _max = math.max(e._3, b)
        val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2
        val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4
        (_min, minCount, _max, maxCount)
      }
    }
    extrema(bs.toList) match {
      case (x,y,z,w) =>
        println(s"${z-x} ${y*w}")
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    io.StdIn.readLine()
    sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))
  }

  def sol(bs: Array[Int]): Unit = {
    def extrema(nums: List[Int]): (Int, Int, Int, Int) = {
      ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>
        val _min = math.min(e._1, b)
        val _max = math.max(e._3, b)
        val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2
        val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4
        (_min, minCount, _max, maxCount)
      }
    }
    extrema(bs.toList) match {
      case (x,y,z,w) =>
        println(s"${z-x} ${y.toLong*w.toLong}")
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    io.StdIn.readLine()
    sol(io.StdIn.readLine().split(' ').map(Integer.parseInt(_)))
  }

  def sol(bs: Array[Int]): Unit = {
    def extrema(nums: List[Int]): (Int, Int, Int, Int) = {
      ((nums.head, 1, nums.head, 1) /: nums.tail) { (e, b) =>
        val _min = math.min(e._1, b)
        val _max = math.max(e._3, b)
        val minCount = if (_min != e._1) 1 else if (b == _min) e._2 + 1 else e._2
        val maxCount = if (_max != e._3) 1 else if (b == _max) e._4 + 1 else e._4
        (_min, minCount, _max, maxCount)
      }
    }
    extrema(bs.toList) match {
      case (x, y, z, w) =>
        println(s"${z-x} ${if (z == x) y else y.toLong * w}")
    }
  }
}

object main extends App with fastIO {

  val Array(n) = readLine split(" ") map(_.toInt)
  var a = readLine split(" ") map(_.toInt)

  val (max, min) = (a.max, a.min)
  val res = if (max == min) n * (n - 1) / 2 else
    a.count(_ == min) * a.count(_ == max)

  println((max - min) + " " + res)
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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


Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x < x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.

The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.

Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x < x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.

NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.

object B extends App {

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

  val s = readLine

  def isBad(l: Int, r: Int): Boolean = {
    var x = l
    var good = false
    while (x < r && !good) {
      var k = 1
      while (x + k + k < r && !good) {
        if (s(x) == s(x + k) && s(x) == s(x + k + k)) good = true
        k += 1
      }
      x += 1
    }
    !good
  }

  var res = s.length.toLong * (s.length - 1) / 2

  for (l <- 0 until s.length) {
    for (len <- 2 until 20) {
      if (l + len <= s.length && isBad(l, l + len)) {
        res -= 1
      }
    }
  }

  println(res)
}


A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).  Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of dice in the tower. The second line contains an integer x (1 ≤ x ≤ 6) — the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 ≤ ai, bi ≤ 6; ai ≠ bi) — the numbers Bob sees on the two sidelong faces of the i-th dice in the tower. Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.

Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val top = in.next().toInt
  val Array(l, r) = in.next().split(' ').map(_.toInt)
  val res = (2 to n).foldLeft((7 - top, Set(l, r, 7 - l, 7 - r, top).size == 5)) {
    case ((s, false), _) => (s, false)
    case ((s, true), _) =>
      val Array(l, r) = in.next().split(' ').map(_.toInt)
      val set = Set(l, r, s, 7 - l, 7 - r)
      if (set.size < 5)
        (s, false)
      else {
        val nt = (1 to 6).find(i => !set.contains(i)).get
        (nt, true)
      }
  }
  if (res._2)
    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.collection.immutable.Queue
import scala.util.Random

object P225A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N = sc.nextInt // the number of dice in the tower
  val X = sc.nextInt // the number on the top of the tower
  val AB = List.fill(N, 2)(sc.nextInt) // two side long faces-es

  def solve(): Unit = {

    @tailrec
    def loop(acc: Int, dices: List[List[Int]]): Unit = {
      dices match {
        case Nil              => out.println("YES")
        case List(x, y) :: ds => {
          val known = acc :: List(x, y, 7 - x, 7 - y)
          val rest = List.range(1, 7) diff known
          rest match {
            case r :: Nil => loop(r, ds)
            case _        => out.println("NO")
          }
        }
      }
    }

    loop(X, AB)
  }

  solve
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)
  def readLine = reader.readLine

  val n = readInt
  val x = readInt
  def ans = if((for(_ <- 1 to n) yield readInts.count(y => y == x || y == 7 - x)).sum == 0) "YES" else "NO"

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val up = readInt()
    val a = (1 to n) map (_ => readLine() split (" ") map (_.toInt))
    val s = Set[Int]() ++ (1 to 6)

    var low = 7 - up
    val r = a.foldLeft(true) { (ac, a0) =>
      val next = s - (a0(0), 7 - a0(0), a0(1), 7 - a0(1), low)
      if (next.size == 1) {
        low = next.toList(0)
        ac
      } else {
        false
      }
    }
    if (r) println("YES")
    else println("NO")
  }
}

object HelloWorld {
    def main (args: Array[String]) {
      val N = readInt
      val first = readInt
      var pred = 7-first
      var i = 0;
      var res = true
      while (i < N) {
        var s = readLine
        val tokens = s.split(" ")
        val one = tokens(0).toInt
        val two = tokens(1).toInt
        if (!((one != pred) && (two != pred) && (7-one != pred) && (7-two != pred))) res = false
        i+=1;
      }
      if (res) println("YES") else println("NO")
    }
  }

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val top = in.next().toInt
  val Array(l, r) = in.next().split(' ').map(_.toInt)
  val res = (2 to n).foldLeft((7 - top, Set(l, r, 7 - l, 7 - r, top).size == 5)) {
    case ((s, false), _) => (s, false)
    case ((s, true), _) =>
      val Array(l, r) = in.next().split(' ').map(_.toInt)
      val set = Set(l, r, s, 7 - l, s - r)
      if (set.size < 5)
        (s, false)
      else {
        val nt = (1 to 6).find(i => !set.contains(i)).get
        (nt, true)
      }
  }
  if (res._2)
    println("YES")
  else
    println("NO")
}

object HelloWorld {
    def main (args: Array[String]) {
      val N = readInt
      val first = readInt
      var pred = 7-first
      var i = 0;
      var res = true
      while (i < N) {
        var s = readLine
        val tokens = s.split(" ")
        val one = tokens(0).toInt
        val two = tokens(1).toInt
        if (!(one != pred) && (two != pred) && (7-one != pred) && (7-two != pred)) res = false
        i+=1;
      }
      if (res) println("YES") else println("NO")
    }
  }


Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares?

The first line contains four space-separated integers a1, a2, a3, a4 (0 ≤ a1, a2, a3, a4 ≤ 104). The second line contains string s (1 ≤ |s| ≤ 105), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.

Print a single integer — the total number of calories that Jury wastes.

object BlackSquareGame {
  def main(args: Array[String]): Unit = {
    val A = readLine.split(" ")
    val S = readLine
    var sum = 0
    S.foreach(c => {
      sum = sum + A(c.asDigit-1).toInt
    })
    println(sum)
  }

}

import java.util.StringTokenizer

object _431 extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val a = (0 until 4).map(i => next.toInt).toArray
  val s = next
  val ans = s.map(i => a(i - '0' - 1)).sum
  println(ans)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val call = in.next().split(" ").zipWithIndex.map {
    case(en, index) => (index + 1) -> en.toInt
  }.toMap
  println(in.next().map(t => call(t.asDigit)).sum)
}

//package codeblocks
import java.util.Scanner
object cf413A {
	def main(args : Array[String]) : Unit = {
	val scn = new Scanner(System.in)
	val caroli :List[Int] = {for(i <- 1 to 4 ) yield scn.nextInt}.toList
	val seq:List[Int] = scn.next.toList.map(_-'0')
	var sum =0
	seq.foreach(x=>sum+=caroli(x - 1))
	println(sum)

	}

//	def getResult(seq:List[Int],caroli:List[Int]):Int = {
//		val (head,tail) = seq.splitAt(4)
//		if(head.isEmpty) 0
//		else{
//
//			val place = getRightPlace(head,head.length)
//			if(place!=0)
//			{
//				val (shead,thead) = head splitAt place-1
//				caroli(place-1)+getResult(shead:::thead.tail:::tail,caroli)
//			}
//			else
//				0
//
//		}
//	}
//	def getRightPlace(xs:List[Int],n:Int ):Int = {
//		if(n == 0) 0
//
//		if(xs(n-1)==n) n
//		else getRightPlace(xs take n-1,n-1)
//
//	}

}

object B {

  def main(args: Array[String]): Unit = {
    var a = readLine.split(" ").map(_.toInt)
    var s = readLine
    var ans = 0;

    for (i <- 0 to s.length()-1)
    	if (s.charAt(i)=='1')
    		ans = ans + a(0)
    	else if (s.charAt(i)=='2')
    		ans = ans + a(1)
    	else if (s.charAt(i)=='3')
    		ans = ans + a(2)
    	else if (s.charAt(i)=='4')
    		ans = ans + a(3)
  println(ans)
  }

}

import java.util.Scanner

object ASquare extends App {

  val scanner = new Scanner(System.in)

  val cal = (0 until 4).map(i => scanner.nextInt())

  val in = scanner.next().map(_.toString.toInt)

  val res = in.foldLeft(0)((acc, i) => acc + cal(i - 1))

  println(res)

}

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

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

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

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

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

  def main(args: Array[String]): Unit = {
    val input = readInts(4)
    val strip = read
    println(strip.map(ch => input(ch - '1')).sum)
  }
}

import java.util.Scanner

/**
 * Created by hama_du on 2014/05/22.
 */
object ProblemA extends App {
  val in = new Scanner(System.in)
  val table = Array(in.nextInt, in.nextInt, in.nextInt, in.nextInt)
  val s = in.next().toCharArray.foldLeft(0)((a, b) => a + table(b-'1'))
  println(s)
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A431 extends App{
  val sc = new Scanner(System.in)
  val a1, a2, a3, a4 = sc.nextInt()
  val input = sc.next()

  println(input.toCharArray.map {
    case '1' => a1
    case '2' => a2
    case '3' => a3
    case '4' => a4
  }.sum)
}

object A {
  def main(args: Array[String]): Unit = {
    val a: Array[Int] = new Array[Int](4)
    val words:Array[String] = scala.io.StdIn.readLine().split(" ")
    for (i <- 0 to 3)
      a(i) = words(i).toInt
    val s = scala.io.StdIn.readLine()
    var res = 0
    val n = s.length()
    for (i <- 0 to n - 1) {
      val j = s.charAt(i).toInt - '1'
      res = res + a(j)
    }
    println(res)
  }
}

object main extends App with fastIO {

  var a = readLine split(" ") map(_.toInt)
  println(readLine.foldLeft(0)((s, c) => s + a(c - '1')))

  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

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

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

/**
 * Created by Amit on 5/21/2014.
 */
object Testing {
  def main (args: Array[String]) {
    val first = Console.readLine()
    val nums = first.split(" ")
    val str = Console.readLine()
    var count = 0
    for(c <- str){
      count += nums(c-49).toInt
    }
    println(count)
  }
}