Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $$$l$$$ centimeters after haircut, where $$$l$$$ is her favorite number. Suppose, that the Alice's head is a straight line on which $$$n$$$ hairlines grow. Let's number them from $$$1$$$ to $$$n$$$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $$$l$$$, given that all hairlines on that segment had length strictly greater than $$$l$$$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types:  $$$0$$$ — Alice asks how much time the haircut would take if she would go to the hairdresser now.  $$$1$$$ $$$p$$$ $$$d$$$ — $$$p$$$-th hairline grows by $$$d$$$ centimeters. Note, that in the request $$$0$$$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$l$$$ ($$$1 \le n, m \le 100\,000$$$, $$$1 \le l \le 10^9$$$) — the number of hairlines, the number of requests and the favorite number of Alice. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the initial lengths of all hairlines of Alice. Each of the following $$$m$$$ lines contains a request in the format described in the statement. The request description starts with an integer $$$t_i$$$. If $$$t_i = 0$$$, then you need to find the time the haircut would take. Otherwise, $$$t_i = 1$$$ and in this moment one hairline grows. The rest of the line than contains two more integers: $$$p_i$$$ and $$$d_i$$$ ($$$1 \le p_i \le n$$$, $$$1 \le d_i \le 10^9$$$) — the number of the hairline and the length it grows by.

For each query of type $$$0$$$ print the time the haircut would take.

NoteConsider the first example:  Initially lengths of hairlines are equal to $$$1, 2, 3, 4$$$ and only $$$4$$$-th hairline is longer $$$l=3$$$, and hairdresser can cut it in $$$1$$$ second.  Then Alice's second hairline grows, the lengths of hairlines are now equal to $$$1, 5, 3, 4$$$  Now haircut takes two seonds: two swings are required: for the $$$4$$$-th hairline and for the $$$2$$$-nd.  Then Alice's first hairline grows, the lengths of hairlines are now equal to $$$4, 5, 3, 4$$$  The haircut still takes two seconds: with one swing hairdresser can cut $$$4$$$-th hairline and with one more swing cut the segment from $$$1$$$-st to $$$2$$$-nd hairline.  Then Alice's third hairline grows, the lengths of hairlines are now equal to $$$4, 5, 4, 4$$$  Now haircut takes only one second: with one swing it is possible to cut the segment from $$$1$$$-st hairline to the $$$4$$$-th.

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

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

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

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

  def solve(): Unit = {
    val N, M, L = ni()
    val A = nal(N)

    val over = Array.ofDim[Boolean](N)
    var cnt = 0
    def add(i: Int): Unit = {
      over(i) = true
      val l = i > 0 && over(i - 1)
      val r = i < N - 1 && over(i + 1)
      if (l && r) cnt -= 1
      else if (!l && !r) cnt += 1
    }
    rep(N) { i =>
      if (A(i) > L) {
        add(i)
      }
    }

    rep(M) { _ =>
      ni() match {
        case 0 => out.println(cnt)
        case 1 =>
          val p = ni() - 1
          val d = ni()
          if (A(p) <= L && A(p) + d > L) {
            add(p)
          }
          A(p) += d
      }
    }
  }

  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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    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
  }
}

