Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.

First line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1 ≤ n ≤ 1000), the number of days. Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person. The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.

Output n + 1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (n + 1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.

ross rachel
4
ross joey
rachel phoebe
phoebe monica
monica chandler

ross rachel
joey rachel
joey phoebe
joey monica
joey chandler

NoteIn first example, the killer starts with ross and rachel.   After day 1, ross is killed and joey appears.  After day 2, rachel is killed and phoebe appears.  After day 3, phoebe is killed and monica appears.  After day 4, monica is killed and chandler appears.

//package solutions

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

import scala.collection.mutable

/**
  * @author traff
  */

object SolTaskA extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def run(s: Scanner, out: PrintWriter): Unit = {

    val Array(v, r) = s.nextLine().split(" ")

    out.println(s"$v $r")

    val n = s.nextLine().toInt

    val a = new Array[String](n)

    val map = new mutable.HashMap[String, Int]()

    val set = new mutable.HashSet[String]()

    set.add(r)
    set.add(v)
    map(r) = 0
    map(v) = 0

    for (i <- 1 to n) {
      val Array(v, r) = s.nextLine().split(" ")
      a(i-1) = v
      map(r) = i
      set += v
      set += r
    }

    for (i <- 0 until n) {
      map.remove(a(i))
      set.remove(a(i))

      if (i >0) {
        var min = n
        var name = ""
        set.foreach(f => {
          val l = map.getOrElse(f, 0)
          if (l < min) {
            min = l
            name = f
          }
        })

        out.println(s"${a(i)} $name")
      }
    }

    val i = set.iterator

    out.println(s"${i.next()} ${i.next()}")
  }
}

import collection.mutable.ListBuffer

object Serial {
  def main(args : Array[String]) {
    var ans = new ListBuffer[String]
    val tok = io.StdIn.readLine.split(" ")
    var a = tok(0)
    var b = tok(1)
    val n = io.StdIn.readLine.toInt
    ans.append(a)
    ans.append(b)
    for (i<-1 to n) {
      val tok = io.StdIn.readLine.split(" ")
      if (tok(0) == a) a = tok(1)
      else b = tok(1)
      ans.append(a)
      ans.append(b)
    }
    for (i<-0 to n) {
      println(ans(i*2).toString + " " +  ans(i*2 + 1).toString)
    }
  }
}

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

object _776A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val init = read[Seq, String](2)
    val replaces = read[Seq[(String, String)]]

    val ans = replaces.scanLeft(init) {
      case (curr, (from, to)) =>
        curr map {
          case `from` => to
          case x => x
        }
    }

    writeAll(ans.map(_.mkString(" ")), separator = "\n")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.There are $$$n$$$ doors, the $$$i$$$-th door initially has durability equal to $$$a_i$$$.During your move you can try to break one of the doors. If you choose door $$$i$$$ and its current durability is $$$b_i$$$ then you reduce its durability to $$$max(0, b_i - x)$$$ (the value $$$x$$$ is given).During Slavik's move he tries to repair one of the doors. If he chooses door $$$i$$$ and its current durability is $$$b_i$$$ then he increases its durability to $$$b_i + y$$$ (the value $$$y$$$ is given). Slavik cannot repair doors with current durability equal to $$$0$$$.The game lasts $$$10^{100}$$$ turns. If some player cannot make his move then he has to skip it.Your goal is to maximize the number of doors with durability equal to $$$0$$$ at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally?

The first line of the input contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100$$$, $$$1 \le x, y \le 10^5$$$) — the number of doors, value $$$x$$$ and value $$$y$$$, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th door.

Print one integer — the number of doors with durability equal to $$$0$$$ at the end of the game, if you and Slavik both play optimally.

NoteClarifications about the optimal strategy will be ignored.

//package codeforces.contest1102

object DoorsBreakingAndRepairing {
  def main(args: Array[String]): Unit = {
    val Array(n, x, y), seq = io.StdIn.readLine.split(" ").map(_.toInt)

    if (x > y) println(seq.length)
    else println((seq.count(_ <= x) + 1) / 2)

  }
}

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

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

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

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

  def solve(): Unit = {
    val N, X, Y = ni()
    val A = na(N)
    if (X > Y) {
      out.println(N)
    } else {
      val b = A.count(_ <= X)
      val ans = b / 2 + b % 2
      out.println(ans)
    }
  }

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

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

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

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

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

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

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

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

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

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

object CF_531_3_C {

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

  def solve(in: In): Out = {
    val (n, break, repair, as) = in

    if (break > repair) as.length
    else math.ceil(as.count(_ <= break)/2.0).toInt
  }
//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

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

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

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

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

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

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

  // A frequently used number in these comps
  val modulo = 1000000007

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

object CF_531_3_C {

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

  def solve(in: In): Out = {
    val (n, break, repair, as) = in

    if (break > repair) as.length
    else divideCeil(as.count(_ <= break), 2)
  }

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

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

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

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

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

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

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

