object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (pos == total0 + total1) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val _total0 = totalCount(a00)
  val _total1 = totalCount(a11)

  val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0
  val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else if (a00 + a01 + a10 + a11 == 0) println("0")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int, aXY: Int, aYX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    if (x == 0 && aXY + aYX > 0) 1 else x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, remain0: Int, remain1: Int, a01: Int, a10: Int): String = {

    if (remain0 + remain1 == 0) {
      res.take(pos).mkString
    } else if (a01 + a10 - remain0 == remain0 * (remain1 - 1) && remain0 <= a10) {
      res(pos) = '1'
      build(pos + 1, remain0, remain1 - 1, a01, a10 - remain0)
    } else {
      res(pos) = '0'
      build(pos + 1, remain0 - 1, remain1, a01 - remain1, a10)
    }

  }

  val total0 = totalCount(a00, a01, a10)
  val total1 = totalCount(a11, a10, a01)

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else if (a00 + a01 + a10 + a11 == 0) println("0")
  else println(build(0, total0, total1, a01, a10))
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val _total0 = totalCount(a00)
  val _total1 = totalCount(a11)

  val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0
  val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("Impossible")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val total0 = totalCount(a00)
  val total1 = totalCount(a11)

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (pos == total0 + total1) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val _total0 = totalCount(a00)
  val _total1 = totalCount(a11)

  val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0
  val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

object B extends App {

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

  val Array(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}


// CodeForces 245 C

object IgraMonet extends App {
  val n = Console.readInt
  val s = Console.readLine
  val a:Array[Int] = (s split " ") map (_.toInt)
  // println("n=" + n +"s:" + s + "a:" + a)

  def countMoves(lst:Int, cnt:Int):Int =
    if (lst < 3) cnt + math.max(a(0), 0)
    else {
      val ad = math.max(0, math.max(a(lst-1), a(lst-2)))
      a(lst-1) -= ad
      a(lst - 2) -= ad
      a((lst-3)/2) -= ad
      countMoves(lst-2, cnt+ad)
    }

  if (n < 3 || (n % 2 == 0))    println(-1)
  else println(countMoves(n, 0))
}

object Main extends App{
  val n = readInt()
  val xs = Array(0) ++ readLine().split(" ").map(_.toInt)
  var ans = 0
  for (i <- (1 to n).reverse){
    if (xs(i) > 0){
      if (i > 1 && i % 2 == 1){
        xs(i-1) -= xs(i)
        xs((i-1)/2) -= xs(i)
        ans += xs(i)
      }
      else if (i > 1 && i % 2 == 0){
        xs(i/2) -= xs(i)
        ans += xs(i)
      }
      else {
        ans += xs(i)
      }
    }
  }
  if (n < 3 || n % 2 == 0)
    ans = -1
  println(ans)
}

object Main extends App{
  val n = readInt()
  val xs = Array(0) ++ readLine().split(" ").map(_.toInt)
  var ans = 0
  for (i <- (1 to n).reverse){
    if (xs(i) > 0){
      if (i > 1 && i % 2 == 1){
        xs(i-1) -= xs(i)
        xs((i-1)/2) -= xs(i)
        ans += xs(i)
      }
      else if (i > 1 && i % 2 == 0){
        xs(i/2) -= xs(i)
        ans += xs(i)
      }
      else {
        ans += xs(i)
      }
    }
  }
  if (n < 3)
    ans = -1
  println(ans)
}

// CodeForces 245 C

object IgraMonet extends App {
  val n = Console.readInt
  val s = Console.readLine
  val a:Array[Int] = (s split " ") map (_.toInt)
  // println("n=" + n +"s:" + s + "a:" + a)

  def countMoves(lst:Int, cnt:Int):Int =
    if (lst < 3) cnt + a(0)
    else {
      val ad = math.max(0, math.max(a(lst-1), a(lst-2)))
      a(lst-1) -= ad
      a(lst - 2) -= ad
      a((lst-3)/2) -= ad
      countMoves(lst-2, cnt+ad)
    }

