Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, h, k) = in.next().split(' ').map(_.toInt)
  val (lh, time) = in.next().split(' ').map(_.toInt).foldLeft(0l, 0l) {
    case ((lh, time), el) if lh + el <= h || lh % k + el <= h =>
      ((lh + el) % k, time + (lh + el) / k)
    case ((lh, time), el) => (el % k, time + lh / k + el / k + 1)
  }
  if (lh == 0)
    println(time)
  else
    println(time + 1)
}

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A365 extends App {

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

    var occupation = 0
    var potatoIndex = 0
    var time: Long = 0L
    while (potatoIndex < n) {
      if (occupation + a(potatoIndex) > h) {
        if (occupation % k == 0) {
          time += occupation / k
          occupation = 0
        } else {
          time += occupation / k + 1
          occupation = 0
        }
      }
      while (potatoIndex < n && occupation + a(potatoIndex) <= h) {
        occupation += a(potatoIndex)
        potatoIndex += 1
      }
      if (occupation % k == 0) {
        time += occupation / k
        occupation = 0
      } else {
        time += occupation / k
        occupation = occupation % k
      }
    }
    if (occupation > 0) {
      if (occupation % k == 0) {
        time += occupation / k
        occupation = 0
      } else {
        time += occupation / k + 1
        occupation = 0
      }
    }

    println(time)
  }

  solve()

}

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

object _677B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, h, k = io[Int]
    val potato = io[Vector, Int](n)

    var i, tower = 0
    var t = 0L
    while(i < n) {
      while(i < n && tower + potato(i) <= h) {
        tower += potato(i)
        i += 1
      }
      val target = if (i < n) h - potato(i) else 0
      val smashes = (tower - target) ceilDiv k
      tower = (tower - k*smashes) max 0
      t += smashes
    }

    io += t
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_._1)
    def firstKeyOption: Option[K] = m.headOption.map(_._1)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv._1
      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 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
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def 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(n.min(x, y), n.max(x, y), 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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

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

object _677B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, h, k = io[Int]
    val potato = io[Vector, Int](n)

    var i, tower = 0
    var t = 0L
    while(i < n) {
      while(i < n && tower + potato(i) <= h) {
        tower += potato(i)
        i += 1
      }
      val target = if (i < n) h - potato(i) else 0
      val smashes = ((1.0 * (tower - target))/k).ceil
      tower = (tower - k*smashes.toInt) max 0
      //debug(t, i, tower, target, smashes)
      t += smashes.toLong
    }

    io += t
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    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
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def 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(n.min(x, y), n.max(x, y), n.one)
  }
  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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def vector[A: IO.Read](n: Int): Vector[A] = apply[Vector, A](n)

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

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

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

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

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

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    val Array(n, h, k) = StdIn.readLine().split(" ").map(_.toLong)

    val A:Array[Long] = StdIn.readLine().split(" ").map(_.toLong)

    var curH = 0L
    var t = 0L
    for ( i <- 0 to A.length - 1) {
      val nd = math.max(A(i) -  (h - curH),0)
      val d = nd / k + (if (nd % k == 0) 0  else 1)
      t += d
      curH = math.max(0L, curH - d * k ) + A(i)
    }
    val d = curH / k + (if (curH % k == 0) 0  else 1)
    t += d
    print(t)
//    print(A.foldLeft((0L,0L))({
//      case(b,a) =>
//        if(i == 0) {
//          (a,a)
//        } else {
//          val k = math.max(0, math.min(b._2 - 1, a))
//          (b._1 + k, k)
//        }
//    })._1)
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, h, k) = in.next().split(' ').map(_.toInt)
  val (lh, time) = in.next().split(' ').map(_.toInt).foldLeft(0, 0) {
    case ((lh, time), el) if lh + el <= h || lh % k + el <= h =>
      ((lh + el) % k, time + (lh + el) / k)
    case ((lh, time), el) => (el % k, time + lh / k + el / k + 1)
  }
  if (lh == 0)
    println(time)
  else
    println(time + 1)
}

/**
 * @author pvasilyev
 * @since 19 Jun 2016
 */
object A365 extends App {

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

    var occupation = 0
    var potatoIndex = 0
    var time = 0
    while (potatoIndex < n) {
      if (occupation + a(potatoIndex) > h) {
        if (occupation % k == 0) {
          time += occupation / k
          occupation = 0
        } else {
          time += occupation / k + 1
          occupation = 0
        }
      }
      while (potatoIndex < n && occupation + a(potatoIndex) <= h) {
        occupation += a(potatoIndex)
        potatoIndex += 1
      }
      if (occupation % k == 0) {
        time += occupation / k
        occupation = 0
      } else {
        time += occupation / k
        occupation = occupation % k
      }
    }
    if (occupation > 0) {
      if (occupation % k == 0) {
        time += occupation / k
        occupation = 0
      } else {
        time += occupation / k + 1
        occupation = 0
      }
    }