import java.util

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 Array(n, m, l) = readInts(3)
  val as = readInts(n)

  val t = new util.TreeMap[Int, Int]()
  var segmentStart = -1
  for (i <- 0 until n) {
    if (as(i) > l) {
      if (segmentStart < 0) segmentStart = i
      t.put(segmentStart, i)
    } else {
      segmentStart = -1
    }
  }

  var count = t.size()

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

  for (_ <- 1 to m) {
    val s = readLine
    if (s == "0") {
      println(count)
    } else {
      val Array(_, _p, d) = s.split(" ").map(_.toInt)
      val p = _p - 1
      if (as(p) <= l) {
        as(p) += d
        if (as(p) > l) {
          val left = t.floorEntry(p)
          val right = t.ceilingEntry(p)
          if (left != null && left.getValue + 1 == p) {
            if (right != null && right.getKey - 1 == p) {
              t.remove(right.getKey)
              t.replace(left.getKey, right.getValue)
              count -= 1
            } else {
              t.replace(left.getKey, p)
            }
          } else if (right != null && right.getKey - 1 == p) {
            t.remove(right.getKey)
            t.put(p, right.getValue)
          } else {
            t.put(p, p)
            count += 1
          }
        }
      }
    }
  }

  Console.flush
}

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

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

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

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

  def solve(): Unit = {
    val N, M, L = ni()
    val A = nal(N)

    var cnt = 0
    def add(i: Int): Unit = {
      val l = i > 0 && A(i - 1) > L
      val r = i < N - 1 && A(i + 1) > L
      if (l && r) cnt -= 1
      else if (!l && !r) cnt += 1
    }
    rep(N) { i =>
      if (A(i) > L) {
        add(i)
      }
    }

    rep(M) { _ =>
      ni() match {
        case 0 => out.println(cnt)
        case 1 =>
          val p = ni() - 1
          val d = ni()
          if (A(p) <= L && A(p) + d > L) {
            add(p)
          }
          A(p) += d
      }
    }
  }

  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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    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 Main {
  import java.io.PrintStream

  def main(args: Array[String]): Unit = {
    val s = new Main()
    val ps = new PrintStream(Console.out)
    Console.withOut(ps) {
      s.solve()
    }
    ps.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
  import scala.Console

  val MOD = 1000000007

  def solve(): Unit = {
    val N, M, L = ni()
    val A = na(N)

    val over = mutable.Set[Int]()
    var cnt = 0
    def add(i: Int): Unit = {
      over += i
      val l = over.contains(i - 1)
      val r = over.contains(i + 1)
      if (l && r) cnt -= 1
      else if (!l && !r) cnt += 1
    }
    rep(N) { i =>
      if (A(i) > L) {
        add(i)
      }
    }

    rep(M) { _ =>
      ni() match {
        case 0 => println(cnt)
        case 1 =>
          val p = ni() - 1
          val d = ni()
          if (A(p) <= L && A(p) + d > L) {
            add(p)
          }
          A(p) += d
      }
    }
  }

  class InputReader(reader: BufferedReader) {
    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(Console.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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    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
  }
}


Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him.  The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2n + 1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads.    To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square  has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.

The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit. The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 — the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and . All numbers ai are positive integers, not exceeding 100.

Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.

NotePicture for the sample test. Green color denotes the additional street lights.

object Main {
  def main(args: Array[String]) {
    val std = scala.io.StdIn
    val n = std.readInt()
    val s : Array[Int] = std.readLine().split(" ").map( _.toInt )

    def f( i : Int ) : (Int,Int) = {
      if ( i * 2 - 2 > s.length ) {
        (0,0)
      }
      else {
        val res1 = f( i *  2 )
        val res2 = f( i * 2 + 1 )

        val path1 = if ( i * 2 - 2 < s.length ) res1._2 + s(i * 2 -2) else 0
        val path2 = if ( i * 2 - 1 < s.length ) res2._2 + s(i * 2 -1 ) else 0

        val add = Math.abs(path1  - path2 )
        val pathForBoth = Math.max( path1, path2 )

        //println( i, add, pathForBoth )

        ( res1._1 + res2._1 + add, pathForBoth )
      }

    }

    println( f(1)._1 )

  }
}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)
  val as = Array(0) ++ readInts((2 << n) - 2)

  var total = 0L

  for (layer <- n - 1 to 0 by -1) {
    val l = (1 << layer)
    val r = (2 << layer) - 1
    for (i <- l to r) {
      val u = 2 * i - 1
      val v = u + 1
      val min = as(u) min as(v)
      val max = as(u) max as(v)
      val add = max - min
      total += add
      as(u / 2) += max
    }
  }

  println(total)
}