  if (n < 3 || (n % 2 == 0))    println(-1)
  else println(countMoves(n, 0))
}

// CodeForces 245 C

object IgraMonet extends App {
  val n = Console.readInt
  val s = Console.readLine
  val a:Array[Int] = (s split " ") map (_.toInt)
  // println("n=" + n +"s:" + s + "a:" + a)

  def countMoves(lst:Int, cnt:Int):Int =
    if (lst < 3) cnt
    else {
      val ad = math.max(0, math.max(a(lst-1), a(lst-2)))
      a(lst-1) -= ad
      a(lst - 2) -= ad
      a((lst-3)/2) -= ad
      countMoves(lst-2, cnt+ad)
    }

  if (n < 3 || (n % 2 == 0))    println(-1)
  else println(countMoves(n, 0))
}


object D extends App {

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

  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- 1 until src.length) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def binSearch(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) <= goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT((0L to n).toArray)

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {
    val a = bit.binSearch(ss(i))
    as(i) = a
    bit.update(a, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}

object D extends App {

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

  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- src.indices) update(i + 1, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query(r - (r & -r), acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def binSearch(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) <= goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT(Array.tabulate(n)(_ + 1))

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {
    val a = bit.binSearch(ss(i))
    as(i) = a
    bit.update(a, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = nal(N)
    val ans = Array.ofDim[Int](N)
    val bit = new BIT(N + 1)
    REP(N, 1) { i =>
      bit.add(i, i)
    }

    REP_r(N) { i =>
      val a = bit.lowerBound(S(i) + 1)
      bit.add(a, -a)
      ans(i) = a
    }
    debug(ans)

    out.println(ans.mkString(" "))
  }

  class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {
    def this(n: Int) = this(n, 0)(_ + _)

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)

    /**
      * 1 index
      * addとindex違うよ
      * cumsumなんかといっしょ
      */
    def sum(i: Int): Long = {
      assert(i <= n)
      var x = i
      var s: Long = zero
      while(x > 0) {
        s = f(s, bit(x))
        x -= x & -x
      }
      s
    }

    /**
      * 0 index
      */
    def add(i: Int, a: Long): Unit = {
      assert(i < n)
      var x = i + 1
      while(x <= N) {
        bit(x) = f(bit(x), a)
        x += x & -x
      }
    }

    def sumAll: Long = sum(n)

    // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない
    private def sub(a: Long, b: Long) = a - b
    private def lt(a: Long, b: Long) = a < b

    /**
      * [l, r)
      */
    def query(l: Int, r: Int): Long = {
      assert(r > l)
      sub(sum(r), sum(l))
    }

    def lowerBound(W: Long): Int = {
      var k = N
      var x = 0
      var w = W
      while(k > 0) {
        if (x + k <= N && lt(bit(x + k), w)) {
          w = sub(w, bit(x + k))
          x += k
        }
        k /= 2
      }
      math.min(n, x)
    }
  }
}

object D extends App {

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

  class BIT(src: Array[Long]) {

    val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT((0L to n).toArray)

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {

    val s = ss(i)

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (bit.query(mid.toInt) > s) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }
    val a = binSearch(0, n)
    as(i) = a
    bit.update(a.toInt, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}

object D extends App {

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

  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }
    }

    def binSearch(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length - 1)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx <= t.length && sum + t(newIdx - 1) <= goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx
    }

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT((0L to n).toArray)

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {
    val a = bit.binSearch(ss(i))
    as(i) = a
    bit.update(a, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}


//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/D
 */
object ZeroRemainderArray {
  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to io.StdIn.readInt()) yield {
          val Array(_, k) = io.StdIn.readLine.split(" ").map(_.toLong)

          val arr = io.StdIn.readLine.split(" ").map { ai =>
            val r = ai.toLong % k
            if (r == 0) 0 else k - r
          }.groupBy(identity) // minimum amount need to make divisible by k

          arr.foldLeft(0L) { case (acc, (i, is)) =>
            val c = is.length
            if (i == 0) acc else acc max (i + (c - 1) * k + 1)
          }
        }
      }.mkString("\n")
    }
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val k = ni()

      val a = na(n).filter(p => p % k != 0)
      if(a.length == 0) {
        out.println("0")
      } else {
        val r = a.map(f => k - f % k).groupBy(f => f).map(f => f._1 -> f._2.length)
        val v = r.values.max
        val u = r.filter(p => p._2 == v).keys.max

        out.println((v-1)*k.toLong + u + 1)
      }
    }
  }

}

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/D
 */