    println(time)
  }

  solve()

}

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

object _677B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, h, k = io[Int]
    val potato = io[Vector, Int](n)

    var i, t, tower = 0
    while(i < n) {
      while(i < n && tower + potato(i) <= h) {
        tower += potato(i)
        i += 1
      }
      val target = if (i < n) h - potato(i) else 0
      val smashes = ((1.0 * (tower - target))/k).ceil.toInt
      tower = (tower - k*smashes) max 0
      //debug(t, i, tower, target, smashes)
      t += smashes
    }

    io += t
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    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
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def 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(n.min(x, y), n.max(x, y), n.one)
  }
  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] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  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
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    val Array(n, h, k) = StdIn.readLine().split(" ").map(_.toInt)

    val A:Array[Int] = StdIn.readLine().split(" ").map(_.toInt)

    var curH = 0
    var t = 0
    for ( i <- 0 to A.length - 1) {
      val nd = math.max(A(i) -  (h - curH),0)
      val d = nd / k + (if (nd % k == 0) 0  else 1)
      t += d
      curH = math.max(0, curH - d * k ) + A(i)
    }
    val d = curH / k + (if (curH % k == 0) 0  else 1)
    t += d
    print(t)
//    print(A.foldLeft((0L,0L))({
//      case(b,a) =>
//        if(i == 0) {
//          (a,a)
//        } else {
//          val k = math.max(0, math.min(b._2 - 1, a))
//          (b._1 + k, k)
//        }
//    })._1)
  }

}


Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.

NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(x, k) = in.next().split(' ').map(_.toInt)
  val contests = Array.ofDim[Boolean](x - 1)
  (1 to k).foreach { i =>
    in.next().split(' ').map(_.toInt) match {
      case Array(1, f, s) =>
        contests(f - 1) = true
        contests(s - 1) = true
      case Array(2, s) => contests(s - 1) = true
    }
  }
  val res = contests.foldLeft((0, 0, 0)) {
    case((min, max, soFar), false) => (min, max, soFar + 1)
    case((min, max, soFar), true) => (min + soFar / 2 + soFar % 2, max + soFar, 0)
  }
  val min = res._1 + res._3 / 2 + res._3 % 2
  val max = res._2 + res._3
  println(s"$min $max")

}

import java.util.Scanner

/**
 * Created by hama_du on 2014/03/11.
 */
object ProblemB extends App {
  val in = new Scanner(System.in)
  val x,k = in.nextInt
  val rounds = new Array[Boolean](x+1)
  rounds(x) = true
  (0 until k).foreach(_ => {
    val rnd = in.nextInt
    if (rnd == 1) {
      rounds(in.nextInt()) = true
      rounds(in.nextInt()) = true
    } else {
      rounds(in.nextInt()) = true
    }
  })

  val max = (1 to x-1).filter(i => !rounds(i)).size
  val min = count(1, rounds)
  println(min + " " + max)

  def count(idx: Int, rounds: Array[Boolean]): Int = {
    if (idx >= x) {
      0
    } else if (rounds(idx)) {
      count(idx+1, rounds)
    } else {
      if (!rounds(idx+1)) {
        1 + count(idx+2, rounds)
      } else {
        1 + count(idx+1, rounds)
      }
    }
  }
}


The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:  If x = 1, exit the function.  Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.

object A {
    def main(args: Array[String]) = {
        val n = readInt;
        val answer = n :: (1 to (n - 1) toList);
        println(answer map {_.toString} reduceLeft {_ + " " + _})
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((n :: (1 to n - 1).toList).mkString(" "))
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

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

  val N = sc.nextInt
  val answer = N :: List.range(1, N)

  out.println(answer.mkString(" "))
  out.close
}

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

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

  val n = readInt
  def ans = (n +: (1 until n)).mkString(" ")

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

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    println((Seq(n) ++ (1 to (n - 1))).mkString(" "))
  }
}

object Code221A extends App {
    val in = new java.util.Scanner(System.in)
    val n = in.nextInt

    println( (n :: (1 to n-1).toList).mkString(" ") )
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(((2 to n).toList ::: List(1)).mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((1 :: (1 to n - 1).toList).mkString(" "))
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    println((n to 1 by -1).mkString(" "))
  }
}


This is the easy version of the problem. The only difference is that in this version $$$n \leq 2000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.

Output a single integer, the maximum number of potions you can drink without your health becoming negative.

NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toLong).toList

  val ans = {
    val cn = Array.fill[Long](n + 1, n + 1)(-1L)
    (0 to n).foreach(cn(_)(0) = 0L)

    for {
      i     <- 1 to n
      potion = an(i - 1)
      j     <- 1 to i if cn(i - 1)(j - 1) >= 0
      c      = cn(i - 1)(j - 1) + potion
    } cn(i)(j) =
      if (c >= 0) c max cn(i - 1)(j)
      else cn(i - 1)(j)

    cn(n).lastIndexWhere(_ >= 0)
  }

  println(ans)
}

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

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ").map(_.toLong)

  def slowSolution(n: Int, a: Array[Long]): Long = {
    val init = (0 to n).map {i => if (i == 0) 0l else -1l }
    val results = a.foldLeft(init) { (v, next) =>
      (0 to n).map { i =>
        if (i == 0)
          0
        else if (v(i - 1) == -1)
          -1
        else
          Math.max(v(i), v(i - 1) + next)
      }
    }
    (0 to n).filter(results(_) != -1).max
  }

  def fastSolution(n: Int, a: Array[Long]): Long = {
    val q = new mutable.PriorityQueue[Long].reverse
    val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>
      val (curResult, curSum) = state;
      if (next + curSum >= 0) {
        q.enqueue(next)
        (curResult + 1, next + curSum)
      } else if (q.nonEmpty && q.head < next) {
        val old = q.dequeue()
        q.enqueue(next)
        (curResult, curSum - old + next)
      } else {
        (curResult, curSum)
      }
    }
    result
  }

  println(fastSolution(n, a))
}

import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ").map(_.toLong)
  val init = (0 to n).map {i => if (i == 0) 0l else -1l }
  val results = a.foldLeft(init) { (v, next) =>
    (0 to n).map { i =>
      if (i == 0)
        0
      else if (v(i - 1) == -1)
        -1
      else
        Math.max(v(i), v(i - 1) + next)
    }
  }

  println((0 to n).filter(results(_) != -1).max)
}

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toLong).toList

  val ans = {
    val cn = Array.fill[Option[Long]](n + 1, n + 1)(None)
    cn(0)(0) = Some(0L)

    for {
      i     <- 1 to n
      potion = an(i - 1)
      j     <- 1 to i
    } cn(i)(j) = cn(i - 1)(j - 1).map(_ + potion) match {
      case Some(c) if c >= 0 => Some(c max cn(i - 1)(j).getOrElse(0L))
      case _                 => cn(i - 1)(j)
    }

    cn(n).lastIndexWhere(_.isDefined)
  }

  println(ans)
}

import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ").map(_.toInt)
  val init = (0 to n).map {i => if (i == 0) 0 else - 1 }
  val results = a.foldLeft(init) { (v, next) =>
    (0 to n).map { i =>
      if (i == 0)
        0
      else if (v(i - 1) == -1)
        -1
      else
        Math.max(v(i), v(i - 1) + next)
    }
  }

  println((0 to n).filter(results(_) != -1).max)
}


Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.

The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.  Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.

Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.

NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.

object A extends App {

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

  case class Car(cost: Int, volume: Int)

  val Array(n, k, s, t) = readInts(4)

  val cars = Array.fill(n) {
    val Array(c, v) = readInts(2)
    Car(c, v)
  }

  val gs = readInts(k).sorted

  def timeToTravel(dist: Int, fuel: Int): Double = {
    val distAtHiSpeed = if (fuel > dist) Math.min(fuel - dist, dist) else 0d
    val distAtLoSpeed = if (fuel >= dist) dist - distAtHiSpeed else Double.PositiveInfinity

    distAtLoSpeed * 2 + distAtHiSpeed
  }

  def can(tankVolume: Int): Boolean = {
    var currentPos = 0
    var currentTime = 0d
    var i = 0
    while (i < k && currentTime <= t) {
      val dist = gs(i) - currentPos
      currentTime += timeToTravel(dist, tankVolume)
      currentPos = gs(i)
      i += 1
    }
    currentTime += timeToTravel(s - currentPos, tankVolume)

    currentTime <= t
  }

  @annotation.tailrec
  def binSearch(low: Int, hi: Int): Int = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  val minVolume = binSearch(1, cars.maxBy(_.volume).volume)

  val suitableCars = cars.filter(_.volume >= minVolume)

  if (suitableCars.isEmpty) println(-1)
  else println(suitableCars.minBy(_.cost).cost)
}

object A extends App {

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

  case class Car(cost: Int, volume: Int)

  val Array(n, k, s, t) = readInts(4)

  val cars = Array.fill(n) {
    val Array(c, v) = readInts(2)
    Car(c, v)
  }

  val gs = readInts(k).sorted

  def timeToTravel(dist: Int, fuel: Int): Int = {
    val distAtHiSpeed = if (fuel > dist) Math.min(fuel - dist, dist) else 0
    val distAtLoSpeed = if (fuel >= dist) dist - distAtHiSpeed else t

    distAtLoSpeed * 2 + distAtHiSpeed
  }

  def can(tankVolume: Int): Boolean = {
    var currentPos = 0
    var currentTime = 0d
    var i = 0
    while (i < k && currentTime <= t) {
      val dist = gs(i) - currentPos
      currentTime += timeToTravel(dist, tankVolume)
      currentPos = gs(i)
      i += 1
    }
    currentTime += timeToTravel(s - currentPos, tankVolume)

    currentTime <= t
  }