Polycarp and his friends want to visit a new restaurant. The restaurant has $$$n$$$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $$$1$$$ to $$$n$$$ in the order from left to right. The state of the restaurant is described by a string of length $$$n$$$ which contains characters "1" (the table is occupied) and "0" (the table is empty).Restaurant rules prohibit people to sit at a distance of $$$k$$$ or less from each other. That is, if a person sits at the table number $$$i$$$, then all tables with numbers from $$$i-k$$$ to $$$i+k$$$ (except for the $$$i$$$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $$$k$$$.For example, if $$$n=8$$$ and $$$k=2$$$, then:  strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant;  strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $$$k=2$$$. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.You are given a binary string $$$s$$$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $$$s$$$.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?For example, if $$$n=6$$$, $$$k=1$$$, $$$s=$$$ "100010", then the answer to the problem will be $$$1$$$, since only the table at position $$$3$$$ can be occupied such that the rules are still satisfied.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of tables in the restaurant and the minimum allowed distance between two people. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ consisting of "0" and "1" — a description of the free and occupied tables in the restaurant. The given string satisfy to the rules of the restaurant — the difference between indices of any two "1" is more than $$$k$$$. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2\cdot 10^5$$$.

For each test case output one integer — the number of tables that you can occupy so as not to violate the rules of the restaurant. If additional tables cannot be taken, then, obviously, you need to output $$$0$$$.

NoteThe first test case is explained in the statement.In the second test case, the answer is $$$2$$$, since you can choose the first and the sixth table.In the third test case, you cannot take any free table without violating the rules of the restaurant.

//package codeforces.contests._1367

object _3 {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

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

      val occupied = arr.collect { case (c, i) if c == '1' => i + 1 }.toVector

      println {
        if (occupied.isEmpty)
          (1 to n by k + 1).size
        else {
          val first = occupied.head
          val last = occupied.last

          val a = (1 until first by k + 1).count(_ + k < first)
          val b = occupied.sliding(2).map { case Vector(x, y) => (x + k + 1 until y).by(k + 1).count(_ + k < y); case _ => 0 }.sum
          val c = (last + k + 1 to n by k + 1).size
          a + b + c
        }
      }
    }
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nk = readIntLine()
      val l = readLine().toCharArray.map(_ == '1').toList
      handle(l, nk.last)
    }
  }

  def handle(list: List[Boolean], k: Int): Unit = {
    def helper(l: List[Boolean], prevDist: Int, acc: Int): Int = l match {
      case Nil => acc
      case b :: bs => if (b) if (prevDist < k) helper(bs, 0, acc - 1) else helper(bs, 0, acc)
      else if (prevDist < k) helper(bs, prevDist + 1, acc) else helper(bs, 0, acc + 1)
    }

    println(helper(list, k, 0))
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val tmp = StdIn.readLine().split(" ").map(_.toInt)
      val (n, k) = (tmp(0), tmp(1))
      var str = StdIn.readLine()
      val blocks = str.split("1").filter(_.length>0)

      var i = 0
      var res = 0
      for (b <- blocks) {
        if (i == 0 && str.startsWith("0")) {
          res += (b.length / (k+1))
        } else if (i == blocks.length - 1 && str.endsWith("0")) {
          res += (b.length / (k+1))
        } else {
          res += math.max(0, (b.length - k) / (k+1))
        }
        i += 1
      }
      if (str.forall(ch => ch == '0') && str.length % (k+1) > 0) res += 1
      println(res)
    }
  }
}

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

  val t = readInt()

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

    val (ans, _) = (sn.zipWithIndex.collect { case (x, i) if x == 1 => i } :+ (n + k)).foldLeft((0, -k - 1)) {
      case ((c, l), r) =>
        (c + (r - l - 1 - k).max(0) / (k + 1), r)
    }

    println(ans)
  }
}