  // A frequently used number in these comps
  val modulo = 1000000007

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


In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part.  If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part. If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?

The first line contains a single number to round up — the integer part (a non-empty set of decimal digits that do not start with 0 — with the exception of a case when the set consists of a single digit — in this case 0 can go first), then follows character «.» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.

If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  if (str.contains('.')) {
    val first = str.takeWhile(_ != '.')
    val second = str.dropWhile(_ != '.').tail
    if (first.last == '9')
      println("GOTO Vasilisa.")
    else if (second.head >= '5') {
      println(s"${first.init}${(first.last + 1).toChar}")
    } else {
      println(first)
    }
  } else {
    println(str)
  }
}

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

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

  val num = sc.nextLine.toList
  val (ipart, fpart): (List[Char], List[Char]) = num span (_ != '.')

  val roundUp: List[Char] => List[Char] = xs => xs.init ::: List((xs.last + 1).toChar)

  if (ipart.last == '9') out.println("GOTO Vasilisa.")
  else if (fpart == Nil || fpart.tail.head - '5' < 0) out.println(ipart.mkString)
  else out.println(roundUp(ipart).mkString)

  out.close
}

object Main {
  def main(args: Array[String]) {
    val str = readLine()
    val Array(i, f) = str.split("\\.")

    if (i.last == '9') println("GOTO Vasilisa.")
    else println (new java.math.BigDecimal(str).setScale(0, BigDecimal.RoundingMode.HALF_UP))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  if (str.contains('.')) {
    val first = str.takeWhile(_ != '.')
    val second = str.dropWhile(_ != '.').tail
    if (first.last == '9' && second.head >= '5')
      println("GOTO Vasilisa.")
    else if (second.head >= '5') {
      println(s"${first.init}${(first.last + 1).toChar}")
    } else {
      println(first)
    }
  } else {
    println(str)
  }
}

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

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

  val num = sc.nextLine.toList

  def roundUp(ipart: List[Char]): Unit = {
    val endDigit = ipart.last
    if (endDigit == '9') out.println("GOTO Vasilisa.")
    else {
      val e = (endDigit + 1).toChar
      val res = ipart.init ::: List(e)
      out.println(res.mkString)
    }
  }

  num.span(_ != '.') match {
    case (ipart, Nil) => out.println(num.mkString)
    case (ipart, '.' :: x :: xs) => if (x - '5' < 0) out.println(ipart.mkString)
                                    else roundUp(ipart)
  }

  out.close
}

object Main {
  def main(args: Array[String]) {
    val str = readLine()
    val Array(i, f) = str.split("\\.")

    println(i)

    if (i.last == '9') println("GOTO Vasilisa.")
    else println (new java.math.BigDecimal(str).setScale(0, BigDecimal.RoundingMode.HALF_UP))
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(i, f) = readLine().split("\\.")
    if (i.last == '9') println("GOTO Vasilisa.")
    else {
      val num = BigDecimal(i + "." + f)
      println(num.setScale(0, BigDecimal.RoundingMode.HALF_UP))
    }
  }
}


Mahmoud and Ehab live in a country with n cities numbered from 1 to n and connected by n - 1 undirected roads. It's guaranteed that you can reach any city from any other using these roads. Each city has a number ai attached to it.We define the distance from city x to city y as the xor of numbers attached to the cities on the path from x to y (including both x and y). In other words if values attached to the cities on the path from x to y form an array p of length l then the distance between them is , where  is bitwise xor operation.Mahmoud and Ehab want to choose two cities and make a journey from one to another. The index of the start city is always less than or equal to the index of the finish city (they may start and finish in the same city and in this case the distance equals the number attached to that city). They can't determine the two cities so they try every city as a start and every city with greater index as a finish. They want to know the total distance between all pairs of cities.

The first line contains integer n (1 ≤ n ≤ 105) — the number of cities in Mahmoud and Ehab's country. Then the second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106) which represent the numbers attached to the cities. Integer ai is attached to the city i. Each of the next n  -  1 lines contains two integers u and v (1  ≤  u,  v  ≤  n, u  ≠  v), denoting that there is an undirected road between cities u and v. It's guaranteed that you can reach any city from any other using these roads.

Output one number denoting the total distance between all pairs of cities.

NoteA bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.In the first sample the available paths are:  city 1 to itself with a distance of 1,  city 2 to itself with a distance of 2,  city 3 to itself with a distance of 3,  city 1 to city 2 with a distance of ,  city 1 to city 3 with a distance of ,  city 2 to city 3 with a distance of .  The total distance between all pairs of cities equals 1 + 2 + 3 + 3 + 0 + 1 = 10.

import scala.io.StdIn.readLine

object MahmudXorTrip extends App {
  private def combWith(as: Array[Long], bs: Array[Long])(f: (Long, Long) ⇒ Long): Array[Long] = {
    val res = Array.ofDim[Long](20)
    var i = 0
    while(i < 20){
      res(i) = f(as(i), bs(i))
      i+=1
    }
    res
  }
  case class Counts(count: Long = 0, bitCounts: Array[Long] = Array.fill(20)(0)) {
    def +(that: Counts) = Counts(count + that.count, combWith(bitCounts, that.bitCounts)(_ + _))
    def -(that: Counts) = Counts(count - that.count, combWith(bitCounts, that.bitCounts)(_ - _))
    def ^(num: Int) = Counts(count, bitCounts.zipWithIndex.map { case (c, i) ⇒
      if ((num & (1 << i)) == 0) c else count - c
    })
    def *(that: Counts) = Counts(count * that.count, combWith(bitCounts, that.bitCounts) {
      (c, tc) ⇒ c * (that.count - tc) + tc * (count - c)
    })

    private def countsStr = bitCounts.zipWithIndex.filter(_._1 != 0).mkString("[", ",", "]")
    override def toString: String = s"Count($count, $countsStr)"
  }
  val zero = Counts()
  val one = Counts(1)