  @annotation.tailrec
  def binSearch(low: Int, hi: Int): Int = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  val minVolume = binSearch(1, cars.maxBy(_.volume).volume)

  val suitableCars = cars.filter(_.volume >= minVolume)

  if (suitableCars.isEmpty) println(-1)
  else println(suitableCars.minBy(_.cost).cost)
}


Isart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?"We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-th (1 ≤ i ≤ m) type of ice cream form a connected subgraph. We build a new graph G with m vertices. We put an edge between the v-th and the u-th (1 ≤ u, v ≤ m, u ≠ v) vertices in G if and only if there exists a vertex in T that has both the v-th and the u-th types of ice cream in its set. The problem is to paint the vertices of G with minimum possible number of colors in a way that no adjacent vertices have the same color.Please note that we consider that empty set of vertices form a connected subgraph in this problem.As usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.

The first line contains two integer n and m (1 ≤ n, m ≤ 3·105) — the number of vertices in T and the number of ice cream types. n lines follow, the i-th of these lines contain single integer si (0 ≤ si ≤ 3·105) and then si distinct integers, each between 1 and m — the types of ice cream in the i-th vertex. The sum of si doesn't exceed 5·105. n - 1 lines follow. Each of these lines describes an edge of the tree with two integers u and v (1 ≤ u, v ≤ n) — the indexes of connected by this edge vertices.

Print single integer c in the first line — the minimum number of colors to paint the vertices in graph G. In the second line print m integers, the i-th of which should be the color of the i-th vertex. The colors should be between 1 and c. If there are some answers, print any of them.

NoteIn the first example the first type of ice cream is present in the first vertex only, so we can color it in any color. The second and the third ice cream are both presented in the second vertex, so we should paint them in different colors.In the second example the colors of the second, the fourth and the fifth ice cream should obviously be distinct.

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val cols = Array.fill(m){ 0 }
  val ices = Array.ofDim[Array[Int]](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val s = tl.nextToken.toInt
    ices(i) = Array.fill(s){tl.nextToken.toInt - 1}
  }

  var leaf = 0
  val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }
  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }
  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int): Unit = {

    val used = new mutable.BitSet
    val ics = ices(u)

    var j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) > 0) used += cols(i)
      j += 1
    }

    var next = 1

    j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) == 0) {
        while (used(next)) next += 1
        cols(i) = next
        next += 1
      }
      j += 1
    }

    j = 0
    while (j < adjs(u).length) {
      val v = adjs(u)(j)
      if (v != parent) dfs(v, u)
      j += 1
    }

  }

  dfs(0, -1)

  for (i <- cols.indices) if (cols(i) == 0) cols(i) = 1

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

  println(cols.max)
  println(cols.mkString(" "))

  Console.flush
}

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val cols = Array.fill(m){ 0 }
  val ices = Array.ofDim[Array[Int]](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val s = tl.nextToken.toInt
    ices(i) = Array.fill(s){tl.nextToken.toInt - 1}
  }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
  }

  val icesSorted = ices.sortBy(- _.length)

  val used = new mutable.BitSet

  for (ics <- icesSorted) {

    used.clear()
//println(ics.mkString(", "))
    var j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) > 0) used += cols(i)
      j += 1
    }

    var next = 1

    j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) == 0) {
        while (used(next)) next += 1
        cols(i) = next
        next += 1
      }
      j += 1
    }
  }

  for (i <- cols.indices) if (cols(i) == 0) cols(i) = 1

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

  println(cols.max)
  println(cols.mkString(" "))

  Console.flush
}

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val cols = Array.fill(m){ 0 }
  val ices = Array.ofDim[Array[Int]](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val s = tl.nextToken.toInt
    ices(i) = Array.fill(s){tl.nextToken.toInt - 1}
  }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
  }

  val icesSorted = ices.sortBy(- _.length)

  val used = new mutable.BitSet

  for (ics <- icesSorted) {

    used.clear()
//println(ics.mkString(", "))
    var j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) > 0) used += cols(i)
      j += 1
    }

    var next = 1

    j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) == 0) {
        while (used(next)) next += 1
        cols(i) = next
        next += 1
      }
      j += 1
    }
  }

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

  println(cols.max)
  println(cols.mkString(" "))

  Console.flush
}

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val cols = Array.fill(m){ 0 }
  val ices = Array.ofDim[Array[Int]](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val s = tl.nextToken.toInt
    ices(i) = Array.fill(s){tl.nextToken.toInt - 1}
  }

  val icesSorted = ices.sortBy(- _.length)

  val used = new mutable.BitSet

  for (ics <- icesSorted) {

    used.clear()
//println(ics.mkString(", "))
    var j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) > 0) used += cols(i)
      j += 1
    }

    var next = 1

    j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) == 0) {
        while (used(next)) next += 1
        cols(i) = next
        next += 1
      }
      j += 1
    }
  }

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

  println(cols.max)
  println(cols.mkString(" "))

  Console.flush
}