object Main extends App {
  val r = new FastScanner(java.lang.System.in)
  val o = new java.io.PrintWriter(java.lang.System.out)
  for(_ <- 1 to r.nextInt()) {
    val n = r.nextInt()
    val mindist = r.nextInt()
    val s = r.nextToken(n)
    def f(x: Int, prefix: Boolean, suffix: Boolean): Int = {
      var t = x
      if(prefix) t += mindist
      if(suffix) t += mindist
      if(t <= mindist) 0
      else ((t + 1) / (mindist + 1)) - 1
    }
    def loop(k: Int, t: Int, ans: Int): Int = {
      if(k == n) {
        if(t > 0) ans + f(t, t == n, true) else ans
      } else if(s(k) == '1') {
        loop(k + 1, 0, ans + f(t, t == k, false))
      } else {
        loop(k + 1, t + 1, ans)
      }
    }
    o.println(loop(0, 0, 0))
  }
  o.close()
}

import scala.annotation.tailrec
import scala.collection.mutable.StringBuilder

object FastScanner {
  val zero = 0.toByte
  val cr = '\r'.toByte
  val nl = '\n'.toByte
  val BUFFER_SIZE = 0x10000
}

class FastScanner(private val input: java.io.InputStream) {
  private val b = new Array[Byte](FastScanner.BUFFER_SIZE)
  private var n = 0
  private var pos = 0
  private var eof = false
  private def read ():Boolean = {
    if (eof) {
      return false
    }
    pos = 0
    n = input.read(b)
    if (n < 0) {
      eof = true
    }
    n > 0
  }
  private def nextByte(): Byte = {
    if (pos >= n && !read ()) {
      0
    } else {
      val r = b(pos)
      pos += 1
      r
    }
  }
  def nextToken(k: Int = -1): String = {
    val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()
    var b = skipBlanks()
    assert(b > 0)
    while(b > 32) {
      sb.append(b.toChar)
      b = nextByte()
    }
    //sb.append('1')
    sb.toString
  }
  @tailrec
  private def skipBlanks(): Byte = {
    val b = nextByte()
    if(b > 32 || b < 1) b else skipBlanks()
  }
  def nextInt():Int = {
    val b = skipBlanks()
    @tailrec
    def f(t: Int): Int = {
      val b = nextByte ()
      if (b <= 32) t else f(10 * t + (b - 48))
    }
    require(b > 0)
    if (b < 48) -f(0) else f(b - 48)
  }
}

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

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

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

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

    n.times {
      val m = in.nextInt()
      val d = in.nextInt()

      val temLine = in.line()
      //      println(temLine)
      val line = "1" + ("0" * d) + temLine + ("0" * d) + "1"
      //      println(line)

      val tableStr = line.split("").map(_.toInt)
      //      printArr(tableStr)

      var r          = 0
      var wasLast1   = false
      var last1Index = 1
      for ((element, i) <- tableStr.zipWithIndex) {
        if (element == 1 && wasLast1) {
          val diff = (i + 1) - last1Index
          val l    = findD(diff - 1, d)
          //          println(s"L: ****************** = $l $last1Index ${i + 1}")
          r = r + l
          last1Index = i + 1
        } else if (element == 1) {
          wasLast1 = true
          last1Index = i + 1
        }
      }
      //      println("Result: =>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=> " + r)
      println(r)
    }
  }

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

  def findD(n: Int, d: Int): Int = {
    //    println("............")
    //    println(n, d)
    val base     = (2 * d) + 1
    val reminder = n - base
    if (reminder >= 0) {
      //      println(base)
      //      println(reminder)
      //      println((reminder / (d + 1)))
      val resu = (reminder / (d + 1)) + 1
      //      println("............")
      resu
    } else {
      0
    }

  }

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val tmp = StdIn.readLine().split(" ").map(_.toInt)
      val (n, k) = (tmp(0), tmp(1))
      var str = StdIn.readLine()
      val blocks = str.split("1").filter(_.length>0)

      var i = 0
      var res = 0
      for (b <- blocks) {
        if (i == 0 && str.startsWith("0")) {
          res += (b.length / (k+1))
        } else if (i == blocks.length - 1 && str.endsWith("0")) {
          res += (b.length / (k+1))
        } else {
          res += math.max(0, (b.length - k) / (k+1))
        }
        i += 1
      }
      if (str.forall(ch => ch == '0') && str.length < k+1) res += 1
      println(res)
    }
  }
}