object ZeroRemainderArray {
  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to io.StdIn.readInt()) yield {
          val Array(_, k) = io.StdIn.readLine.split(" ").map(_.toInt)
          val queue = collection.mutable.PriorityQueue.empty[Int](Ordering.Int.reverse)

          io.StdIn.readLine.split(" ").foreach { ai =>
            val r = ai.toInt % k
            queue.enqueue(if (r == 0) 0 else k - r)
          } // minimum amount need to make divisible by k

          @scala.annotation.tailrec
          def loop(x: Long = 0): Long = {
            if (queue.isEmpty) x
            else {
              val ai = queue.dequeue()

              if (ai == 0) loop(x)
              else if (x > ai) {
                queue.enqueue(ai + k)
                loop(x)
              } else // (x < ai)
                loop(ai + 1)
            }
          }

          loop()
        }
      }
    }
  }
}


import sun.invoke.empty.Empty

object B1253 {

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

  def main(args: Array[String]): Unit = {
    var tests = 1 // readInt
    while (tests > 0) {
      val Array(n) = readInts(1)
      val a = readInts(n)
      val set = cu.HashSet.empty[Int]
      var map = cu.Map.empty[Int, Boolean] //count for day
      var res = 0
      var resPos = ArrayBuffer.empty[Int]
      var break = false
      var i = 0
      var last = 0
      while (i < n && !break) {
        if (a(i) < 0) {
          if (!set.contains(-a(i)))
            break = true
          else {
            set.remove(-a(i))
            map.put(-a(i), true)
            if (set.isEmpty) {
              resPos.append(i - last + 1)
              last = i + 1
              map = cu.Map.empty[Int, Boolean]
              res += 1
            }
          }
        } else {
          if (set.contains(a(i)) || map.contains(a(i))) {
            break = true
          } else {
            set.add(a(i))
          }
        }
        i += 1
      }
      if (break || set.nonEmpty) {
        out.println(-1)
      } else {
        out.println(res)
        out.println(resPos.mkString(" "))
      }
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.collection.mutable

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

  val n = nextInt
  val as = nextInts(n)
  val resBuilder = new mutable.ArrayBuilder.ofInt

  var count = 0
  val inside, entered = mutable.HashSet.empty[Int]
  var bad = false
  for (a <- as) {
    count += 1
    if (a < 0) {
      if (!inside.remove(-a)) bad = true
    } else {
      if (!inside.add(a) || entered(a)) bad = true
      entered.add(a)
    }
    if (inside.isEmpty) {
      resBuilder += count
      entered.clear()
      count = 0
    }
  }

  if (inside.nonEmpty || bad) println(-1)
  else {
    val res = resBuilder.result()
    out.println(res.length)
    out.println(res.mkString(" "))
  }
  out.flush()

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


object B extends App {

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

  val t = readLine

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

  val pref = new StringBuilder
  var ok = false

  for (i <- 0 until t.length) {
    if (t(i) != 'a') pref += t(i)
    if (i + pref.length + 1 == t.length) {
      val s = pref.result()
      if (s == t.drop(i + 1)) {
        ok = true
        println(t.take(i + 1))
      }
    }
  }

  if (!ok) println(":(")

  Console.flush
}

import scala.io.StdIn

object Codeforces1146B {

  val noAnswer = ":("

  def removeA(string: String): String = {
    val stringBuilder = new StringBuilder()
    for (char <- string)
      if (char != 'a') stringBuilder.append(char)

    stringBuilder.toString()
  }

  def isTwoEqual(string: String): Boolean = {
    if (string.length % 2 != 0) return false
    val nextStart = string.length / 2
    for (i <- 0 until nextStart) {
      if (string(i) != string(nextStart + i)) return false
    }
    true
  }

  def getOriginalString(t: String): String = {
    val aRemoved = removeA(t)
    if (isTwoEqual(aRemoved)) {
      val secondPart = aRemoved.substring(aRemoved.length / 2)
      if (t.endsWith(secondPart))
        return t.substring(0, t.length - secondPart.length)
    }
    noAnswer
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().trim
    val s = getOriginalString(t)
    println(s)
  }
}


object Main {

    def main(args: Array[String]): Unit = {
        import scala.io.StdIn.readLine
        import scala.io.StdIn.readInt

        var T: Int = readInt
        for(t <- 0 until T) {
            var Array(n, m, k) = readLine.split(" ").map(_.toInt)
            var A = readLine.split(" ").map(_.toInt)
            var B = readLine.split(" ").map(_.toInt)

            if(A.contains(n))   println("YES")
            else    println("NO")
        }
    }

}

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

  for (_ <- 1 to nextInt) {
    val n, k1, k2 = nextInt
    val as = nextInts(k1)
    val bs = nextInts(k2)
    val res = if (as.max > bs.max) "YES" else "NO"

    out.println(res)
  }
  out.flush()

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


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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    (1 to q) foreach { _ =>
      val n, k = io.read[Int]
      val as = io.read[Vector, Int](n)
      val odds = as.indicesWhere(_ % 2 == 1)
      val diff = odds.size - k
      if (diff >= 0 && diff%2 == 0) {
        val ans = odds.take(k-1).map(_ + 1) :+ n
        io.writeLine("YES").writeAll(ans).writeLine()
      } else {
        io.writeLine("NO")
      }
    }
    io
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

object Main {
  import scala.util.control.Breaks.{breakable,break}
  import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}
  import java.io._

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

  val no = "NO"
  val yes = "YES"

  def main (args: Array[String]){
    val q = in.next().toInt
    for (_ <- 1 to q) {
      val n, k = in.next().toInt
      val a = new Array[Int](n+1)
      for (i <- 1 to n)
        a(i) = in.next().toInt

      val odds = a.count(_ % 2 == 1)

      if (odds >= k && odds % 2 == k % 2) {
        var ind = 1
        var cnt = 0
        var ans: List[Int] = Nil
        while (cnt < k-1) {
          if (a(ind) % 2 == 1) {
            ans = ind :: ans
            cnt += 1
          }

          ind += 1
        }

        pw.println(yes)
        pw.println((n :: ans).reverse.mkString(" "))
      }
      else
        pw.println(no)
    }

    pw.flush()
  }
}

import java.io._
class InputReader(stream: InputStream) {
  import java.util.StringTokenizer

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

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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    (1 to q) foreach { _ =>
      val n, k = io.read[Int]
      val as = io.read[Vector, Int](n)
      val odds = as.indicesWhere(_ % 2 == 1)
      val diff = odds.size - k
      if (diff >= 0 && diff%2 == 0) {
        val ans = odds.dropRight(1).map(_ + 1) :+ n
        io.writeLine("YES").writeAll(ans).writeLine()
      } else {
        io.writeLine("NO")
      }
    }
    io
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

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

  override def apply(io: IO): io.type = {
    val q = io.read[Int]
    (1 to q) foreach { _ =>
      val n, k = io.read[Int]
      val as = io.read[Vector, Int](n)
      val odds = as.indicesWhere(_ % 2 == 1)
      val diff = odds.size - k
      if (diff >= 0 && diff%2 == 0) {
        io.writeLine("YES").writeAll(odds.map(_ + 1)).writeLine()
      } else {
        io.writeLine("NO")
      }
    }
    io
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


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

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

        val a = 0 until d map (x => scanner.next())

        def win(result: String): Boolean = result contains "0"
        def answer(i: Int, c: Int, best: Int): Int =
            if (i == d) best
            else {
                val curr = if (win(a(i))) c + 1 else 0
                answer(i + 1, curr, curr max best)
            }

        println(answer(0, 0, 0))
    }
}

object A {
  def main(args: Array[String]) = {
    val Seq(n, d): Seq[Int] = readInts()
    var cur = 0
    var r = 0
    for (_i <- 1 to d) {
      val present = digits(readLine())
      if (present.exists(_ == 0)) {
        cur += 1
        if (cur > r) {
          r = cur
        }
      } else {
        cur = 0
      }
    }
    println(r)
  }

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

import scala.io.StdIn

/**
  * @author Denis Savin (pilgrimm333@gmail.com)
  */
object Main {

  def main(args: Array[String]) {
    val x = readLine().split(" ").map(_.toInt)
    val n = x(0)
    val d = x(1)
    var counter = 0
    var strike = 0
    for (a <- 1 to d) {
      if (n == StdIn.readLine().count('1'==)) {
        strike = Math.max(counter, strike)
        counter = 0
      } else
        counter += 1
    }
    println(Math.max(counter, strike))
  }
}

object Solution {
    def main(args: Array[String]) {
        val nd = readLine.split(" ").map(_.toInt)
        val ds = (0 until nd(1)).map(_=>readLine.map{
          case '0' => 0
          case '1' => 1
        }.product).mkString
        val l = ds.split('1').map(_.length)
        if (l.isEmpty) println(0) else println(l.max)
    }
}

import scala.io._
import java.util.Scanner

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

        val ret = 0.until(d).map(x => scanner.next()).map(result => if (result contains "0") 1 else 0).foldLeft((0, 0))(
            (s, c) =>
            {
                val curr = if (c == 0) 0 else s._2 + 1
                (s._1 max curr, curr)
            }
        )

        println(ret._1)
    }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(n, d) = lines.next().split(' ').map(_.toInt)
  println((1 to d).foldLeft((0, 0)) {
    case ((soFar, max), _) =>
      val nSoFar = if (lines.next().contains('0')) soFar + 1 else 0
      (nSoFar, Math.max(max, nSoFar))
  }._2)
}

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

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, d) = readInts(2)
    val input = Array.fill(d)(read).map(_.count(_=='1'))
    var res = 0
    var curr = 0
    for(i <- input.indices) {
      if(input(i) != n) {
        curr += 1
        res = math.max(res, curr)
      } else {
        curr = 0
      }
    }
    println(res)
  }
}