  case class Step(num: Int, remains: List[Int], attSum: Counts = zero, detSum: Counts = zero, prodSum: Counts = zero) {
    def add(att: Counts, det: Counts) = Step(num, remains.tail, attSum + att, detSum + det, prodSum + attSum * att)
  }
  object ChildDown {
    def unapply(step: Step): Option[(Int, Step)] = step.remains match {
      case next :: rest ⇒ Some((next, step.copy(remains = rest)))
      case Nil ⇒ None
    }
  }
  val n = readLine().toInt
  val labels = -1 +: readLine().split(' ').map(_.toInt)
  val roads = Iterator.fill(n - 1)(readLine().split(' ').map(_.toInt))
              .flatMap { case Array(a, b) ⇒ Seq(a → b, b → a) }
              .toList.groupBy(_._1).mapValues(_.map(_._2))

  def go(stack: List[Step]): Counts = {
//    println(stack)
    stack match {
      case step :: upper if step.remains.nonEmpty ⇒
        val next = step.remains.head
        go(Step(next, roads(next).filter(_ != step.num)) :: step :: upper)
      case Step(num, _, attSum, detSum, prodSum) :: upper ⇒
        val detach = attSum + detSum + (prodSum ^ labels(num))
        val attach = (attSum + one) ^ labels(num)
        upper match {
          case Nil ⇒ attach + detach
          case pstep :: upup ⇒ go(pstep.add(attach, detach) :: upup)
        }
    }
  }

  val resState = if(n == 1) one ^ labels(1) else go(Step(1, roads(1), zero, zero, zero) :: Nil)
//  println(resState)
  val result = resState.bitCounts.zipWithIndex
               .map { case (c, i) ⇒ c.toLong << i }.sum

  println(result)
}


Did you know you can download more RAM? There is a shop with $$$n$$$ different pieces of software that increase your RAM. The $$$i$$$-th RAM increasing software takes $$$a_i$$$ GB of memory to run (temporarily, once the program is done running, you get the RAM back), and gives you an additional $$$b_i$$$ GB of RAM (permanently). Each software can only be used once. Your PC currently has $$$k$$$ GB of RAM.Note that you can't use a RAM-increasing software if it takes more GB of RAM to use than what you currently have.Since RAM is the most important thing in the world, you wonder, what is the maximum possible amount of RAM achievable?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains the integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 1000$$$). Then two lines follow, each containing $$$n$$$ integers describing the arrays $$$a$$$ and $$$b$$$ ($$$1 \le a_i, b_i \le 1000$$$).

For each test case, output a single line containing the largest amount of RAM you can achieve.

NoteIn the first test case, you only have enough RAM to run the third software initially, but that increases your RAM to $$$20$$$ GB, which allows you to use the first software, increasing your RAM to $$$29$$$ GB. The only software left needs $$$30$$$ GB of RAM, so you have to stop here.In the second test case, you can use the first, second, fourth and fifth software that need only $$$1$$$ GB of RAM per software to run to increase your RAM to $$$5$$$ GB, and then use the last remaining one to increase your RAM to $$$6$$$ GB.In the third test case, all the software need more than $$$1$$$ GB of RAM to run, so the amount of RAM you have stays at $$$1$$$ GB.

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
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(_, k) = readInts()
    val a = readInts()
    val b = readInts()
    val c = a.zip(b).sortBy(_._1)

    def findAnswer(index: Int, currentRam: Int): Int = {
      if (index < c.length) {
        c(index) match {
          case (a, b) if a <= currentRam => findAnswer(index + 1, currentRam + b)
          case _ => currentRam
        }
      } else {
        currentRam
      }
    }

    println(findAnswer(0, k))
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)

  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)

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

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

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

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

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

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

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val k = readInt()
        val arr = new Array[pair](n)
        for (i <- 0 until n) {
            arr(i) = pair(0, 0)
            arr(i).a = readInt()
        }
        for (i <- 0 until n) {
            arr(i).b = readInt()
        }
        quickSort(arr)
        var ans = k
        for (i <- 0 until n) {
            if (arr(i).a <= ans) {
                ans += arr(i).b
            }
        }
        writer.println(ans )

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


Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.

Print n integers, separated by spaces — the numbers written on the cubes in their initial order. It can be shown that the answer is unique.

NoteConsider the first sample.  At the begining row was [2, 3, 9, 6, 7, 1, 4].  After first operation row was [4, 1, 7, 6, 9, 3, 2].  After second operation row was [4, 3, 9, 6, 7, 1, 2].  After third operation row was [4, 3, 7, 6, 9, 1, 2].  At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].

object Solution {

  import scala.math._

  def main(args: Array[String]) {

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

    val n = sc.nextInt()
    val cubes = Array.fill(n)(sc.nextInt())

    val init = Array.fill(n)(0)

    for (i <- 0 until n/2) {
      if (i%2 == 0) {
        init(i) = cubes(n-1-i)
        init(n-1-i) = cubes(i)
      }
      else {
        init(i) = cubes(i)
        init(n-1-i) = cubes(n-1-i)
      }
    }
    if (n%2 == 1) init((n-1)/2) = cubes((n-1)/2)
    println(init.mkString(" "))
  }
}

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