You are given two positive integers $$$n$$$ and $$$k$$$. Print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.For example, if $$$n=3$$$, and $$$k=7$$$, then all numbers that are not divisible by $$$3$$$ are: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$$$. The $$$7$$$-th number among them is $$$10$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$2 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$).

For each test case print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.

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

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    var arr = StdIn.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val k = arr(1)

    val ans = ListBuffer.empty[Int]
    var l: Long = 1
    var r: Long = 100000000000L
    while (Math.abs(r - l) > 1){
      var mid: Long = (r + l) / 2L
      val x: Long = mid / n
      val y: Long = mid - x
      if(y == k && mid % n != 0){
        l = mid
        r = mid
      }else if (y < k){
        l = mid
      }else{
        r = mid
      }
    }
    println(l)
  }
}

import scala.io.StdIn

object C {

   def solution(n: Int, k: Int): Int = k + (k - 1) / (n - 1)

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine.toInt)) {
         val Seq(n, k) = StdIn.readLine.split(" ").toSeq.map(_.toInt)
         println(solution(n, k))
      }
   }
}

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 C640B(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 C640B(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 gap = n - 1

      val r =if(k % gap == 0) - 1 else k % gap
      val x = k / gap
      out.println(x * n + r)
    }
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (i, j)      = (k / (n - 1), k % (n - 1))
    val ans         = i * n + (if (j == 0) j - 1 else j)

    println(ans)
  }
}

object C extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val ans         = k + (k - 1) / (n - 1)

    println(ans)
  }
}

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

  override def solve(io: IO) = io.repeat {
    val n, k = io.read[Long]
    val ans = if ((k*n)%(n-1) == 0) {
      (k * n)/(n - 1) - 1
    } else {
      (k * n)/(n - 1)
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  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)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

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

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[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")

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

  def write(obj: Any*): this.type = writeAll(obj)
  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 = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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 C extends App {

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

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (i, j)      = (k / (n - 1), k % (n - 1))
    val rs         = i * n + (if (j == 0) j - 1 else j)
    println(rs)
  }
}


n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.

The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 1012) — the number of people and the number of wins. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.

Output a single integer — power of the winner.

NoteGames in the second sample:3 plays with 1. 3 wins. 1 goes to the end of the line.3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val k = io.read[Long]
    val powers = io.read[List, Int](n)
    val best = powers.max

    @tailrec
    def fight(players: List[Int], wins: Int): Int = {
      players match {
        case p1 :: ps if wins >= k || p1 == best => p1
        case p1 :: p2 :: ps if p1 > p2 => fight(players = p1 :: (ps :+ p2), wins = wins + 1)
        case p1 :: p2 :: ps if p1 < p2 => fight(players = p2 :: (ps :+ p1), wins = 1)
      }
    }

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

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

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

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

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

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

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

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

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

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

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

object Codeforces extends App {
  val Array(n, k) = readLine split ' ' map(_.toLong)
  val players = readLine split ' ' map(_.toInt)
  val window = math.min(n, k)
  val queue = mutable.Queue[Int](players: _*)
  var current = queue.dequeue()
  var winCount = 0
  while (queue.nonEmpty && winCount < window) {
    for (_ <- 1L to window) {
      if (winCount < window) {
        val player = queue.dequeue()
        if (player < current) {
          winCount += 1
          queue.enqueue(player)
        }
        else {
          winCount = 1
          queue.enqueue(current)
          current = player
        }
      }
    }
  }
  println(current)
}

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val k = io.read[Long]
    val powers = io.read[List, Int](n)
    val best = powers.max

    @tailrec
    def fight(players: List[Int], wins: Int): Int = {
      players match {
        case p1 :: ps if wins >= k || p1 == best => p1
        case p1 :: p2 :: ps if p1 > p2 => fight(players = p1 :: (ps :+ p2), wins = wins + 1)
        case p1 :: p2 :: ps if p1 < p2 => fight(players = p2 :: (ps :+ p1), wins = 0)
      }
    }

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

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

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

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

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

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

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

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

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

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


Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$.