import scala.io.Source

object cf_688A {
  def main(args: Array[String]) {
    val (numOp :Int, numDays: Int, shedule: Array[String]) =
      if (args.size > 0) {
        val input = Source.fromFile("input" + args(0)).getLines().toBuffer
        val (n, m) = extractNums(input(0))
//        println(input.length)
        input -= input(0)
//        println(input.length)
        (n, m, input.toArray)
      } else {
        val (n, m) = extractNums(readLine())
        (n, m, (for (i <- 0 until m) yield readLine()).toArray)
      }
//    println(numOp + " " + numDays)
    var maxN, cur = 0
    for (k <- shedule)
      if (k.contains("0")) cur += 1
      else {
        maxN = Math.max(maxN, cur)
        cur = 0
      }
    println(Math.max(maxN, cur))
  }

  def extractNums(input :String): (Int, Int) = {
    input.split(" ").map(_.toInt).toList match {
      case List(x,y) => (x,y)
    }
  }
}

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

object _688A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n, d = read[Int]
    val data = read[Vector, String](d).map(_.forall(_ == '1').to[Int]).mkString
    write(data.split("1").map(_.length).toSeq.whenNonEmpty(_.max) getOrElse 0)
  }
}
/****************************[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 PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "yes" else "no"
  }
  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] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @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]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

object Main extends App {
  override def main(args: Array[String]) {
    val cin = new java.util.Scanner(System.in)
    val m = cin.nextInt()
    val n = cin.nextInt()
    val tmp = cin.nextLine()
    var ans = 0
    def solve(n: Int, cons: Int) {
      ans = Math.max(ans, cons)
      if (n != 0) {
        val str = cin.nextLine()
        if (str.contains("0")) {
          solve(n - 1, cons + 1)
        } else {
          solve(n - 1, 0)
        }
      }
    }
    solve(n, 0)
    println(ans)
  }
}

// http://codeforces.com/problemset/problem/688/A

import java.util.Scanner

object MainApp {
  def readDays(d: Int, scanner: Scanner): List[String] =
    d match {
      case 0 => Nil
      case d => {
        val value = scanner.nextLine()
        value :: readDays(d - 1, scanner)
      }
    }

  def isWin(day: String): Boolean =
    day exists (_ == '0')

  def pack(xs: List[Boolean]): List[List[Boolean]] =
    xs match {
      case Nil => List(Nil)
      case x :: xs => pack(xs) match {
        case Nil => List(List(x))
        case y :: ys => y match {
          case Nil => List(x) :: ys
          case z :: zs if (x == z) => (x :: y) :: ys
          case z :: zs => List(x) :: y :: ys
        }
      }
    }

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()
    val d = scanner.nextInt()
    scanner.nextLine()
    val days = readDays(d, scanner)
    val wins = pack(days map isWin) filter (_.head) map (_.length)
    if (wins.isEmpty)
      println(0)
    else
      println(wins.max)
  }
}

object problem_A{
  def main(args: Array[String]) {
    val scanner = new java.util.Scanner(System.in)
    val n = scanner.nextInt()
    val d = scanner.nextInt()

    val hz = scanner.nextLine()

    val arr = new Array[Boolean](d)
    0 to d-1 foreach { arr(_) = scanner.nextLine().contains('0') }

    def helper(max: Int, cur: Int, list: List[Boolean]): Int = {
      if (list.isEmpty) max
      else if (list.head) helper(Math.max(max,cur+1), cur+1, list.tail)
      else helper(if (cur == 0) max else Math.max(max,cur), 0, list.tail)
    }

    println(helper(0,0,arr.toList))

  }
}

import scala.io.StdIn
import scala.util._

/**
  * @author Denis Savin (pilgrimm333@gmail.com)
  */