import scala.collection.mutable

object E extends App {

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

  val Array(n, m) = readInts(2)

  val cols = Array.fill(m){ 0 }
  val ices = Array.ofDim[Array[Int]](n)

  for (i <- 0 until n) {
    val tl = tokenizeLine
    val s = tl.nextToken.toInt
    ices(i) = Array.fill(s){tl.nextToken.toInt - 1}
  }

  val icesSorted = ices.sortBy(- _.length)

  val used = new mutable.BitSet

  for (ics <- icesSorted) {
    used.clear()
    var j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) > 0) used += cols(i)
      j += 1
    }
    var next = 1
    j = 0
    while (j < ics.length) {
      val i = ics(j)
      if (cols(i) == 0) {
        while (used(next)) next += 1
        cols(i) = next
        next += 1
      }
      j += 1
    }
  }

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

  println(cols.max)
  println(cols.mkString(" "))

  Console.flush
}


You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 100; -100 \le a, b \le 100$$$) — the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.

For each testcase, print a single integer — the maximum number of points that you can score.

NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \cdot 1 + 5 = 3$$$ points, i. e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, a, b) = readLine().split(" ").map(_.toInt)
    val s              = readLine()

    val ans =
      if (b >= 0) n * (a + b)
      else {
        val (c, _) = s.tail.foldLeft((1, s.head)) {
          case (state @ (_, p), c) if p == c => state
          case ((m, _), c)                   => (m + 1, c)
        }
        n * a + (c / 2 + 1) * b
      }

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, a, b) = readLine().split(" ").map(_.toInt)
    val s              = readLine()

    def f: Int => Int      = l => if (l == 0) 0 else a * l + b
    def g: Seq[Int] => Int = ls => ls.foldLeft(0) { case (s, l) => s + f(l) }

    val ans =
      if (b >= 0) n * f(1)
      else {
        val zeros = s.split("1").map(_.length)
        val ones  = s.split("0").map(_.length)

        (g(zeros) + f(ones.sum)) max (g(ones) + f(zeros.sum))
      }

    println(ans)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }
    rep(StdIn.readInt) { f }

    def f() {
      def calc(l: Int, a: Int, b: Int): Int =
        (a * l) + b

      def doSomething(in: String, a: Int, b: Int) = {
        val first = in.head
        val second = if (first == '1') '0' else '1'

        val part1 = in.split(second).filter(_ != "")
        val part2 = in.split(first).filter(_ != "")

        val part2Sum = part2.map { l => calc(l.length, a, b) }.sum
        val part1Sum = calc(part1.reduce(_ + _).length, a, b)

        part2Sum + part1Sum
      }

      def points(in: String, a: Int, b: Int) = {

        if (b < 0) doSomething(in, a, b)
        else {
          val ones = in.split('0')
          val zeros = in.split('1')
          val all = (ones ++ zeros).filter(_ != "")
          (all.flatMap(_.toCharArray)).map(e => calc(1, a, b)).sum
        }
      }

      val arr = (StdIn.readLine.split(" ") map (_.toInt))
      val (n, a, b) = (arr(0), arr(1), arr(2))
      val str = StdIn.readLine
      println(points(str, a, b))

    }

  }
}


You are given a function $$$f$$$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $$$x$$$. $$$x$$$ is an integer variable and can be assigned values from $$$0$$$ to $$$2^{32}-1$$$. The function contains three types of commands:  for $$$n$$$ — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$. After the execution of these commands, value of $$$x$$$ is returned.Every "for $$$n$$$" is matched with "end", thus the function is guaranteed to be valid. "for $$$n$$$" can be immediately followed by "end"."add" command can be outside of any for loops.Notice that "add" commands might overflow the value of $$$x$$$! It means that the value of $$$x$$$ becomes greater than $$$2^{32}-1$$$ after some "add" command. Now you run $$$f(0)$$$ and wonder if the resulting value of $$$x$$$ is correct or some overflow made it incorrect.If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

The first line contains a single integer $$$l$$$ ($$$1 \le l \le 10^5$$$) — the number of lines in the function. Each of the next $$$l$$$ lines contains a single command of one of three types:   for $$$n$$$ ($$$1 \le n \le 100$$$) — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$.

If overflow happened during execution of $$$f(0)$$$, then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

9
add
for 43
end
for 10
for 15
add
end
add
end

11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end

NoteIn the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for $$$n$$$" can be immediately followed by "end" and that "add" can be outside of any for loops.In the second example there are no commands "add", thus the returning value is 0.In the third example "add" command is executed too many times, which causes $$$x$$$ to go over $$$2^{32}-1$$$.