object _764B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val a = read[Array[Int]]
    val n = a.length

    @tailrec
    def solve(i: Int): Unit = {
      val j = n - i - 1
      if (i <= j) {
        if (i%2 == 0) {
          val t = a(i)
          a(i) = a(j)
          a(j) = t
        }
        solve(i + 1)
      }
    }

    solve(0)

    writeAll(a)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import scala.io.StdIn

/**
 * Created by dmitry on 05.02.17.
 */
object Main2 {
  def main(args: Array[String]) {
    val n: Int = StdIn.readInt() - 1
    val str: String = StdIn.readLine()
    val digits: Array[Int] = str.split(' ').toStream.map(_.toInt).toArray
    for (i <- 0 to n / 2) {
      if ((i + 1) % 2 != 0) {
        val tmp = digits(i)
        digits(i) = digits(n - i)
        digits(n - i) = tmp
      }
    }
    println(digits.mkString("", " ", ""))
  }
}

import io.StdIn.readLine

object TimofeyAndCubes extends App {

  val n = readLine().toInt
  val a = readLine.split(" ").map(_.toInt)
  solve(n, a)
  println(a.mkString(" "))

  def solve (n: Int, a: Array[Int]) : Unit = {

    for (i <- 0 until n/2) {
      if (i == 0 || i % 2 == 0) {
        val tmp = a(i)
        a(i) = a(n - i - 1)
        a(n - i - 1) = tmp
      }
    }
  }
}

import java.util

import scala.io.StdIn

/**
 * Created by dmitry on 05.02.17.
 */
object Main2 {
  def main(args: Array[String]) {
    var n: Int = (StdIn.readInt() - 1) / 2
    val str: String = StdIn.readLine()
    val digits: Array[Int] = str.split(' ').toStream.map(_.toInt).toArray
    while (n >= 0) {
      rev(digits, n, digits.length - 1 - n)
      n -= 1
    }
    println(util.Arrays.toString(digits))
  }

  def rev(ms: Array[Int], i: Int, j: Int): Unit = {
    var k: Int = i
    while (k < (j - i) / 2 + i) {
      val tmp = ms(k)
      ms(k) = ms(j - k + i)
      ms(j - k + i) = tmp
      k += 1
    }
  }
}


Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example:   the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds;  the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array;  the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \ne 1$$$;  the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \ne 1$$$;  the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \le s \le 5000$$$) for the $$$i$$$-th test case.

Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

NoteConsider the example test:  in the first test case, the array $$$[1]$$$ meets all conditions;  in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions;  in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions;  in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions.

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

  def f: Int => Int = x => math.ceil(math.sqrt(x)).toInt

  val t = readInt()

  (0 until t).foreach { _ =>
    val x = readInt()
    println(f(x))
  }
}


Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?

The first line of the input contains integer n (2 ≤ n ≤ 100000) — the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n. The second line contains n - 1 integer a1, a2, ..., an (1 ≤ ai ≤ n) — the numbers of episodes that Polycarpus has watched. All values of ai are distinct.

Print the number of the episode that Polycarpus hasn't watched.

object Devu {
  def main(args: Array[String]) {
	  val n = readLine().toInt
	  val d = readLine().split(" ").map(_.toLong)
	  var r = d.reduceLeft(_ ^ _)
	  var k = 0
	  var z = n
	  while (z > 0) {
	    k += 1
	    z >>= 1
	  }
	  var mx = 1 << k
	  if (mx < n){
	    mx <<= 1
	  }
	  for (z <- (n + 1) until mx){
	    r = r ^ z
	  }
	  println(r)
  }
}

object Main extends App{
  val n = readLine().toInt
  val nums = readLine().split(" ").map { _.toInt }
  println((1 to n).toList.diff(nums).head.toString)
}

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  data.next()
  val r = data.next().split(" ").map(_.toInt).toSet
  println(Range(1, r.size + 2).find{i => !r.contains(i)}.get)
}

object Template {
	def main(args: Array[String]) {
		var n = readLine.toInt
		var books: Array[Boolean] = new Array[Boolean](n)
		var input = readLine.split(' ').map(_.toInt)
		for(i <- input){
			books(i-1) = true
		}
		for(i <- 0 until books.length){
			if(!books(i)){
				print(i+1)
			}
		}
	}
}

import java.util.Scanner

object aa {
 def main(args: Array[String]) {
  val sc = new Scanner(System.in)
  val n=sc.nextInt();
  var x: Long = 0
  for(i <- 1 to n-1){
   x+=sc.nextInt
  }
  val m:Long=n;
  print((m*(m+1))/2-x)
 }
}

object Devu {
  def main(args: Array[String]) {
	  val n = readLine().toInt
	  val d = readLine().split(" ").map(_.toLong)
	  var r = d.reduceLeft(_ ^ _)
	  val mx = 1 << (math.log(n).toInt + 2)
	  for (z <- (n + 1) until mx){
	    r = r ^ z
	  }
	  println(r)
  }
}