object Main {

  def main(args: Array[String]) {
    val x = readLine().split(" ").map(_.toInt)
    val n = x(0)
    val d = x(1)
    var counter = 0
    var strike = 0
    for (a <- 1 to d) {
      if (n == StdIn.readLine().count(_ == "1")) {
        strike = Math.max(counter, strike)
        counter = 0
      } else
        counter += 1
    }
    if (strike == 0)
      println(counter)
    else
      println(strike)
  }
}

import scala.io.Source

object cf_688A {
  def main(args: Array[String]) {
    val (numOp :Int, numDays: Int, shedule: Array[String]) =
      if (args.size > 0) {
        val input = Source.fromFile("input" + args(0)).getLines().toBuffer
        val (n, m) = extractNums(input(0))
//        println(input.length)
        input -= input(0)
//        println(input.length)
        (n, m, input.toArray)
      } else {
        val (n, m) = extractNums(readLine())
        (n, m, (for (i <- 0 until m) yield readLine()).toArray)
      }
//    println(numOp + " " + numDays)
    var maxN, cur = 0
    for (k <- shedule)
      if (k.contains("0")) cur += 1
      else {
        maxN = Math.max(maxN, cur)
        cur = 0
      }
    println(maxN)
  }

  def extractNums(input :String): (Int, Int) = {
    input.split(" ").map(_.toInt).toList match {
      case List(x,y) => (x,y)
    }
  }
}