//package codeforces

/*
https://codeforces.com/contest/1175/problem/B
 */
object CatchOverFlow {

  type Statements = List[List[String]]

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

    countIncrements((1 to lines).map(_ => io.StdIn.readLine().split(" ").toList).toList, 0) match {
      case Some((result, Nil)) => println(result)
      case None => println("OVERFLOW!!!")
    }

    def countIncrements(statements: Statements, result: Long): Option[(Long, Statements)] = {
      if (result > (1l << 32) - 1)
        None
      else
        statements match {
          case Nil => Some(result, Nil)
          case statement :: rest =>

            statement match {
              case "for" :: n :: Nil =>
                countIncrements(rest, 0).flatMap {
                  case (forLoopResult, statementsAfterForLoop) =>
                    countIncrements(statementsAfterForLoop, result + forLoopResult * n.toInt)
                }

              case "end" :: Nil =>
                Some(result, rest)

              case "add" :: Nil =>
                countIncrements(rest, result + 1)
            }
        }
    }
  }

}

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

object B_1175 extends App {
  val Max   = 4294967295L
  var n     = readInt()
  var value = 0L
  val stack = mutable.Stack[Long]()

  stack.push(1)

  var overflow = false

  1 to n foreach { _ =>
    val line = readLine()
    if (!overflow) {
      line.split(" ") match {
        case Array("add") =>
          value += stack.top
          if (value > Max) overflow = true
        case Array("for", x) =>
          val mul = x.toInt * stack.top
          if (mul < Max) stack.push(mul)
          else stack.push(Max + 1)
        case Array("end") => stack.pop()
      }
    }

  }

  println(if (value >= 0 && value <= Max) value else "OVERFLOW!!!")

}

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

object B_1175 extends App {
  var n     = readInt()
  var value = 0L
  val stack = mutable.Stack[Long]()

  stack.push(1)

  1 to n foreach { _ =>
    readLine().split(" ") match {
      case Array("add")    => value += stack.top
      case Array("for", x) => stack.push(x.toInt * stack.top)
      case Array("end")    => stack.pop()
    }
  }

  println(if (value >= 0 && value <= 2147483646L) value else "OVERFLOW!!!")

}

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

object B_1175 extends App {
  var n     = readInt()
  var value = 0L
  val stack = mutable.Stack[Long]()

  stack.push(1)

  1 to n foreach { _ =>
    readLine().split(" ") match {
      case Array("add")    => value += stack.top
      case Array("for", x) => stack.push(x.toInt * stack.top)
      case Array("end")    => stack.pop()
    }
  }

  println(if (value >= 0 && value <= 2147483646L) value else "OVERFLOW")

}

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

object B_1175 extends App {
  val Max   = 2147483646L
  var n     = readInt()
  var value = 0L
  val stack = mutable.Stack[Long]()

  stack.push(1)

  var overflow = false

  1 to n foreach { _ =>
    val line = readLine()
    if (!overflow) {
      line.split(" ") match {
        case Array("add") =>
          value += stack.top
          if (value > Max) overflow = true
        case Array("for", x) =>
          val mul = x.toInt * stack.top
          if (mul < Max) stack.push(mul)
          else stack.push(Max + 1)
        case Array("end") => stack.pop()
      }
    }

  }

  println(if (value >= 0 && value <= Max) value else "OVERFLOW!!!")

}


Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers ti (1 ≤ ti ≤ 109), separated by spaces.

Print a single number — the maximum number of not disappointed people in the queue.

NoteValue 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.

import java.util.StringTokenizer

object _545D extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).sorted.toArray

  def calc(i: Int, sum: Int, acc: Int): Int = {
    if (i >= n) acc
    else {
      if (sum <= a(i)) calc(i + 1, sum + a(i), acc + 1)
      else calc(i + 1, sum, acc)
    }
  }
  println(calc(0, 0, 0))
}

import scala.io.StdIn

object CF545D extends App {
  val n = StdIn.readInt
  val ts = StdIn.readLine.split(' ').map(_.toInt)

  var peopleLeft = ts.sorted
  var notDisappointed = 0
  var sum = 0
  while (peopleLeft.nonEmpty) {
    peopleLeft = peopleLeft.dropWhile(_ < sum)
    if (peopleLeft.nonEmpty) {
      sum += peopleLeft.head
      notDisappointed += 1
      peopleLeft = peopleLeft.tail
    }
  }
  println(notDisappointed)
}

object D545 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readLongs(n).sorted
    var curr = 0L
    var res = 0
    for(num <- in) {
      if(curr <= num) {
        res += 1
        curr += num
      }
    }
    println(res)
  }

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

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

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

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

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

}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.immutable.Queue
import scala.collection.mutable.ArrayBuffer

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def lowerBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (!(array(mid) < value)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val n = nextInt
    val service_time = new Array[Int](n)
    for (i <- 0 until n) {
      service_time(i) = nextInt
    }
    util.Sorting.quickSort(service_time)
    var (res, sum) = (0, 0)
    for (i <- 0 until n) {
      if (service_time(i) >= sum) {
        res += 1
        sum += service_time(i)
      }
    }
    out.println(res)
  }

  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