object Main extends App {
  println("Hello!")
}

object Main extends App{
  val input = readLine() +"\r\n"+ readLine()
  TR10A.func(input)
}

object TR10A extends Example {
  def func(input: String): String = {
    val lines = input.lines.toList
    val n = lines.head.toInt
    val nums = lines(1).split(" ").map { _.toInt }
    (1 to n).toList.diff(nums).head.toString
  }
  def exs =
    Example("""10
3 8 10 1 7 9 6 5 2""", "4") :: Nil
}

trait Contents {
  def func(input: String): String
}

trait Example extends Contents {
  def exs: List[Example]
  case class Example(input: String, output: String)
  def results = exs.map { ex => func(ex.input) }
  def check =
    assert(exs.forall { case Example(input, output) => func(input) == output })
  /*  def samples: String
  def makeExample(is: Int, os: Int): List[Example] = {
    val lines = samples.split("\n").toList
    lines
      .grouped(is + os + 2).toList
      .map { _.splitAt(is + 1) }
      .map { case (input, output) => Example(input.drop(1).mkString("\n"), output.drop(1).mkString("\n")) }
    }
      */

}

object Main extends App{
  val n = readLine().toInt
  val nums = readLine().split(" ").map { _.toInt }
  (1 to n).toList.diff(nums).head.toString
}

import java.util.Scanner

object aa {
 def main(args: Array[String]) {
  val sc = new Scanner(System.in)
  val n=sc.nextInt
  var x: Int = 0
  for(i <- 1 to n-1){
   x+=sc.nextInt
  }
  print((n*(n+1))/2-x)
 }
}

import java.util.Scanner

object aa {
 def main(args: Array[String]) {
  val sc = new Scanner(System.in)
  val n=sc.nextInt();
  var x: Int = 0
  for(i <- 1 to n-1){
   x+=sc.nextInt
  }
  val m:Long=n;
  print((m*(m+1))/2-x)
 }
}


In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l < m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.

The first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l < m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].

Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, d, m, l) = readLine.split(" ").map(e => e.toLong);
    var x: Long = 0;
    var p = ArrayBuffer[(Long, Long)]();
    for (k <- 1 to n.toInt) {
      var x1 = (k - 1) * m;
      var x2 = (k - 1) * m + l
      p.append((x1, x2));
    }
    for (i <- 0 until p.length - 1) {
      var c: Long = (p(i)._2 - x) / d
      x +=  c * d;
      if (x + d < p(i + 1)._1) {
        println(x + d);
        return;
      }
    }
    var c: Long = x + ((p.last._2 - x) / d) * d + d
    println(c);
  }

}

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 = nextLong
    val d = nextLong
    val m = nextLong
    val l = nextLong
    var pos: Long = 1L * d
    while (pos % m <= l && pos / m < n) {
      val num = pos / m
      val jumps = (num * m + l - pos) / d
      if (jumps == 0) {
        pos += d
      } else {
        pos += jumps * d
      }
    }
    out.println(pos)
    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
  }
}

// CodeForces 18B

object Platforms extends App {
  val ln = (Console.readLine()).split(" ") map (_.toInt)
  val n = ln(0)
  val d = ln(1)
  val m = ln(2)
  val l = ln(3)

  var p = 0L
  var cont = true
  while(cont) {
    val nn = p / m
    val oo = p % m
    if (nn >= n || oo > l) {
      cont = false
    } else {
      if (oo + 3*d < l) {
        p += ((l - oo)/d)*d
      } else {
        p += d
      }
    }
  }
  println(p)
}

// 3 6 6 3

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 d = nextInt
    val m = nextInt
    val l = nextInt
    for (i <- 1 to n) {
      if (i * d % m > l) {
        out.println(i * d)
        return 1
      }
    }
    out.println((n - 1) * m + l + 1)
    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 d = nextInt
    val m = nextInt
    val l = nextInt
    for (i <- 1 to n) {
      if (i * d % m > l) {
        out.println(i * d)
        return 1
      }
    }
    out.println(n * d)
    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 = nextLong
    val d = nextLong
    val m = nextLong
    val l = nextLong
    for (i <- 1 to n.toInt) {
      if (i.toLong * d % m > l) {
        out.println(i * d)
        return 1
      }
    }
    out.println(n * d)
    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.lang._
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 Long.parseLong(next)
  }

  def fallInto(k: Int, m: Int, l: Int, pos: Int): Boolean = {
    if ((pos > (k - 2) * m + l && pos < (k - 1) * m) || (pos > (k - 1) * m + l && pos < k * m))
      return true
    return false
  }

  def solve: Int = {
    val n = nextInt
    val d = nextInt
    val m = nextInt
    val l = nextInt
    var pos = 0
    for (i <- 1 to n) {
      pos += d
      if (fallInto(i, m, l, pos)) {
        out.println(pos)
        return 1
      }
    }
    out.println(pos)
    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
  }
}

// CodeForces 18B

object Platforms extends App {
  val ln = (Console.readLine()).split(" ") map (_.toInt)
  val n = ln(0)
  val d = ln(1)
  val m = ln(2)
  val l = ln(3)