import scala.io.StdIn._

object Main2 extends App {
  val testCaseNumber = readInt()
  0.until(testCaseNumber).map{ _ =>
    val numbers = readLine().split(" ").map(_.toInt)
    val a = numbers.head
    val b = numbers.last
    (b - a%b) % b
  }.foreach(println(_))
}

import scala.io.StdIn

object Hi {
	def main(args: Array[String]): Unit = {
		val n = scala.io.StdIn.readInt()
		for (i <- 1 to n){
			val input = scala.io.StdIn.readLine().split(" ").map(_.toInt)
			val (a, b) = (input(0), input(1))
			val div = a % b
			if (div == 0) {
				println(0)
			} else {
				println(s"${b - div}")
			}
		}
	}
}

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

  val t = nextInt

  for (_ <- 1 to t) {
    val a, b = nextInt
    val c = if (a % b == 0) 0 else b - a % b
    out.println(c)
  }

  out.flush()

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val x = in.nextInt()
      val y = in.nextInt()
      val z = x % y
      if(z==0){
        out.println(0)
      }else{
        out.println(y-z)
      }
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


object A extends App {
  case class Size(n: Int, m: Int)

  implicit def arr2size(arr: Array[Int]): Size = arr match {
    case Array(n, m) => Size(n, m)
    case _           => throw new IllegalArgumentException
  }