/**
 * <a href="http://codeforces.com/problemset/problem/545/D"/>
 *
 * @author pvasilyev
 * @since 13 Apr 2016
 */
object Problem150 extends App {
  private val n: Int = scala.io.StdIn.readInt()
  private val ints: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  util.Arrays.sort(ints)
  val answer: Array[Int] = new Array[Int](n)
  answer(0) = 1
  var sum = ints(0)
  for (i <- 1 until n) {
    if (sum <= ints(i)) {
      sum += ints(i)
      answer(i) = answer(i - 1) + 1
    } else {
      answer(i) = answer(i - 1)
    }
  }
  println(answer(n - 1))
}

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

import scala.collection.mutable

object C {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = new MultiTreeSet[Long]
    for (i <- 0 until n) {
      m.add(nextLong)
    }
    var waitTime = 0L
    var ans = 0L
    var current = m.first()
    while (current != 0 && !m.map.isEmpty) {
      if (m.count(current) > 0) {
        if (current >= waitTime) {
          ans += 1
//          out.print(current + " ")
          m.remove(current)
          waitTime += current
        } else {
          current = m.map.ceilingKey(waitTime)
        }
      } else {
        current = m.first()
      }
    }
    out.println(ans)
    return 0
  }
}

object _545D extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[Int]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt).sorted
  }

  override def solve(input: Input) = {
    var t: Long = 0L
    var ans = 0

    for(i <- input) {
      //debug(input, i, t, ans)
      if(t <= i) {
        ans += 1
        t += i
      }
    }
    ans
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

object _545D extends CodeForcesApp {
  override type Input = List[Int]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt).sorted
  }

  override def solve(input: Input) = {
    var (ans, t) = (0, 0)
    for (i <- input if t <= i) {
      ans += 1
      t += i
    }
    ans
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

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

object Main {
  def main(args: Array[String]) {
    StdIn.readLine(); // ignoring

    val q = StdIn.readLine().split(" ").map(Integer.parseInt).to[PriorityQueue].reverse;

    def f : Long => Int = t => {
      if(q.isEmpty)
        0
      else {
        val v = q.dequeue();

        t <= v match {
          case true => f(t + v) + 1;
          case false => f(t);
        }
      }
    }

    println(f(0));
  }
}

import scala.io.StdIn._

object D extends App {
  val n = readInt()
  val P = readLine().split(" ").map(_.toInt).sortWith(_ < _)
//  println(P.mkString(" "))

  def solve(): Int = {
    var happy = 0
    var needToWait = 0
    for (i <- 0 until P.length) {
//      println(s"($needToWait <= ${P(i)})")
      if (needToWait <= P(i)) {
        needToWait += P(i)
        happy += 1
      }

      if (needToWait > 1000000000) return happy
    }
    happy
  }

  println(solve())

}

import scala.io.StdIn

/**
  * http://codeforces.com/problemset/problem/545/D
  **/
object DQueue {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val timesToServe = StdIn.readLine().split(" ").map(_.toInt)
    val (nbHappyPersons, _) = timesToServe.sorted.foldLeft((0, 0)) { case ((nbHappyPersons, accTime), timeToServe) =>
      if (accTime > timeToServe) (nbHappyPersons, accTime)
      else (nbHappyPersons + 1, accTime + timeToServe)
    }
    println(nbHappyPersons)
  }
}

import scala.io.StdIn
object b extends App {
  var r = 0
  StdIn.readLine
  StdIn.readLine.split(" ")
    .map(_.toInt)
    .sorted
    .reduce((s,x) => if (s<=x) {r+=1; s+x} else s)
  println(r+1)
}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    StdIn.readLine()
    print(StdIn.readLine()
      .split(" ")
      .map(_.toInt)
      .sorted
      .foldLeft( (0,0) )((r,c) =>
        if(r._1 > c) {
          r
        } else {
          (r._1 + c, r._2 + 1)

        }
      )._2)

//    val in = scala.io.Source.stdin.getLines()
//    val n = in.next().toInt

//    val Array(n, h, k) = StdIn.readLine().split(" ").map(_.toLong)
//
//    val A:Array[Long] = StdIn.readLine().split(" ").map(_.toLong)
//
//
//    var curH = 0L
//    var t = 0L
//    for ( i <- 0 to A.length - 1) {
//      val nd = math.max(A(i) -  (h - curH),0)
//      val d = nd / k + (if (nd % k == 0) 0  else 1)
//      t += d
//      curH = math.max(0L, curH - d * k ) + A(i)
//    }
//    val d = curH / k + (if (curH % k == 0) 0  else 1)
//    t += d
//    print(t)
//    print(A.foldLeft((0L,0L))({
//      case(b,a) =>
//        if(i == 0) {
//          (a,a)
//        } else {
//          val k = math.max(0, math.min(b._2 - 1, a))
//          (b._1 + k, k)
//        }
//    })._1)
  }

}