  var p = 0L
  var cont = true
  while(cont) {
    val nn = p / m
    val oo = p % m
    if (nn > n || oo > l) {
      cont = false
    } else {
      p += d
    }
  }
  println(p)
}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, d, m, l) = readLine.split(" ").map(_.toInt);
    var x = 0;
    var p = ArrayBuffer[(Int, Int)]();
    for (k <- 1 to n) {
      var x1 = (k - 1) * m;
      var x2 = (k - 1) * m + l
      p.append((x1, x2));
    }
    for (i <- 0 until p.length - 1) {
      var c = (p(i)._2 - x) / d
      x +=  c * d;
      if (x + d < p(i + 1)._1) {
        println(x + d);
        return;
      }
    }
  }

}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, d, m, l) = readLine.split(" ").map(_.toInt);
    var x = 0;
    var p = ArrayBuffer[(Int, Int)]();
    for (k <- 1 to n) {
      var x1 = (k - 1) * m;
      var x2 = (k - 1) * m + l
      p.append((x1, x2));
    }
    for (i <- 0 until p.length - 1) {
      var c = (p(i)._2 - x) / d
      x +=  c * d;
      if (x + d < p(i + 1)._1) {
        println(x + d);
        return;
      }
    }
    println(x + ((p.last._2 - x) / d) * d + d);
  }

}


A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.

The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.

Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.

NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.

import java.util.Scanner
import scala.collection.mutable._

object Main extends App {
  val sc = new Scanner(System.in)

  val n, k = sc.nextInt()

  val a = input(n).toArray

  val m = Map[Int, Int]().withDefault(_ => 0)

  for (i <- 1 until (a.size - 1)) {
    if (a(i - 1) != a(i + 1)) m(a(i)) += 1
    else m(a(i)) += 2
  }

  m(a.last) += 1
  m(a.head) += 1

  val ans = m reduce { (A, B) =>
    if (A._2 > B._2) A
    else if (A._2 == B._2 && A._1 < B._1) A
    else B
  }

  println(ans._1)

  def input(n: Int, result: List[Int] = Nil): List[Int] = {
    if (n == 0) result.reverse
    else {
      val q = sc.nextInt()
      if (result.headOption == Some(q)) input(n - 1, result)
      else input(n - 1, q :: result)
    }
  }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val ab=ArrayBuffer[Int]()
    ab+=arr(0)
    for(i<-1 until n) if(arr(i)!=arr(i-1)) ab+=arr(i)

    var dp=new Array[Int](k+1)
    for(i<-1 until ab.length-1){
        if(ab(i-1)!=ab(i+1))
            dp(ab(i))+=1
        else
            dp(ab(i))+=2
    }
    dp(ab.head)+=1
    dp(ab.last)+=1

    println(dp.indexOf(dp.max))
}

import java.util.Scanner
import scala.collection.mutable._

object Main extends App {
  val sc = new Scanner(System.in)

  val n, k = sc.nextInt()

  val a = input(n).toArray

  val m = Map[Int, Int]().withDefault(_ => 0)

  for (i <- 1 until (a.size - 1)) {
    if (a(i - 1) != a(i + 1)) m(a(i)) += 1
    else m(a(i)) += 2
  }

  m(a.last) += 1

  val ans = m reduce { (A, B) =>
    if (A._2 > B._2) A
    else if (A._2 == B._2 && A._1 < B._1) A
    else B
  }

  println(ans._1)

  def input(n: Int, result: List[Int] = Nil): List[Int] = {
    if (n == 0) result.reverse
    else {
      val q = sc.nextInt()
      if (result.headOption == Some(q)) input(n - 1, result)
      else input(n - 1, q :: result)
    }
  }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    val ab=ArrayBuffer[Int]()
    ab+=arr(0)
    for(i<-1 until n) if(arr(i)!=arr(i-1)) ab+=arr(i)

    var dp=new Array[Int](k+1)
    for(i<-1 until n-1){
        if(arr(i-1)!=arr(i+1))
            dp(arr(i))+=1
        else
            dp(arr(i))+=2
    }
    dp(arr(0))+=1
    dp(arr(n-1))+=1

    println(dp.indexOf(dp.max))
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val Array(n,k)=readLine.split(" ").map(_.toInt)
    val arr=readLine.split(" ").map(_.toInt)
    var dp=new Array[Int](k+1)
    for(i<-1 until n){
        if(arr(i-1)!=arr(i)){
            dp(arr(i-1))+=1
            dp(arr(i))+=1
        }
    }

    println(dp.indexOf(dp.max))
}