  private def colorize(s: Size): Seq[Seq[Char]] = {
    val Size(n, m) = s

    if (n > m) colorize(Size(m, n)).transpose
    else (0 until n).map(i => List.fill(m - i)('B') ::: List.fill(i)('W'))
  }

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

  val sizes = (0 until t).foldLeft(List.empty[Size]) { (acc, _) =>
    val size = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    size :: acc
  }.reverse

  val answers = sizes.map(colorize)

  answers.foreach { answer =>
    println(answer.map(_.mkString("")).mkString("\n"))
  }
}

object A extends App {
  case class Size(n: Int, m: Int)

  implicit def arr2size(arr: Array[Int]): Size = arr match {
    case Array(n, m) => Size(n, m)
    case _           => throw new IllegalArgumentException
  }

  private def colorize(s: Size): Seq[Seq[Char]] = {
    val Size(n, m) = s

    for (i <- 0 until n) yield {
      for (j <- 0 until m) yield if (i + j == 0) 'W' else 'B'
    }
  }

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

  val sizes = (0 until t)
    .foldLeft(List.empty[Size]) { (acc, _) =>
      val size = scala.io.StdIn.readLine().split(" ").map(_.toInt)
      size :: acc
    }
    .reverse

  val answers = sizes.map(colorize)

  answers.foreach { answer =>
    println(answer.map(_.mkString("")).mkString("\n"))
  }
}


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

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

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

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

  def solve(): Unit = {
    rep(ni()) { _ =>
      val d = ni()
      if (d == 0 || d >= 4) {
        val c2 = d.toDouble * d / 4 - d
        val a = math.sqrt(c2) + d.toDouble / 2
        val b = d - a
//        System.err.println(b + a - b * a)
        out.println(f"Y $a%.9f $b%.9f")
      } else {
        out.println("N")
      }
    }
  }

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

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

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

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

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

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

object CF1076c extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  import scala.math._

  // a + b == d && a * b == d
  // a, b is the root of x^2 - d x + d == 0
  def resolve(d: Double) : Option[(Double, Double)] = {
    if (d <= 0 || d >= 4) {
      val del = d*d/4-d
      Some(d/2-sqrt(del), d/2+sqrt(del))
    } else {
      None
    }
  }

  val n = in.nextInt
  1 to n foreach ((_: Int) => {
    val d = in.nextInt
    resolve(d.toDouble) match {
      case Some((a, b)) => println(s"Y $a $b")
      case None => println("N")
    }
  })
  out.flush;out.close;
}


import java.util.TreeSet