The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements.

Print the number of segments in Petya's array with the sum of elements less than $$$t$$$.

NoteIn the first example the following segments have sum less than $$$4$$$:  $$$[2, 2]$$$, sum of elements is $$$-1$$$  $$$[2, 3]$$$, sum of elements is $$$2$$$  $$$[3, 3]$$$, sum of elements is $$$3$$$  $$$[4, 5]$$$, sum of elements is $$$3$$$  $$$[5, 5]$$$, sum of elements is $$$-1$$$

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val T = nl()
    val A = na(N)
    val cum = Array.ofDim[Long](N + 1) // index 1ずれてる
    rep(N) { i =>
      cum(i + 1) = cum(i) + A(i)
    }

    val cntr = new ZippedCounter(sort(cum.clone()))
    var ans = 0L
    rep_r(N) { i =>
      cntr.add(cum(i + 1))
      val x = T + cum(i)
      ans += cntr.countLt(x)
    }

    out.println(ans)
  }

  def lowerBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = l + (h - l) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }
    step(-1, a.length)
  }

  class BIT(n: Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val bit = Array.ofDim[Int](N + 1)

    /**
      * 0 index
      */
    def sum(i: Int): Int = {
      var x = i + 1
      var s = 0
      while(x > 0) {
        s += bit(x)
        x -= x & -x
      }
      s
    }

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

  def sort(as: Array[Long]): Array[Long] = {
    val n = as.length
    val sorted = new java.util.PriorityQueue[Long](n)
    rep(n)(i => sorted.add(as(i)))
    rep(n)(i => as(i) = sorted.poll())
    as
  }

  type A = Long

  /**
    * N + 1の範囲に分割する
    *
    * 例:
    * as = [3 5 6]
    * (, 3] => 0  (3, 5] => 1 (5, 6] => 2 (6, ) => 3
    *
    */
  class Zipper(as: Array[A]) {
    def apply(x: A): Int = {
      lowerBound(as, x)
    }
  }

  /**
    * まじめなBSTつくるの大変だからlesserThanをカウントできるだけのものを用意した
    * java.util.TreeSetじゃできない
    */
  class ZippedCounter(as: Array[A]) {
    val n = as.length
    val zip = new Zipper(as)
    val bit = new BIT(n + 1) // zipされたレンジはn + 1個になる
    var cnt = 0

    /**
      * @param x 必ずレンジの上限を追加しないいけない
      */
    def add(x: A): Unit = {
      val i = zip(x)
      assert(i < n && x == as(i))
      bit.add(i, 1)
      cnt += 1
    }

    def countLt(x: A): Int = {
      // レンジの上限の値しか存在しないので、ある値より小さい = より小さいレンジ と置き換えることができる
      val i = zip(x)
      if (i > 0) bit.sum(i - 1)
      else 0
    }

    def countLe(x: A): Int = {
      countLt(x + 1)
    }

    def countGe(x: A): Int = {
      cnt - countLt(x)
    }

    def countGt(x: A): Int = {
      cnt - countLe(x)
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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


Happy new year! The year 2020 is also known as Year Gyeongja (경자년, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of $$$n$$$ strings $$$s_1, s_2, s_3, \ldots, s_{n}$$$ and $$$m$$$ strings $$$t_1, t_2, t_3, \ldots, t_{m}$$$. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings $$$x$$$ and $$$y$$$ as the string that is obtained by writing down strings $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings $$$s_1$$$ and $$$t_1$$$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if $$$n = 3, m = 4, s = $$${"a", "b", "c"}, $$$t =$$$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size $$$n$$$ and $$$m$$$ and also $$$q$$$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?

The first line contains two integers $$$n, m$$$ ($$$1 \le n, m \le 20$$$). The next line contains $$$n$$$ strings $$$s_1, s_2, \ldots, s_{n}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. The next line contains $$$m$$$ strings $$$t_1, t_2, \ldots, t_{m}$$$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $$$1$$$ and at most $$$10$$$. Among the given $$$n + m$$$ strings may be duplicates (that is, they are not necessarily all different). The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2\,020$$$). In the next $$$q$$$ lines, an integer $$$y$$$ ($$$1 \le y \le 10^9$$$) is given, denoting the year we want to know the name for.

Print $$$q$$$ lines. For each line, print the name of the year as per the rule described above.

10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020

sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja

NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

import scala.io.StdIn

object NewYearAndNaming extends App {

  val l1 = StdIn.readLine().split(" ")
  val n = l1(0).toInt
  val m = l1(1).toInt

  val s = StdIn.readLine().split(" ")
  val t = StdIn.readLine().split(" ")

  val q = StdIn.readLine().toInt

  for (i <- 1 to q) {
    val year = StdIn.readLine().toInt
    if (i == q) {
      print(impl(s, t, n, m, year))
    } else {
      println(impl(s, t, n, m, year))
    }
  }

  def impl(s: Array[String], t: Array[String], n: Int, m: Int, year: Int): String = {
    val sIndex = year % n match {
      case 0 => n - 1
      case notZero => notZero - 1
    }

    val tIndex = year % m match {
      case 0 => m - 1
      case notZero => notZero - 1
    }

    s(sIndex) + t(tIndex)
  }
}

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

  val n, m = nextInt
  val s, t = nextLine.split(" ")
  val q = nextInt

  for (_ <- 1 to q) {
    val y = nextInt - 1
    val j = y % n
    val i = y % m
    val res = s(j) + t(i)
    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 S extends App {
    val lengths = readLine().split(' ').map(_.toInt)
    val arr1 = readLine().split(' ')
    val arr2 = readLine().split(' ')
    val cnt = readLine().toInt

    1.to(cnt).map(_ => readLine().toInt).foreach {year =>
        val (ind1, ind2) = ((year - 1) % lengths(0), (year - 1) % lengths(1))
        val res = arr1(ind1) + arr2(ind2)
        System.out.println(res)
    }
}

import scala.io.StdIn

object Codeforces1284A extends App {
  StdIn.readLine()
  val s = StdIn.readLine().split("\\s+")
  val t = StdIn.readLine().split("\\s+")
  var q = StdIn.readLine().toInt
  while (q > 0) {
    val y = StdIn.readLine().toLong - 1
    println(s((y % s.length).toInt) + t((y % t.length).toInt))
    q -= 1
  }
}


Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the ai-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold:   thread x is not updated (it has no new messages);  the list order 1, 2, ..., n changes to a1, a2, ..., an.

The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 105). The next line contains a list of n space-separated integers a1, a2, ..., an where ai (1 ≤ ai ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the ai are distinct.

Output a single integer — the number of threads that surely contain a new message.

NoteIn the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.In the second test case, there may be no new messages at all, since the thread order hasn't changed.In the third test case, only thread 1 can contain no new messages.

object cf165b extends App {
  val n = readLine.toInt
  val arr = readLine.split(' ').map(_.toInt).reverse.toList
  println(n - (arr zip ((n + 2) :: arr)).span(p => p._1 < p._2)._1.length)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  println(n - 1 - in.next().split(' ').map(_.toInt - 1).reverse.sliding(2).takeWhile(i => i.last < i.head).length)
}

import collection.mutable.Queue

object test6 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)
    var i=a.length-2
    while(i>=0 && a(i)<a(i+1)) i-=1
    println(i+1)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val r =
      if(n == 1) 0
      else n - 1 - a.reverse.sliding(2).takeWhile(t => t(0) > t(1) ).size
    println(r)
  }
}

import scala.collection.Set

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map(_.toInt)

  var i = t - 1;
  while (i > 0 && threads(i) > threads(i - 1)) {
    i -= 1
  }
  println(i)
}