After defeating a Blacklist Rival, you get a chance to draw $$$1$$$ reward slip out of $$$x$$$ hidden valid slips. Initially, $$$x=3$$$ and these hidden valid slips are Cash Slip, Impound Strike Release Marker and Pink Slip of Rival's Car. Initially, the probability of drawing these in a random guess are $$$c$$$, $$$m$$$, and $$$p$$$, respectively. There is also a volatility factor $$$v$$$. You can play any number of Rival Races as long as you don't draw a Pink Slip. Assume that you win each race and get a chance to draw a reward slip. In each draw, you draw one of the $$$x$$$ valid items with their respective probabilities. Suppose you draw a particular item and its probability of drawing before the draw was $$$a$$$. Then,  If the item was a Pink Slip, the quest is over, and you will not play any more races.  Otherwise,   If $$$a\leq v$$$, the probability of the item drawn becomes $$$0$$$ and the item is no longer a valid item for all the further draws, reducing $$$x$$$ by $$$1$$$. Moreover, the reduced probability $$$a$$$ is distributed equally among the other remaining valid items.  If $$$a > v$$$, the probability of the item drawn reduces by $$$v$$$ and the reduced probability is distributed equally among the other valid items.  For example,  If $$$(c,m,p)=(0.2,0.1,0.7)$$$ and $$$v=0.1$$$, after drawing Cash, the new probabilities will be $$$(0.1,0.15,0.75)$$$.  If $$$(c,m,p)=(0.1,0.2,0.7)$$$ and $$$v=0.2$$$, after drawing Cash, the new probabilities will be $$$(Invalid,0.25,0.75)$$$.  If $$$(c,m,p)=(0.2,Invalid,0.8)$$$ and $$$v=0.1$$$, after drawing Cash, the new probabilities will be $$$(0.1,Invalid,0.9)$$$.  If $$$(c,m,p)=(0.1,Invalid,0.9)$$$ and $$$v=0.2$$$, after drawing Cash, the new probabilities will be $$$(Invalid,Invalid,1.0)$$$. You need the cars of Rivals. So, you need to find the expected number of races that you must play in order to draw a pink slip.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10$$$)  — the number of test cases. The first and the only line of each test case contains four real numbers $$$c$$$, $$$m$$$, $$$p$$$ and $$$v$$$ ($$$0 < c,m,p < 1$$$, $$$c+m+p=1$$$, $$$0.1\leq v\leq 0.9$$$). Additionally, it is guaranteed that each of $$$c$$$, $$$m$$$, $$$p$$$ and $$$v$$$ have at most $$$4$$$ decimal places.

For each test case, output a single line containing a single real number — the expected number of races that you must play in order to draw a Pink Slip. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteFor the first test case, the possible drawing sequences are:   P with a probability of $$$0.6$$$;  CP with a probability of $$$0.2\cdot 0.7 = 0.14$$$;  CMP with a probability of $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$;  CMMP with a probability of $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$;  MP with a probability of $$$0.2\cdot 0.7 = 0.14$$$;  MCP with a probability of $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$;  MCCP with a probability of $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$.  So, the expected number of races is equal to $$$1\cdot 0.6 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 = 1.532$$$.For the second test case, the possible drawing sequences are:   P with a probability of $$$0.4$$$;  CP with a probability of $$$0.4\cdot 0.6 = 0.24$$$;  CMP with a probability of $$$0.4\cdot 0.4\cdot 1 = 0.16$$$;  MP with a probability of $$$0.2\cdot 0.5 = 0.1$$$;  MCP with a probability of $$$0.2\cdot 0.5\cdot 1 = 0.1$$$. So, the expected number of races is equal to $$$1\cdot 0.4 + 2\cdot 0.24 + 3\cdot 0.16 + 2\cdot 0.1 + 3\cdot 0.1 = 1.86$$$.

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

  val scale = 1e8

  val t = readInt()

  (0 until t).foreach { _ =>
    // c + m + p == 1, 0 < c, m, p < 1
    // 0.1 <= v <= 0.9
    val Array(c, m, p, v) = readLine().split(" ").map(s => (s.toDouble * scale).toInt)

    def reward(slips: List[Int]): List[Int] =
      slips match {
        case x :: xs if x <= v => xs.map(_ + x / xs.length)
        case x :: xs if x > v  => xs.map(_ + v / xs.length) :+ (x - v)
        case _                 => slips
      }

    def race(slips: List[Int]): Double =
      slips match {
        case x :: y :: Nil      =>
          x / scale + y / scale * (1 + race(reward(y :: x :: Nil)))
        case x :: y :: z :: Nil =>
          x / scale +
            y / scale * (1 + race(reward(y :: x :: z :: Nil))) +
            z / scale * (1 + race(reward(z :: x :: y :: Nil)))
        case _                  => 1
      }

    val ans = race(List(p, m, c))

    println(ans)

  }
}

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

  val scale = 1e8

  val t = readInt()

  (0 until t).foreach { _ =>
    // c + m + p == 1, 0 < c, m, p < 1
    // 0.1 <= v <= 0.9
    val Array(c, m, p, v)                   =
      readLine().split(" ").zipWithIndex.map { case (s, i) => ((s.toDouble + i / scale) * scale).toInt }

    def reward(slips: List[Int]): List[Int] =
      slips match {
        case x :: xs if x <= v => xs.map(_ + x / xs.length)
        case x :: xs if x > v  => xs.map(_ + v / xs.length) :+ (x - v)
        case _                 => slips
      }

    def race(slips: List[Int]): Double =
      slips match {
        case x :: Nil           => 1
        case x :: y :: Nil      =>
          x / scale +
            y / scale * (1 + race(reward(y :: x :: Nil)))
        case x :: y :: z :: Nil =>
          x / scale +
            y / scale * (1 + race(reward(y :: x :: z :: Nil))) +
            z / scale * (1 + race(reward(z :: x :: y :: Nil)))
        // case x :: xs       =>
        //   xs.permutations.foldLeft(x / scale) {
        //     case (sum, y :: ys) => sum + y / scale * (1 + race(reward(y :: x :: ys)))
        //     case (sum, _)       => sum
        //   }
        case _                  => 0
      }

    val ans = race(List(p, m, c))

    println(ans)

  }
}

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

  val scale = 1e6

  val t = readInt()

  (0 until t).foreach { _ =>
    // c + m + p == 1, 0 < c, m, p < 1
    // 0.1 <= v <= 0.9
    val Array(c, m, p, v)                   =
      readLine().split(" ").zipWithIndex.map { case (s, i) => ((s.toDouble + i / scale) * scale).toInt }

    def reward(slips: List[Int]): List[Int] =
      slips match {
        case x :: xs if x <= v => xs.map(_ + x / xs.length)
        case x :: xs if x > v  => xs.map(_ + v / xs.length) :+ (x - v)
        case _                 => slips
      }

    def race(slips: List[Int]): Double =
      slips match {
        case x :: Nil => 1
        case x :: xs  =>
          xs.permutations.foldLeft(x / scale) {
            case (sum, y :: ys) => sum + y / scale * (1 + race(reward(y :: x :: ys)))
            case (sum, _)       => sum
          }
        case _        => 0
      }

    val ans = race(List(p, m, c))

    println(ans)

  }
}