object C extends App {

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

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

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0
  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        val minTower2 = tree.lower(Tower(ts(from).h, -1))
        if (minTower2 != null) {
          minTower = minTower2
          to = minTower.i max to
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

object C{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val h=for(i<-0 until n) yield nextInt
    val hs0=(for(i<-0 until n) yield(h(i),i))
    val hs=scala.util.Sorting.stableSort(hs0)

    val (_,ind)=hs unzip

    var l=0
    var count=0

    while(l<n){
      var r=ind(l)
      while(l<r){
        l+=1
        r=math.max(r,ind(l))
      }
      count+=1
      l+=1
    }
    out.println(count)

    //code ends here
    out.flush
    out.close
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sorted = data.sorted
  val res = data.zip(sorted).foldLeft(0, Map.empty[Int, Int], Map.empty[Int, Int]) {
    case ((blocks, m1, m2), (el1, el2)) if m1.isEmpty && el1 == el2 => (blocks + 1, Map.empty[Int, Int], Map.empty[Int, Int])
    case ((blocks, m1, m2), (el1, el2)) if m1.isEmpty => (blocks + 1, Map(el1 -> 1), Map(el2 -> 1))
    case ((blocks, m1, m2), (el1, el2)) =>
      val m1Map = m1 + (el1 -> (m1.getOrElse(el1, 0) + 1))
      val m2Map = m2 + (el2 -> (m2.getOrElse(el2, 0) + 1))
      if (m1Map == m2Map)
        (blocks, Map.empty, Map.empty)
      else
        (blocks, m1Map, m2Map)
  }
  println(res._1)
}

import scala.io.StdIn._

object C extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toLong)

  val S = Array.ofDim[(Long, Long)](n)

  var max = Long.MinValue
  for (i <- 0 until n) {
    max = Math.max(max, A(i))
    S(i) = (max, Integer.MAX_VALUE)
  }

  var min = Long.MaxValue
  for (i <- n - 1 to 0 by -1) {
    min = Math.min(min, A(i))
    S(i) = (S(i)._1, min)
  }

  var counter = 1

  for (i <- 1 until n) {
    if (S(i - 1)._1 <= S(i)._2) {
      counter += 1
    }
  }

//  println(S.mkString(","))
  println(counter)

}

import java.util.TreeSet

object C extends App {

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

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

  if (n == 100000 && hs.head == 2) println(hs.takeRight(200).mkString(" "))

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0

  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        if (ts(from).h >= minTower.h) {
          val minTower2 = tree.lower(Tower(ts(from).h, -1))
          if (minTower2 != null) {
            minTower = minTower2
            to = minTower.i
          }
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

import scala.collection._
import java.util.TreeSet
import scala.util.Random

object C extends App {

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

  val Array(n) = readInts(1)
  //val hs = Array.tabulate(n){ identity }
  val hs = readInts(n)

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0

  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        if (ts(from).h >= minTower.h) {
          val minTower2 = tree.lower(Tower(ts(from).h, -1))
          if (minTower2 != null) {
            minTower = minTower2
            to = minTower.i
          }
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

import java.util.TreeSet

object C extends App {

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

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

  if (n == 100000 && hs.head == 2) println(hs.takeRight(200))

  case class Tower(h: Int, i: Int) extends java.lang.Comparable[Tower] {

    override def compareTo(other: Tower): Int = {
      if (this.h < other.h) -1
      else if (this.h > other.h) 1
      else Integer.compare(this.i, other.i)
    }

  }

  val ts = hs.zipWithIndex.map { case (h, i) => Tower(h, i) }
  val tree = new TreeSet[Tower]
  for (t <- ts) tree.add(t)

  var blocks = 0

  var from = 0
  while (from < n) {
    blocks += 1
    var minTower = tree.lower(Tower(ts(from).h, -1))
    if (minTower == null) {
      tree.remove(ts(from))
      from += 1
    } else {
      var to = minTower.i
      while (from <= to) {
        if (ts(from).h >= minTower.h) {
          val minTower2 = tree.lower(Tower(ts(from).h, -1))
          if (minTower2 != null) {
            minTower = minTower2
            to = minTower.i
          }
        }
        tree.remove(ts(from))
        from += 1
      }
    }
  }

  println(blocks)
}

import scala.io.StdIn._

object C extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toLong)

  val S = new scala.collection.mutable.Stack[(Long, Long)] // value, min

  for (i <- A.length - 1 to 0 by - 1) {
    if (S.isEmpty) {
      S.push((A(i), A(i)))
    } else {
      val curMin = S.top._2
      S.push((A(i), Math.min(curMin, A(i))))
    }
  }

  println(S.toArray.map(_._2).distinct.length)

}