object cf165b extends App {
  val n = readLine.toInt
  val arr = readLine.split(' ').map(_.toInt).reverse.toList
  println((arr zip ((n + 2) :: arr)).span(p => p._1 < p._2)._1.length)
}

object cf165b extends App {
  val n = readLine.toInt
  var ans = 0
  var arr = Array.ofDim[Boolean](n + 1)
  var nxt = 1
  readLine.split(' ').map(_.toInt).map { i =>
    arr(i) = true
    if (nxt != i) ans += 1
    while (nxt <= n && arr(nxt)) nxt += 1
  }
  println(ans)
}

object cf165b extends App {
  val n = readLine.toInt
  var ans = 0
  var arr = Array.ofDim[Boolean](n + 1)
  var nxt = 1
  def ans(xs: List[Int]): Int = {
    if (xs.isEmpty) 0 else {
      val (ys, m :: zs) = xs.span(_ != xs.min)
      ys.length + ans(zs)
    }
  }
  readLine.split(' ').map(_.toInt).map { i =>
    arr(i) = true
    if (nxt < i) ans += 1
    while (nxt <= n && arr(nxt)) nxt += 1
  }
  println(ans)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  println(in.next().split(' ').map(_.toInt - 1).reverse.sliding(2).takeWhile(i => i.last < i.head).length)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val visited = Array.ofDim[Boolean](n)
  val line = in.next().split(' ').map(_.toInt - 1).foldLeft(0, 0) {
    case ((k, sum), el) if el == k =>
      visited(el) = true
      ((k + 1 until n).find(i => !visited(i)).getOrElse(-1), sum)
    case ((k, sum), el) if el > k =>
      visited(el) = true
      (k, sum + 1)
    case ((k, sum), el) =>
      visited(el) = true
      (k, sum)
  }
  println(line._2)
}