Alice and Bob play a game. They have a binary string $$$s$$$ (a string such that each character in it is either $$$0$$$ or $$$1$$$). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in $$$s$$$ and delete them.For example, if the string is $$$10110$$$, there are $$$6$$$ possible moves (deleted characters are bold):  $$$\textbf{1}0110 \to 0110$$$;  $$$1\textbf{0}110 \to 1110$$$;  $$$10\textbf{1}10 \to 1010$$$;  $$$101\textbf{1}0 \to 1010$$$;  $$$10\textbf{11}0 \to 100$$$;  $$$1011\textbf{0} \to 1011$$$. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $$$10\textbf{11}0 \to 1\textbf{00} \to 1$$$.The game ends when the string becomes empty, and the score of each player is the number of $$$1$$$-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 500$$$) — the number of test cases. Each test case contains exactly one line containing a binary string $$$s$$$ ($$$1 \le |s| \le 100$$$).

For each test case, print one integer — the resulting score of Alice (the number of $$$1$$$-characters deleted by her).

NoteQuestions about the optimal strategy will be ignored.

object Solution extends App {
    var n = scala.io.StdIn.readInt()
    for (_ <- 1 to n) {
        var ans = scala.io.StdIn.readLine()
            .split("0")
            .map(_.length)
            .sorted
            .reverse
            .zipWithIndex
            .filter(_._2 % 2 == 0)
            .map(_._1)
            .sum
        println(ans)
    }
}

object CodeforcesRoundE93b {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

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

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

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val s = rl
    val res = s
      .split('0')
      .map(_.length)
      .sorted
      .reverse
      .grouped(2)
      .map(_ (0))
      .sum
    writer.println(res)
  }

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

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

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

}

import scala.io.StdIn

object Solution2 extends App {

  //A + B > C and B + C > A and C + A > B

  val n = StdIn.readLine().toInt

  val tc = for {
    _ <- 0 until n
  } yield {
    StdIn.readLine()
  }

  for {
    code <- tc
  } {
    println(solve(code))
  }

  def solve(code: String): String = {
    var i = 0

    val groups = scala.collection.mutable.Buffer[Int]()
    var group = 0
    while (i < code.length) {
      if (group != 0 && code.charAt(i) == '0') {
        groups += group
        group = 0
      } else if (code.charAt(i) == '1') {
        group += 1
      }
      i += 1
    }
    if (group != 0) {
      groups += group
    }
    groups.sorted.reverse.zipWithIndex.collect {
      case (score, idx) if idx % 2 == 0 => score
    }.sum.toString
  }
}

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

  val r = """1+""".r

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    val ans = r
      .findAllIn(s)
      .map(_.length)
      .toList
      .sorted(Ordering.Int.reverse)
      .zipWithIndex
      .collect {
        case (l, i) if i % 2 == 0 => l
      }
      .reduceOption(_ + _)
      .getOrElse(0)

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    val ans = s
      .foldLeft(List(0)) {
        case (0 :: xs, '0') => 0 :: xs
        case (xs, '0')      => 0 :: xs
        case (x :: xs, '1') => (x + 1) :: xs
      }
      .sorted(Ordering.Int.reverse)
      .zipWithIndex
      .collect { case (l, i) if i % 2 == 0 => l }
      .reduceOption(_ + _)
      .getOrElse(0)

    println(ans)
  }
}

import scala.collection.mutable.ListBuffer

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec

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

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

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

    inputLines.times {
      val temLine   = in.line()
      var oneCounts = ListBuffer.empty[Int]
      var count     = 0
      temLine.foreach(x => {
        if (x == '1') {
          count = count + 1
        } else {
          if (count > 0) {
            oneCounts +== count
            count = 0
          }
        }
      })
      if (count > 0) {
        oneCounts +== count
      }
      val result = oneCounts
        .sortWith(_ > _)
        .zipWithIndex
        .foldLeft(0)((x, y) => {
          x + (if (y._2 % 2 == 0) y._1 else 0)
        })
      println(result)
//      val connectivity = Array.ofDim[Boolean](airports, airports)

    }
  }

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

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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