import java.util.StringTokenizer

object _545D extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).sorted.toArray

  def calc(i: Int, sum: Int, acc: Int): Int = {
    if (i >= n) acc
    else {
      calc(i + 1, sum + a(i), if (sum <= a(i)) acc + 1 else acc)
    }
  }

  println(calc(0, 0, 0))
}

import java.util

/**
 * <a href="http://codeforces.com/problemset/problem/545/D"/>
 *
 * @author pvasilyev
 * @since 13 Apr 2016
 */
object Problem150 extends App {
  private val n: Int = scala.io.StdIn.readInt()
  private val ints: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  util.Arrays.sort(ints)
  val latency: Array[Int] = new Array[Int](n)
  latency(0) = 0
  for (i <- 1 until n) {
    latency(i) = latency(i - 1) + ints(i - 1)
  }
  val answer: Array[Int] = new Array[Int](n)
  answer(0) = 1
  for (i <- 1 until n) {
    if (latency(i) > ints(i)) {
      answer(i) = answer(i - 1)
    } else {
      answer(i) = answer(i - 1) + 1
    }
  }
  println(answer(n - 1))
}

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

import scala.collection.mutable

object C {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  def solve: Int = {
    val n = nextInt
    val m = new MultiTreeSet[Long]
    for (i <- 0 until n) {
      m.add(nextLong)
    }
    var waitTime = 0L
    var ans = 0L
    var current = m.first()
    while (current != 0 && !m.map.isEmpty) {
      if (m.count(current) > 0) {
        if (current >= waitTime) {
          ans += 1
          out.print(current + " ")
          m.remove(current)
          waitTime += current
        } else {
          current = m.map.ceilingKey(waitTime)
        }
      } else {
        current = m.first()
      }
    }
    out.println(ans)
    return 0
  }
}

object _545D extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[Int]
  override type Output = Int

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt).sorted
  }

  override def solve(input: Input) = {
    var t = 0
    var ans = 0

    for(i <- input) {
      //debug(input, i, t, ans)
      if(t <= i) {
        ans += 1
      }
      t += i
    }
    ans
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

import scala.io.StdIn._

object D extends App {
  val n = readInt()
  val P = readLine().split(" ").map(_.toInt).sortWith(_ < _)

  def solve(): Int = {
    var happy = 0
    var needToWait = 0
    for (i <- 0 until P.length) {
      if (needToWait <= P(i)) happy += 1
      needToWait += P(i)

      if (needToWait > 1000000000) return happy
    }
    happy
  }

  println(solve())

}

import scala.io.StdIn._

object D extends App {
  val n = readInt()
  val P = readLine().split(" ").map(_.toInt).sortWith(_ < _)

  def solve(): Int = {
    var happy = 1
    var needToWait: BigInt = P(0)
    for (i <- 1 until P.length) {
//      println(s"consider $i $needToWait <= ${P(i)}")
      if (needToWait <= P(i)) happy += 1

      needToWait += P(i)

      if (needToWait > 1000000000) return happy
    }
    happy
  }

  println(solve())

}

import scala.io.StdIn._

object D extends App {
  val n = readInt()
  val P = readLine().split(" ").map(_.toInt).sortWith(_ < _)

  def solve(): Int = {
    var happy = 1
    var needToWait = P(0)
    for (i <- 1 until P.length) {
//      println(s"consider $i $needToWait <= ${P(i)}")
      if (needToWait <= P(i)) happy += 1

      needToWait += P(i)
    }
    happy
  }

  println(solve())
}

import scala.io.StdIn._

object D extends App {
  val n = readInt()
  val P = readLine().split(" ").map(_.toInt).sortWith(_ < _)

  def solve(): Int = {
    var happy = 1
    var needToWait: BigInt = P(0)
    for (i <- 1 until P.length) {
//      println(s"consider $i $needToWait <= ${P(i)}")
      if (needToWait <= P(i)) happy += 1

      needToWait += P(i)
    }
    happy
  }

  println(solve())

}

import scala.io.StdIn

/**
  * http://codeforces.com/problemset/problem/545/D
  **/
object DQueue {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val timesToServe = StdIn.readLine().split(" ").map(_.toInt)
    val (nbHappyPersons, _) = timesToServe.sorted.foldLeft((0, 0)) { case ((nbHappyPersons, accTime), timeToServe) =>
        if (accTime > timeToServe) (nbHappyPersons, accTime + timeToServe)
        else (nbHappyPersons + 1, accTime + timeToServe)
    }
    println(nbHappyPersons)
  }
}