import collection.mutable.Queue

object test6 extends App {
    val n=readLine.toInt
    val a=readLine.split(" ").map(_.toInt)
    var count=0
    var i=0
    while(a(i)!=1) {count+=1;i+=1}
    println(count)
}

object Main {

  class Node(val value: Int) {
    var left: Option[Node] = None
    var right: Option[Node] = None

    def leftCount: Int =
      Seq(left.map(_.leftCount), right.map(_.leftCount), left.map(_ => 1)).flatten.sum

    def add(node: Node) {
      if (node.value < this.value) {
        left match {
          case None => left = Some(node)
          case Some(n0) => n0.add(node)
        }
      } else {
        right match {
          case None => right = Some(node)
          case Some(n0) => n0.add(node)
        }
      }
    }

    def add(ls: TraversableOnce[Int]) {
      for(i <- ls) {
        val node = new Node(i)
        this.add(node)
      }
    }
  }

  object Tree {
    private var root: Option[Node] = None

    def add(ls: Array[Int]) {
      val rs = if (root == None) {
        root = Some(new Node(ls.head))
        ls.tail
      } else ls
      root.map(_.add(rs))
    }

    def count = root.map(_.leftCount).get
  }

  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    Tree.add(a)
    println(Tree.count)
  }
}

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map((s: String) => s.toInt)

  var num = 0
  for (i <- Range(0, t - 1)) {
    if (threads(i) > threads(i + 1)) {
      num += 1
    }
  }
  println(num)
}

import scala.collection.Set

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map((s: String) => s.toInt)
  var set = Set[Int]() ++ threads

  var num = 0
  for (i <- Range(0, t)) {
    set = set - threads(i)
    if (set.exists((x) => x < threads(i))) {
      num += 1
      num += threads.slice(0, i).filter(_ < threads(i)).size
    }
  }
  println(num)
}

import scala.collection.Set

object Multithreading extends App {

  val t = readInt //num tests
  val threads = readLine.split(' ').map((s: String) => s.toInt)
  var set = Set[Int]() ++ threads

  var num = 0
  for (i <- Range(0, t - 1)) {
    set = set - threads(i)
    if (set.exists((x) => x < threads(i))) {
      num += 1
    }
  }
  println(num)
}