Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$.

Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set.

import scala.io.StdIn
import scala.util.control.Breaks

object Main extends App {

  val n = StdIn.readInt()

  for (i <- 0 to n-1) {
    val k = StdIn.readInt()
    val st: Array[String] = StdIn.readLine().split(" ")
    val arr: Array[Int] = st.map(_.toInt)

    var res: Int = 0

    //O(n^2) - TL
//    for (i <- 0 to k-1) {
//      var good: Boolean = true
//      Breaks.breakable {
//        for (j <- i + 1 to k - 1) {
//          if (arr(j) < arr(i)) {
//            good = false
//            if (!good) Breaks.break
//          }
//        }
//      }
//      if (!good) {
//        res += 1
//      }
//    }

    //O(n)
    var min = arr(arr.size-1)
    for (i <- k-1 to 0 by -1) {
      if (arr(i) > min) {
        res += 1
      }
      min = Math.min(arr(i), min)
    }

    println(res)
  }

}

//package codeforces.contest1213

import scala.collection.immutable.TreeSet

object BadPrices {

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

      println {
        val indexedSeq = io.StdIn.readLine.split(" ").map(_.toInt)

        (0 to n - 2)
          .foldRight((0, TreeSet(indexedSeq.last))) {
            case (i, (res, set)) =>
              val v = indexedSeq(i)
              val minFound = set.until(v).nonEmpty

              (if (minFound) res + 1 else res, set + v)
          }
          ._1
      }
    }
  }

}

//package codeforces.contest1213

import scala.collection.immutable.TreeSet

object BadPrices {

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

      println {
        val indexedSeq = io.StdIn.readLine.split(" ").map(_.toInt)

        (0 to n - 2)
          .foldRight((0, collection.mutable.TreeSet(indexedSeq.last))) {
            case (i, (res, set)) =>
              val v = indexedSeq(i)
              val minFound = set.until(v).nonEmpty

              (if (minFound) res + 1 else res, set += v)
          }
          ._1
      }
    }
  }

}

object Main extends App {
  val t = readInt()
  for (i <- 0 to t-1) {
      var i = readInt() - 2
      val a = readLine().split(" ").map(_.toInt)
      var rs = 0
      var temp = a(i+1)
      while(i>=0){
          if(a(i) > temp)
            rs += 1
          else
            temp = a(i)
          i-=1
      }
      println(rs)
  }
}

object Main extends App {
  val t = readInt()
  for (i <- 0 to t-1) {
      val n = readInt()
      val a = readLine().split(" ").map(_.toInt)
      var rs = 0
      var temp = a(0)
      for(i <- 1 to n-1) {
          if(a(i) > temp) rs += 1
          temp = a(i)
      }
      println(rs)
  }
}


The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map. The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least k lakes.

In the first line print the minimum number of cells which should be transformed from water to land.  In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them.  It is guaranteed that the answer exists on the given data.

NoteIn the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(' ').map(_.toInt)
  val map = in.take(n).map(_.toCharArray.map(_.toString)).toArray
  var lakes = List.empty[(Int, String)]
  var bays = Set.empty[String]
  var id = 0

  def process(i: Int, j: Int, color: String): Int = {
    if (i == -1 || j == -1 || i == n || j == m) {
      bays += color
      0
    }
    else if (map(i)(j) == ".") {
      map(i)(j) = color
      process(i - 1, j, color) +
      process(i + 1, j, color) +
      process(i, j - 1, color) +
      process(i, j + 1, color) + 1
    } else 0
  }

  (0 until n).foreach { i =>
    (0 until m).foreach { j =>
      if (map(i)(j) == ".") {
        val size = process(i, j, id.toString)
        if (!bays.contains(id.toString))
          lakes ::= (size, id.toString)
        id += 1
      }
    }
  }

  val dropLakes = lakes.sorted.reverse.drop(k)
  val count = dropLakes.map(_._1).sum
  val dropLakesId = dropLakes.map(_._2).toSet

  (0 until n).foreach { i =>
    (0 until m).foreach { j =>
      if (map(i)(j) != "*") {
        if (dropLakesId.contains(map(i)(j)))
          map(i)(j) = "*"
        else
          map(i)(j) = "."
      }
    }
  }
  println(count)
  println(map.map(_.mkString).mkString("\n"))

}


The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

NoteIn the first sample the best strategy is to delete the second digit. That results in number 112 = 310.In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.

import java.util.StringTokenizer

object _258A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next
  val pos = s.indexWhere(ch => ch == '0')
  if (pos != -1) println(s.take(pos) + s.drop(pos + 1))
  else println(s.drop(1))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val nStr = str.replaceFirst("0", "")
  if (str.length == nStr.length)
    println(str.tail)
  else
    println(nStr)
}

object Main {

  def main(args: Array[String]): Unit = {

    def fixNumber(n: String): String = {
      val index = n.indexOf("0")
      if (index >= 0)
        n.substring(0, index) + n.substring(index+1)
      else
        n.substring(1)
    }

    print(fixNumber(readLine))
  }

}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A258 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val a = sc.next()

    if (a.indexOf("1") != -1) {
      val startWith1 = a.substring(a.indexOf("1"))

      if (startWith1.indexOf("0") != -1) {
        val pre = startWith1.substring(0, startWith1.indexOf("0"))
        val post = startWith1.substring(startWith1.indexOf("0") + 1)
        println(pre + post)
      } else {
        println(startWith1.substring(1))
      }
    } else {
      println(a.substring(1))
    }
  }
}

import scala.util.control.Breaks._
import scala.util.control.Breaks

//Julian_Miranda

object LittleElephantAndBits {
  def main(args: Array[String]): Unit = {
    var a = readLine
    var pos = -1

    val loop = new Breaks
    loop.breakable {
      for (i <- 0 to a.length() - 1) {
        breakable {
          if (a.charAt(i) == '0') {
            pos = i
            loop.break
          }
        }
      }
    }

    if (pos == -1) {
      for (i <- 1 to a.length()) {
        if (i < a.length()) {
          print(a.charAt(i))
        }
      }
    } else {
      for (i <- 0 to a.length() - 1) {
        breakable {
          if (i == pos) break;
          else {
            print(a.charAt(i))
          }
        }
      }
    }
    println()
  }
}

object Contest extends App {
  val s = readLine()
  val p = s.indexOf('0')
  val ans = if (p == -1) s.substring(1) else s.substring(0, p) + s.substring(p+1)
  println(ans)
}

import scala.util.control.Breaks._

//Julian_Miranda

object LittleElephantAndBits {
  def main(args: Array[String]): Unit = {
    var a = readLine
    var pos = -1

    for (i <- 0 to a.length()-1) {
      breakable {
        if (a.charAt(i) == '0') {
          pos = i
          break;
        }
      }
    }

    if (pos == -1) {
      for (i <- 1 to a.length()) {
        if(i < a.length()){
          print(a.charAt(i))
        }
      }
    } else {
      for (i <- 0 to a.length()-1) {
        breakable {
          if (i == pos)break;
          else{
            print(a.charAt(i))
          }
        }
      }
    }
    println()
  }
}


A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example:   If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};  If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};  If x = 5 and the crossword is 11111, then its encoding is an array {5};  If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!

The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 109) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 10000) — the encoding.

Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.

import scala.io.StdIn._

object Codeforces extends App {
  val Array(n, x) = readLine split ' ' map(_.toLong)
  val a = readLine split ' ' map(_.toLong)
  if (x == (a sum) + (n - 1))
    println("YES")
  else
    println("NO")
}


Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.The teacher gave Andrew an array of n numbers a1, ..., an. After that he asked Andrew for each k from 1 to n - 1 to build a k-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.Andrew looked up on the Wikipedia that a k-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to n, then the children of element v are elements with indices k(v - 1) + 2, ..., kv + 1 (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any k-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote p(v) as the number of the parent of the element with the number v. Let's say that for a non-root element v the property of the heap is violated if av < ap(v).Help Andrew cope with the task!

The first line contains a single integer n (2 ≤ n ≤ 2·105). The second line contains n space-separated integers a1, ..., an ( - 109 ≤ ai ≤ 109).

in a single line print n - 1 integers, separate the consecutive numbers with a single space — the number of elements for which the property of the k-ary heap is violated, for k = 1, 2, ..., n - 1.

NotePictures with the heaps for the first sample are given below; elements for which the property of the heap is violated are marked with red.     In the second sample all elements are equal, so the property holds for all pairs.

import java.util.StringTokenizer

import scala.io.Source

object F extends App {
  object In {
    private val lines = Source.stdin.getLines()
    private var tokenizer: StringTokenizer = new StringTokenizer(lines.next())

    def next(): String = {
      if (tokenizer.hasMoreTokens) {
        tokenizer.nextToken()
      } else {
        tokenizer = new StringTokenizer(lines.next())
        next()
      }
    }

    def nextInt() = next().toInt
    def nextDouble() = next().toDouble
  }

  val emptyIntArray = Array.empty[Int]

  class MinTree(d0: Array[Int]) {
    val offset = 1 << (32 - Integer.numberOfLeadingZeros(d0.length))
    val data = Array.fill(2 * offset)(emptyIntArray)
    for (i <- 0 until d0.length) {
      data(i + offset) = Array.ofDim[Int](1)
      data(i + offset)(0) = d0(i)
    }
    for (i <- offset - 1 to 1 by -1) {
      data(i) = merge(data(2 * i), data(2 * i + 1))
    }

    def merge(a: Array[Int], b: Array[Int]): Array[Int] = {
      val rv = Array.ofDim[Int](a.length + b.length)
      var ai, bi, ci = 0
      while (ai < a.length && bi < b.length) {
        if (a(ai) < b(bi)) {
          rv(ci) = a(ai)
          ai += 1
        } else {
          rv(ci) = b(bi)
          bi += 1
        }
        ci += 1
      }
      while (ai < a.length) {
        rv(ci) = a(ai)
        ci += 1
        ai += 1
      }
      while (bi < b.length) {
        rv(ci) = b(bi)
        ci += 1
        bi += 1
      }
      rv
    }

    def countLess(a: Array[Int], v: Int): Int = {
      if (a.length == 0 || a(0) >= v) {
        0
      } else if (a(a.length - 1) < v) {
        a.length
      } else {
        def bs(l: Int, r: Int): Int = {
          if (r - l == 1) r else {
            val m = (l + r) >>> 1
            if (a(m) < v) {
              bs(m, r)
            } else {
              bs(l, m)
            }
          }
        }
        bs(0, a.length)
      }
    }

    def count(l: Int, r: Int, v: Int): Int = {
      var ll = l + offset
      var rr = r + offset
      var rv = 0
      while (ll <= rr) {
        if ((ll & 1) == 1) {
          rv += countLess(data(ll), v)
        }
        if ((rr & 1) == 0) {
          rv += countLess(data(rr), v)
        }
        ll = (ll + 1) >>> 1
        rr = (rr - 1) >>> 1
      }
      rv
    }
  }

  val n = In.nextInt()
  val d = Array.fill(n)(In.nextInt())

  val t = new MinTree(d)
  for (k <- 1 until n) {
    var count = 0
    var i = 0
    while (k * i + 1 < n) {
      count += t.count(k * i + 1, math.min(n - 1, k * (i + 1)), d(i))
      i += 1
    }
    print(count + " ")
  }
  println()
}

object F 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 as = readInts(n)

  val deltas = Array.fill(n){ 0 }

  for (i <- 1 until n) {
    var k = 1
    while (k < n) {
      val parent = (i - 1) / k
      val nextK = if (parent == 0) n else (i - 1) / parent + 1
      if (as(i) < as(parent)) {
        deltas(k) += 1
        if (nextK < n) deltas(nextK) -= 1
      }
      k = nextK
    }
  }

  val res = deltas.scan(0){ _ + _ }.drop(2)

  println(res.mkString(" "))
}

object F 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 as = readInts(n)

  val deltas = Array.fill(n){ 0 }

  for (i <- 1 until n) {
    var k = 1
    var violating = false
    val a = as(i)
    while (k < n) {
      val parent = (i - 1) / k
      if (a < as(parent)) {
        if (!violating) {
          deltas(k) += 1
          violating = true
        }
      } else {
        if (violating) {
          deltas(k) -= 1
          violating = false
        }
      }
      k = if (parent == 0) n else (i - 1) / parent + 1
    }
  }

  val res = deltas.scan(0){ _ + _ }.drop(2)

  println(res.mkString(" "))
}

object F extends App {

  object BIT {

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

    def rangeQuery(t: Array[Int], l: Int, r: Int) = query(t, r) - query(t, l - 1)

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

    def apply(n: Int): Array[Int] = {
      Array.fill(n) { 0 }
    }

  }

  @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 as = readInts(n)

  val bit = BIT(n)

  for (i <- 1 until n) {
    var nextK = 1
    var violating = false
    while (nextK < n) {
      val k = nextK
      val parent = (i - 1) / k
      if (as(i) < as(parent)) {
        if (!violating) {
          BIT.update(bit, k, 1)
          violating = true
        }
      } else {
        if (violating) {
          BIT.update(bit, k, -1)
          violating = false
        }
      }
      nextK = if (parent == 0) n else (i - 1) / parent + 1
          println(i, k, nextK)
    }
  }

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

  val res = Array.tabulate(n - 1){ i => BIT.query(bit, i + 1) }

  println(res.mkString(" "))

  Console.flush
}

import scala.collection._

object F extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val tMin = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    val tMax = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) tMin(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        tMin(v) = Math.min(tMin(v2), tMin(v2 + 1))
        tMax(v) = Math.max(tMax(v2), tMax(v2 + 1))
      }
    }

    def query(l: Int, r: Int, p: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Int = {
      val res = if (l > r) 0
      else if (l == tl && r == tr) {
        if (tMin(v) >= p) 0
        else if (tMax(v) < p) r - l + 1
        else -1
      } else -1

      if (res >= 0) res
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        query(l, Math.min(r, tm), p, v2, tl, tm) +
          query(Math.max(l, tm + 1), r, p, v2 + 1, tm + 1, tr)
      }
    }

  }
  val Array(n) = readInts(1)
  val as = readInts(n)

  val segTree = SegTree(as)

  val res = Array.ofDim[Int](n - 1)

  for (k <- 0 until n - 1) {
    var cnt = 0
    var v = 0
    var r = 0
    while (r <= n && v < n) {
      val l = r + 1 // k * v + 1
      r = (l + k) min (n - 1)
      //println(l, r)
      cnt += segTree.query(l, r, as(v))
      v += 1
    }
    res(k) = cnt
  }

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

  println(res.mkString(" "))

  Console.flush
}

import scala.collection._

object F extends App {

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

  case class SegTree(as: Array[Int]) {

    val n = as.length
    val tMin = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    val tMax = Array.ofDim[Int](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) tMin(v) = as(tl)
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        build(v2, tl, tm)
        build(v2 + 1, tm + 1, tr)
        tMin(v) = Math.min(tMin(v2), tMin(v2 + 1))
        tMax(v) = Math.max(tMax(v2), tMax(v2 + 1))
      }
    }

    def query(l: Int, r: Int, p: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Long = {
      val res = if (l > r) 0
      else if (l == tl && r == tr) {
        if (tMin(v) >= p) 0
        else if (tMax(v) < p) r - l + 1
        else -1
      } else -1

      if (res >= 0) res
      else {
        val tm = (tl + tr) >> 1
        val v2 = v << 1
        query(l, Math.min(r, tm), p, v2, tl, tm) +
          query(Math.max(l, tm + 1), r, p, v2 + 1, tm + 1, tr)
      }
    }

  }
  val Array(n) = readInts(1)
  val as = readInts(n)

  val segTree = SegTree(as)

  val res = Array.ofDim[Long](n - 1)

  for (k <- 0 until n - 1) {
    var cnt = 0L
    var v = 0
    var r = 0
    while (r < n - 1) {
      val l = r + 1 // k * v + 1
      r = (l + k) min (n - 1)
      //println(l, r)
      cnt += segTree.query(l, r, as(v))
      v += 1
    }
    res(k) = cnt
  }

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

  println(res.mkString(" "))

  Console.flush
}


There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.

The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·105) — the initial number of cities in Westeros and the number of cities at which the game ends.  The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 106), which represent the population of each city in Westeros.

Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.

NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.

import scala.collection._

object C extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n)

  val moves = n - k
  val bMoves = (n - k) / 2
  val aMoves = n - k - bMoves

  val odd = as.count(_ % 2 == 1)
  val even = n - odd

  val winner = if (odd <= bMoves) 0
  else if (even <= bMoves) k % 2
  else if (n == k) odd % 2
  else moves % 2

  println(if (winner == 0) "Daenerys" else "Stannis")
}

import scala.collection._

object C extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n)

  val moves = n - k
  val bMoves = (n - k) / 2
  val aMoves = n - k - bMoves

  val odd = as.count(_ % 2 == 1)
  val even = n - odd

  val winner = if (odd <= bMoves) 0
  else if (even <= aMoves && k % 2 == 1) 1
  else if (n == k) odd % 2
  else moves % 2

  println(if (winner == 0) "Daenerys" else "Stannis")
}

import scala.collection._

object C extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n)

  val moves = n - k
  val bMoves = (n - k) / 2
  val aMoves = n - k - bMoves

  val odd = as.count(_ % 2 == 1)
  val even = n - odd

  val winner = if (odd <= bMoves) 0
  else if (even <= aMoves) k % 2
  else if (n == k) odd % 2
  else moves % 2

  println(if (winner == 0) "Daenerys" else "Stannis")
}

import scala.collection._

object C extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n)

  val bMoves = (n - k) / 2
  val aMoves = n - k - bMoves

  val odd = as.count(_ % 2 == 1)
  val even = n - odd

  val winner = if (odd <= bMoves) 0
  else if (even <= aMoves && k % 2 == 1) 1
  else if (n == k) odd % 2
  else 1

  println(if (winner == 0) "Daenerys" else "Stannis")
}

import scala.collection._

object C extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n)

  val bMoves = (n - k) / 2
  val aMoves = n - k - bMoves

  val odd = as.count(_ % 2 == 1)
  val even = n - odd

  val winner = if (odd <= bMoves) 0
  else if (even <= aMoves && k % 2 == 1) 1
  else 1

  println(if (winner == 0) "Daenerys" else "Stannis")
}


This is an interactive problem.Bob lives in a square grid of size $$$n \times n$$$, with rows numbered $$$1$$$ through $$$n$$$ from top to bottom, and columns numbered $$$1$$$ through $$$n$$$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $$$n$$$.Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed.You can ask at most $$$4 \cdot n$$$ queries of form "? $$$r_1$$$ $$$c_1$$$ $$$r_2$$$ $$$c_2$$$" ($$$1 \le r_1 \le r_2 \le n$$$, $$$1 \le c_1 \le c_2 \le n$$$). The answer will be "YES" if Bob can get from a cell $$$(r_1, c_1)$$$ to a cell $$$(r_2, c_2)$$$, and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $$$n - 1$$$, i.e. the following condition must be satisfied: $$$(r_2 - r_1) + (c_2 - c_1) \ge n - 1$$$.It's guaranteed that Bob can get from the top-left corner $$$(1, 1)$$$ to the bottom-right corner $$$(n, n)$$$ and your task is to find a way to do it. You should print the answer in form "! S" where $$$S$$$ is a string of length $$$2 \cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $$$1$$$, the right move increases the second coordinate by $$$1$$$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.

The only line of the input contains an integer $$$n$$$ ($$$2 \le n \le 500$$$) — the size of the grid.

When you are ready to print the answer, print a single line containing "! S" where where $$$S$$$ is a string of length $$$2 \cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell $$$(1, 1)$$$ to the cell $$$(n, n)$$$ passing only through allowed cells.

NoteThe first example is shown on the picture below.  To hack, use the following input format:The first line should contain a single integer $$$n$$$ ($$$2 \le n \le 500$$$) — the size of the grid.Each of the next $$$n$$$ lines should contain a string of $$$n$$$ characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell.For example, the following text encodes the example shown above:4..#.#...###.....

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

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

  def solve(): Unit = {
    val N = ni()

    def step(from: Int): String = {
      var i, j = from
      val trace = ArrayBuffer[Char]()

      def query(query: String): Boolean = {
        println(query)
        ns() match {
          case "BAD" =>
            System.exit(0)
            false

          case "YES" => true
          case "NO" => false
        }
      }
      def queryToN(): Boolean = {
        query(s"? $i ${j+1} $N $N") // 右優先
      }
      def queryTo1(): Boolean = {
        query(s"? 1 1 ${i-1} $j") // 上優先
      }

      while (trace.length < N - 1) {
        if (from == 1) {
          if (queryToN()) { // 右
            j += 1
            trace += 'R'
          } else {
            i += 1
            trace += 'D'
          }
        } else {
          if (queryTo1()) { // 上
            i -= 1
            trace += 'D'
          } else {
            j -= 1
            trace += 'R'
          }
        }
      }

      trace.mkString
    }

    val ans = step(1) + step(N).reverse
    println(s"! $ans")
  }

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

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

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

  def solve(): Unit = {
    val N = ni()
    var i, j = 1
    val trace = ArrayBuffer[Char]()

    def mkQuery(r: Int, c: Int) = {
      if (r - 1 + c - 1 >= N - 1) s"? 1 1 $r $c"
      else s"? $r $c $N $N"
    }

    def queryRight(): Boolean = {
      println(mkQuery(i, j + 1))
      ns() match {
        case "BAD" =>
          System.exit(0)
          false

        case "YES" => true
        case "NO" => false
      }
    }

    while (i < N && j < N) {
      if (queryRight()) {
        trace += 'R'
        j += 1
      } else {
        trace += 'D'
        i += 1
      }
    }

    val (lastD, lastCnt) = if (i == N) ('R', N - j) else ('D', N - i)
    rep(lastCnt)(_ => trace += lastD)

    println(s"! ${trace.mkString}")
  }

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

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()
    var i, j = 1
    val trace = ArrayBuffer[Char]()

    def mkQuery(r: Int, c: Int) = {
      if (r - 1 + c - 1 >= N - 1) s"? 1 1 $r $c"
      else s"? $r $c $N $N"
    }

    def queryRight(): Boolean = {
      println(mkQuery(i, j + 1))
      ns() match {
        case "BAD" =>
          System.exit(0)
          false

        case "YES" => true
        case "NO" => false
      }
    }

    while (i < N && j < N) {
      if (queryRight()) {
        trace += 'R'
        j += 1
      } else {
        trace += 'D'
        i += 1
      }
    }

    var lastD = if (i == N) 'R' else 'D'
    rep(N - j)(_ => trace += lastD)

    out.println(s"! ${trace.mkString}")
  }

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


In this problem you will have to help Berland army with organizing their command delivery system.There are $$$n$$$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $$$a$$$ is the direct superior of officer $$$b$$$, then we also can say that officer $$$b$$$ is a direct subordinate of officer $$$a$$$.Officer $$$x$$$ is considered to be a subordinate (direct or indirect) of officer $$$y$$$ if one of the following conditions holds:  officer $$$y$$$ is the direct superior of officer $$$x$$$;  the direct superior of officer $$$x$$$ is a subordinate of officer $$$y$$$. For example, on the picture below the subordinates of the officer $$$3$$$ are: $$$5, 6, 7, 8, 9$$$.The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.Formally, let's represent Berland army as a tree consisting of $$$n$$$ vertices, in which vertex $$$u$$$ corresponds to officer $$$u$$$. The parent of vertex $$$u$$$ corresponds to the direct superior of officer $$$u$$$. The root (which has index $$$1$$$) corresponds to the commander of the army.Berland War Ministry has ordered you to give answers on $$$q$$$ queries, the $$$i$$$-th query is given as $$$(u_i, k_i)$$$, where $$$u_i$$$ is some officer, and $$$k_i$$$ is a positive integer.To process the $$$i$$$-th query imagine how a command from $$$u_i$$$ spreads to the subordinates of $$$u_i$$$. Typical DFS (depth first search) algorithm is used here.Suppose the current officer is $$$a$$$ and he spreads a command. Officer $$$a$$$ chooses $$$b$$$ — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then $$$a$$$ chooses the one having minimal index. Officer $$$a$$$ gives a command to officer $$$b$$$. Afterwards, $$$b$$$ uses exactly the same algorithm to spread the command to its subtree. After $$$b$$$ finishes spreading the command, officer $$$a$$$ chooses the next direct subordinate again (using the same strategy). When officer $$$a$$$ cannot choose any direct subordinate who still hasn't received this command, officer $$$a$$$ finishes spreading the command.Let's look at the following example:  If officer $$$1$$$ spreads a command, officers receive it in the following order: $$$[1, 2, 3, 5 ,6, 8, 7, 9, 4]$$$.If officer $$$3$$$ spreads a command, officers receive it in the following order: $$$[3, 5, 6, 8, 7, 9]$$$.If officer $$$7$$$ spreads a command, officers receive it in the following order: $$$[7, 9]$$$.If officer $$$9$$$ spreads a command, officers receive it in the following order: $$$[9]$$$.To answer the $$$i$$$-th query $$$(u_i, k_i)$$$, construct a sequence which describes the order in which officers will receive the command if the $$$u_i$$$-th officer spreads it. Return the $$$k_i$$$-th element of the constructed list or -1 if there are fewer than $$$k_i$$$ elements in it.You should process queries independently. A query doesn't affect the following queries.

The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le q \le 2 \cdot 10^5$$$) — the number of officers in Berland army and the number of queries. The second line of the input contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ is the index of the direct superior of the officer having the index $$$i$$$. The commander has index $$$1$$$ and doesn't have any superiors. The next $$$q$$$ lines describe the queries. The $$$i$$$-th query is given as a pair ($$$u_i, k_i$$$) ($$$1 \le u_i, k_i \le n$$$), where $$$u_i$$$ is the index of the officer which starts spreading a command, and $$$k_i$$$ is the index of the required officer in the command spreading sequence.

Print $$$q$$$ numbers, where the $$$i$$$-th number is the officer at the position $$$k_i$$$ in the list which describes the order in which officers will receive the command if it starts spreading from officer $$$u_i$$$. Print "-1" if the number of officers which receive the command is less than $$$k_i$$$. You should process queries independently. They do not affect each other.

import scala.collection.mutable
//package codeforces

object MilitaryProblem {

  //  private def computeSizes(n: Int, childrenMap: Map[Int, Array[Int]], parentArray: Array[Int]): Array[Int] = {
  //    val result = Array.fill(n + 1)(1)
  //
  //    def compute(set: Set[Int]): Unit = {
  //      set.foreach(node => result(parentArray(node)) += result(node))
  //      if (!(set.size == 1 && set.contains(0))) compute(set map parentArray)
  //    }
  //
  //    compute((1 to n).filter(node => !childrenMap.contains(node)).toSet) // starting with the leaves
  //    result
  //  }

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

    //    val parentArray: Array[Int] = Array(0, 0) ++ io.StdIn.readLine.split(" ").map(_.toInt)
    //    var childrenMap: Map[Int, Array[Int]] = parentArray.zipWithIndex.groupBy(_._1).map { case (p, elems) => (p, elems.unzip._2) }

    val parentArray: Array[Int] = io.StdIn.readLine.split(" ").map(_.toInt)
    val children: Array[mutable.Queue[Int]] = Array.fill(n + 1)(mutable.Queue[Int]())

    var i: Int = 0
    while (i < parentArray.length) {
      children(parentArray(i)).enqueue(i + 2)
      i += 1
    }

    //val subtreeCount: Array[Int] = computeSizes(n, childrenMap, parentArray)

    //val childrenMapWithPrefixSum = childrenMap.map { case (node, children) => (node, children.scanLeft(1) { case (res, elem) => res + subtreeCount(elem) }) }

    val sortedSeq, startingPositionInSortedSeq, endingPositionInSortedSeq = new Array[Int](n + 1)
    i = 0
    dfs(1)

    def dfs(node: Int): Unit = {
      sortedSeq(i) = node
      startingPositionInSortedSeq(node) = i
      i += 1
      children(node).foreach(dfs)
      endingPositionInSortedSeq(node) = i - 1
    }

    i = 0
    while (i < q) {
      val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)

      val startingPos = startingPositionInSortedSeq(u)
      val endingPos = endingPositionInSortedSeq(u)

      if (endingPos - startingPos + 1 < k) println(-1)
      else println(sortedSeq(startingPos + k - 1))

      i += 1
      //println(computeQueryResult(u, k))
    }

    //    def computeQueryResult(u: Int, k: Int): Int = {
    //      if (k > subtreeCount(u)) -1
    //      else if (k == 1) u
    //      else {
    //        val childPrefixSum: Array[Int] = childrenMapWithPrefixSum(u)
    //        val i = childPrefixSum.search(k).insertionPoint // optimized  binary search
    //
    //        val newU = childrenMap(u)(i - 1)
    //        val newK = k - childPrefixSum(i - 1)
    //        computeQueryResult(newU, newK)
    //      }
    //    }
  }
}

//package codeforces

import scala.collection.Searching._
import scala.collection.mutable

/*

link- http://codeforces.com/contest/1006/problem/E

Pre-order traversal sequence, find the kth element starting from node u

 */
object MilitaryProblem {

  def main(args: Array[String]): Unit = {
    val Array(n, q) = io.StdIn.readLine.split(" ").map(_.toInt)
    val parentArray: Array[Int] = io.StdIn.readLine.split(" ").map(_.toInt)

    val children: Array[mutable.Queue[Int]] = Array.fill(n + 1)(mutable.Queue[Int]())

    //    var i: Int = 0
    //    while (i < parentArray.length) {
    //      children(parentArray(i)).enqueue(i + 2)
    //      i += 1
    //    }

    computeChildrenMapping(0)

    def computeChildrenMapping(idx: Int): Unit = {
      if (idx < parentArray.length) {
        children(parentArray(idx)).enqueue(idx + 2)
        computeChildrenMapping(idx + 1)
      }
    }

    val sortedSeq, startingPositionInSortedSeq, endingPositionInSortedSeq = new Array[Int](n + 1)
    var i = 0
    dfs(1)

    def dfs(node: Int): Unit = {
      sortedSeq(i) = node
      startingPositionInSortedSeq(node) = i
      i += 1
      children(node).foreach(dfs)
      endingPositionInSortedSeq(node) = i - 1
    }

    //    i = 0
    //    while (i < q) {
    //      val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)
    //
    //      val startingPos = startingPositionInSortedSeq(u)
    //      val endingPos = endingPositionInSortedSeq(u)
    //
    //      if (endingPos - startingPos + 1 < k) println(-1)
    //      else println(sortedSeq(startingPos + k - 1))
    //
    //      i += 1
    //    }

    solveQueries(0)

    def solveQueries(idx: Int): Unit = {
      if (idx < q) {
        val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)

        val startingPos = startingPositionInSortedSeq(u)
        val endingPos = endingPositionInSortedSeq(u)

        if (endingPos - startingPos + 1 < k) println(-1)
        else println(sortedSeq(startingPos + k - 1))

        solveQueries(idx + 1)
      }
    }

  }

  // Another Solution although inefficient

  def usingReverseLevelOrderTraversal(args: Array[String]): Unit = {
    val Array(n, q) = io.StdIn.readLine.split(" ").map(_.toInt)

    val parentArray: Array[Int] = Array(0, 0) ++ io.StdIn.readLine.split(" ").map(_.toInt)
    var childrenMap: Map[Int, Array[Int]] = parentArray.zipWithIndex.groupBy(_._1).map { case (p, elems) => (p, elems.unzip._2) }

    val subtreeSizeCount: Array[Int] = { // reverse level order traversal to compute sizes of each subtree
      val result = Array.fill(n + 1)(1)

      def compute(set: Set[Int]): Unit = {
        set.foreach(node => result(parentArray(node)) += result(node))
        if (!(set.size == 1 && set.contains(0))) compute(set map parentArray)
      }

      compute((1 to n).filter(node => !childrenMap.contains(node)).toSet) // starting with the leaves
      result
    }

    val childrenMapWithPrefixSum = childrenMap.map { case (node, children) => (node, children.scanLeft(1) { case (res, elem) => res + subtreeSizeCount(elem) }) }

    var i = 0
    while (i < q) {
      val Array(u, k) = io.StdIn.readLine.split(" ").map(_.toInt)
      println(computeQueryResult(u, k))
      i += 1
    }

    def computeQueryResult(u: Int, k: Int): Int = {
      if (k > subtreeSizeCount(u)) -1
      else if (k == 1) u
      else {
        val childPrefixSum: Array[Int] = childrenMapWithPrefixSum(u)
        val i = childPrefixSum.search(k).insertionPoint // optimized with binary search

        val newU = childrenMap(u)(i - 1)
        val newK = k - childPrefixSum(i - 1)
        computeQueryResult(newU, newK)
      }
    }
  }
}

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, Q = ni()
    val from, to = Array.ofDim[Int](N - 1)
    REP(N -1) { i =>
      from(i) = ni() - 1
      to(i) = i + 1
    }

    val g = packDGraph(N, from, to)
    val (tour, _) = traceDfs(g)
    val pos = Array.ofDim[Int](N)
    REP(N) { i =>
      pos(tour(i)) = i
    }
    val childCnt = Array.ofDim[Int](N)
    REP_r(N) { v =>
      REP(g(v).length) { j =>
        val u = g(v)(j)
        childCnt(v) += childCnt(u) + 1
      }
    }

    REP(Q) { _ =>
      val u, k = ni() - 1
      if (k > childCnt(u)) out.println(-1)
      else {
        out.println(tour(pos(u) + k) + 1)
      }
    }
  }

  def traceDfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int]) = {
    val n = g.length
    val stack = mutable.Stack[Int]()
    val ix = Array.ofDim[Int](n)
    val tour = Array.ofDim[Int](n)
    val parent = Array.ofDim[Int](n)
    parent(rt) = -1
    var p = 0

    tour(p) = rt
    p += 1
    stack.push(rt)

    while(stack.nonEmpty) {
      val v = stack.top
      val es = g(v)
      if (ix(v) == es.length) stack.pop()
      else {
        val u = es(ix(v))
        if (u != parent(v)) {
          parent(u) = v
          stack.push(u)
          tour(p) = u
          p += 1
        }
        ix(v) += 1
      }
    }

    (tour, parent)
  }

  def packDGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP_r(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
    }
    t
  }

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

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

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

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

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

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


Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.

The first line of the input contains two integers n and m () — the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.

If Vladislav has made a mistake and such graph doesn't exist, print  - 1. Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.

import java.io._
import java.util._
import scala.collection.JavaConversions._

/**
 * Created by antonkov on 9/17/15.
 */
object B {
  class Edge(val w: Int, val inMst: Boolean, val num: Int) {
    override def toString = s"Edge($w, $inMst, $num)"
  }

  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n, m = in.nextInt()
    var edges = new Array[Edge](m)
    for (i <- 0 until m) {
      edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)
    }
    edges = edges.sortWith((e1, e2) => if (e1.w != e2.w) e1.w < e2.w else e2.inMst < e1.inMst )
    val q = new ArrayDeque[(Int, Int)]()
    var v = 1
    val res = new Array[(Int, Int)](m)
    for (e <- edges) {
      if (e.inMst) {
        v += 1
        def addEdges {
          for (u <- 1 until v) {
            if (q.size() >= m)
              return
            q.add((u, v))
          }
        }
        addEdges
        res(e.num) = q.pollLast()
      } else {
        if (q.isEmpty) {
          out.println(-1)
          return
        }
        res(e.num) = q.pollFirst()
      }
    }
    for ((u, v) <- res) {
      out.println(u + " " + v)
    }
  }

  def main (args: Array[String]): Unit = {
    val in = new Scanner()
    val out = new PrintWriter(System.out)

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

object D{
  //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,m)=(nextInt,nextInt)
    val edges=for(i<-0 until m) yield(i,nextInt,nextInt)
    val edgesSorted=scala.util.Sorting.stableSort(edges, (e1: Tuple3[Int, Int,Int], e2: Tuple3[Int, Int,Int]) => if(e1._2 < e2._2){
                                                    true
                                                  }
                                                  else if(e1._2>e2._2){
                                                    false
                                                  }else{
                                                    e1._3 > e2._3
                                                  })

    val nextNode=Array.ofDim[Int](n)
    var lastNode=0
    val ans=Array.ofDim[(Int,Int)](m)
    nextNode(0)=2
    for(i<-0 until m){
      val (idx,_,isTree)=edgesSorted(i)
      if(isTree==1){
        ans(idx)=(lastNode+1,lastNode+2)
        nextNode(lastNode)=lastNode+2
        lastNode+=1
      }else{
        var has=false
        breakable{
          for(j<-0 until lastNode){
            if(nextNode(j)<=lastNode){
              ans(idx)=(j+1,nextNode(j)+1)
              nextNode(j)+=1
              has=true
              break
            }
          }
        }
        if(has==false){
          out.println(-1)
          out.flush()
          out.close()
          return
        }
      }
    }
    ans.foreach(a=>println(a._1+" "+a._2))
    //code ends here
    out.flush
    out.close
  }
}

import java.io._
import java.util._
import scala.collection.JavaConversions._

/**
 * Created by antonkov on 9/17/15.
 */
object B {
  class Edge(val w: Int, val inMst: Boolean, val num: Int)

  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n, m = in.nextInt()
    val edges = new Array[Edge](m)
    for (i <- 0 until m) {
      edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)
    }
    edges.sortWith((e1, e2) => e1.w < e2.w)
    val q = new ArrayDeque[(Int, Int)]()
    var v = 1
    val res = new Array[(Int, Int)](m)
    for (e <- edges) {
      if (e.inMst) {
        v += 1
        for (u <- 1 until v) {
          q.add((u, v))
        }
        res(e.num) = q.pollLast()
      } else {
        if (q.isEmpty) {
          out.println(-1)
          return
        }
        res(e.num) = q.pollFirst()
      }
    }
    for ((u, v) <- res) {
      out.println(u + " " + v)
    }
  }

  def main (args: Array[String]): Unit = {
    val in = new Scanner()
    val out = new PrintWriter(System.out)

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

import java.io._
import java.util._
import scala.collection.JavaConversions._

/**
 * Created by antonkov on 9/17/15.
 */
object B {
  class Edge(val w: Int, val inMst: Boolean, val num: Int) {
    override def toString = s"Edge($w, $inMst, $num)"
  }

  def solve(in: Scanner, out: PrintWriter): Unit = {
    val n, m = in.nextInt()
    var edges = new Array[Edge](m)
    for (i <- 0 until m) {
      edges(i) = new Edge(in.nextInt(), in.nextInt() == 1, i)
    }
    edges = edges.sortWith((e1, e2) => if (e1.w != e2.w) e1.w < e2.w else e2.inMst < e1.inMst )
    val q = new ArrayDeque[(Int, Int)]()
    var v = 1
    val res = new Array[(Int, Int)](m)
    for (e <- edges) {
      if (e.inMst) {
        v += 1
        def addEdges {
          for (u <- 1 until v) {
            if (q.size() >= n)
              return
            q.add((u, v))
          }
        }
        addEdges
        res(e.num) = q.pollLast()
      } else {
        if (q.isEmpty) {
          out.println(-1)
          return
        }
        res(e.num) = q.pollFirst()
      }
    }
    for ((u, v) <- res) {
      out.println(u + " " + v)
    }
  }

  def main (args: Array[String]): Unit = {
    val in = new Scanner()
    val out = new PrintWriter(System.out)

    solve(in, out)

    out.close()
  }

  class Scanner {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer(br.readLine())

    def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    def nextInt() = next().toInt
    def nextLong() = next().toLong
    def nextDouble() = next().toDouble
  }
}

object D{
  //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,m)=(nextInt,nextInt)
    val edges=for(i<-0 until m) yield(i,nextInt,nextInt)
    val edgesSorted=scala.util.Sorting.stableSort(edges, (e1: Tuple3[Int, Int,Int], e2: Tuple3[Int, Int,Int]) => e1._2 < e2._2)

    val nextNode=Array.ofDim[Int](n)
    var lastNode=0
    val ans=Array.ofDim[(Int,Int)](m)
    nextNode(0)=2
    for(i<-0 until m){
      val (idx,_,isTree)=edgesSorted(i)
      if(isTree==1){
        ans(idx)=(lastNode+1,lastNode+2)
        nextNode(lastNode)=lastNode+2
        lastNode+=1
      }else{
        var has=false
        breakable{
          for(j<-0 until lastNode){
            if(nextNode(j)<=lastNode){
              ans(idx)=(j+1,nextNode(j)+1)
              nextNode(j)+=1
              has=true
              break
            }
          }
        }
        if(has==false){
          out.println(-1)
          out.flush()
          out.close()
          return
        }
      }
    }
    ans.foreach(a=>println(a._1+" "+a._2))
    //code ends here
    out.flush
    out.close
  }
}


You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$) — the length of the array. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case of input data, output "YES" (without quotes), if the array may be not sorted in non-decreasing order, output "NO" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).

NoteIn the first test case, it's possible to select $$$len = 1$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[2, 1, 2]$$$.In the second test case, it's possible to select $$$len = 3$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[1, 2, 3, 1]$$$.In the third test case, the array will be sorted in non-decreasing order for every possible $$$len$$$.

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val prefix = new MutableMultiSet[Int](List.empty)
    val suffix = new MutableMultiSet[Int](a.toList)
    var canWrongSort = false
    a.dropRight(1).foreach { v =>
      prefix.add(v)
      suffix.remove(v)
      if (prefix.max > suffix.min) canWrongSort = true
    }
    if (canWrongSort) println("YES") else println("NO")
  }

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

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

import scala.io.Source
import scala.util.control.Breaks

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Int]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toInt)
  }

  arrays.map(check).foreach(println)

  def check(arr: Array[Int]): String = {
    val n = arr.length
    val maxes = arr.scanLeft(0)(math.max)
    val mins = arr.scanRight(Int.MaxValue)(math.min)
    var res = "NO"
    Breaks.breakable {
      for (i <- 1 until n) {
        if (maxes(i) > mins(i)) {
          res = "YES"
          Breaks.break()
        }
      }
    }
    res
  }
}

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val prefix = new MutableMultiSet[Int](List.empty)
    val suffix = new MutableMultiSet[Int](a.toList)
    var canSort = false
    a.dropRight(1).foreach { v =>
      prefix.add(v)
      suffix.remove(v)
      if (prefix.max <= suffix.min) canSort = true
    }
    if (canSort || a.length == 1) println("NO") else println("YES")
  }

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val prefix = new MutableMultiSet[Int](List.empty)
    val suffix = new MutableMultiSet[Int](a.toList)
    var canSort = false
    a.dropRight(1).foreach { v =>
      prefix.add(v)
      suffix.remove(v)
      if (prefix.max <= suffix.min) canSort = true
    }
    if (canSort) println("NO") else println("YES")
  }

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val max = a.max
    if (max != a.last) println("YES") else println("NO")
  }

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

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

import scala.io.Source
import scala.util.control.Breaks

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Int]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toInt)
  }

  arrays.map(check).foreach(println)

  def check(arr: Array[Int]): String = {
    val n = arr.length
    val maxes = arr.scanLeft(0)(math.max)
    val mins = arr.scanRight(Int.MaxValue)(math.min)
    var res = "NO"
    Breaks.breakable {
      for (i <- 1 until n) {
        println(maxes(i), mins(i))
        if (maxes(i) > mins(i)) {
          res = "YES"
          Breaks.break()
        }
      }
    }
    res
  }
}

import scala.io.Source
import scala.util.control.Breaks

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Int]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toInt)
  }

  arrays.map(check).foreach(println)

  def check(arr: Array[Int]): String = {
    val n = arr.length
    val maxes = arr.scanLeft(0)(math.max)
    val mins = arr.scanRight(Int.MaxValue)(math.min)
    var res = "YES"
    Breaks.breakable {
      for (i <- 1 until n - 2) {
        if (maxes(i) <= mins(i + 1)) {
          res = "NO"
          Breaks.break()
        }
      }
    }
    res
  }
}


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

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

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

  def solve(): Int = {
    val N = sc.nextInt
    N - List.fill(N)(sc.nextInt).filter(x => 1 <= x && x <= N).distinct.size
  }

  out.println(solve)
  out.close
}

// codeforces 137B
object Perestanovki extends App {
  val n = Console.readLine toInt
  val al = Console readLine() split(" ") map (_.toInt)
  val agood = Array.fill(n)(0)

  for {
    i <- 0 until n
    if 1<= al(i) && al(i) <= n
  } agood(al(i) - 1) = 1
  val sm:Int = ((agood toList) sum)
  //println("sm = " + sm)
  //println("agood = " + (agood.toList.mkString(" ")))
  val s = (n-sm) toString;
  println(s)

}

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

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

  val n = readInt
  val a = readInts
  def ans = a.count(n<) + a.filter(n>=).groupBy(x => x).values.map(_.size - 1).sum

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

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(i => map(i) = map.getOrElse(i, 0) + 1)
    val count = (1 to n).foldLeft(0){ (a, i) => map.get(i) match {
      case Some(_) => a
      case None => a + 1
    }}
    println(count)
  }
}

object P137B extends App {
    readLine
    var n = readLine.split(" ").map(_.toInt).toList.sorted
    val d = n.distinct
    n = d ++ (n diff d)
    def s(a: Int, l: List[Int]):Int = l match{
      case (h::Nil) => a
      case (h::t) => if (h+1 == t.head) s(a, t) else s(a+1, h+1::t.slice(0,t.size-1))
    }
    println(if(n.head == 1) s(0,n) else s(1,1::n.slice(0,n.size-1)))
}

object P137B extends App {

    readLine
    var numbers = readLine.split(" ").map(_.toInt).toList.sorted
    numbers = numbers.distinct ++ (numbers diff numbers.distinct)

    def solve(acc: Int, list: List[Int]):Int = list match{
      case (h::Nil) => acc
      case (h::t) => if (h+1 == t.head) solve(acc,t) else solve(acc+1,h+1::t.slice(0,t.size-1))
    }

    println(if(numbers.head == 1) solve(0,numbers) else solve(1,1::numbers.slice(0,numbers.size-1)))

}

object P137B extends App {
    var n = readLine toInt
    var a = new Array[Int](5001)
    for(i <- readLine.split(" ")) a(i.toInt-1) = 1
    println(a.take(n).filter(_ < 1).size)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(n - in.next().split(' ').map(_.toInt).filter(_ <= n).distinct.length)
}

object P137B extends App {

    readLine
    var numbers = readLine.split(" ").map(_.toInt).toList.sorted
    numbers = numbers.distinct ++ (numbers diff numbers.distinct)

    def solve(acc: Int, list: List[Int]):Int = list match{
      case (h::Nil) => acc
      case (h::t) => if (h+1 == t.head) solve(acc,t) else solve(acc+1,h+1::t.slice(0,t.size-1))
    }

    println(solve(0,numbers))

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(n - in.next().split(' ').distinct.length)
}

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

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

  def solve(): Int = {
    val N = sc.nextInt
    N - List.fill(N)(sc.nextInt).distinct.size
  }

  out.println(solve)
  out.close
}


You are given two strings $$$s$$$ and $$$t$$$, each of length $$$n$$$ and consisting of lowercase Latin alphabets. You want to make $$$s$$$ equal to $$$t$$$. You can perform the following operation on $$$s$$$ any number of times to achieve it —   Choose any substring of $$$s$$$ and rotate it clockwise once, that is, if the selected substring is $$$s[l,l+1...r]$$$, then it becomes $$$s[r,l,l + 1 ... r - 1]$$$. All the remaining characters of $$$s$$$ stay in their position. For example, on rotating the substring $$$[2,4]$$$ , string "abcde" becomes "adbce". A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find the minimum number of operations required to convert $$$s$$$ to $$$t$$$, or determine that it's impossible.

The first line of the input contains a single integer $$$t$$$ $$$(1\leq t \leq 2000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\leq n \leq 2000)$$$ — the length of the strings.  The second and the third lines contain strings $$$s$$$ and $$$t$$$ respectively. The sum of $$$n$$$ over all the test cases does not exceed $$$2000$$$.

For each test case, output the minimum number of operations to convert $$$s$$$ to $$$t$$$. If it is not possible to convert $$$s$$$ to $$$t$$$, output $$$-1$$$ instead.

6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc

NoteFor the $$$1$$$-st test case, since $$$s$$$ and $$$t$$$ are equal, you don't need to apply any operation.For the $$$2$$$-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.For the $$$3$$$-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.For the $$$4$$$-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length $$$2$$$ beginning at the second character to convert it to cba.For the $$$5$$$-th test case, you only need to apply one operation on the entire string abab to convert it to baba.For the $$$6$$$-th test case, it is not possible to convert string $$$s$$$ to $$$t$$$.

//package codeforces.contests._1363

/*
https://codeforces.com/contest/1363/problem/F
 */
object RotatingSubstring {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val n = io.StdIn.readInt()
      val s, t = '0' + io.StdIn.readLine()

      val (freqS, freqT) = {
        val fS, fT = new Array[Int](26)
        (1 to n).foreach { k =>
          fS(s(k) - 'a') += 1
          fT(t(k) - 'a') += 1
        }
        (fS, fT)
      }

      val frequenciesMatch = (0 until 26).forall(i => freqS(i) == freqT(i))

      println {
        if (frequenciesMatch) {
          val dp = Array.ofDim[Int](n + 1, n + 1)
          val fS = freqS.clone()
          (1 to n).foreach { i =>
            val fT = freqT.clone()
            fS(s(i) - 'a') -= 1

            (1 to n).foreach { j =>
              fT(t(j) - 'a') -= 1

              dp(i)(j) = if (s(i) == t(j)) dp(i - 1)(j - 1) else {
                (dp(i - 1)(j) + 1) min {
                  val x = t(j) - 'a'
                  if (fS(x) > fT(x)) dp(i)(j - 1) else Int.MaxValue
                }
              }
            }
          }

          dp(n)(n)
        } else -1
      }
    }
  }
}


Sasha and Dima want to buy two $$$n$$$-tier cakes. Each cake should consist of $$$n$$$ different tiers: from the size of $$$1$$$ to the size of $$$n$$$. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are $$$2 \cdot n$$$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $$$i$$$-th house you can buy a tier of the size $$$a_i$$$ ($$$1 \le a_i \le n$$$).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $$$1$$$, then $$$2$$$, then $$$3$$$ and so on up to $$$n$$$.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $$$1$$$.

The first line of the input contains an integer number $$$n$$$ — the number of tiers in each cake ($$$1 \le n \le 10^5$$$). The second line contains $$$2 \cdot n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is equal to the size of the tier, which can be bought in the $$$i$$$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $$$1$$$ to $$$n$$$ occurs in $$$a$$$ exactly two times.

Print one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $$$n$$$ tiers in ascending order of their sizes.

NoteIn the first example, the possible optimal sequence of actions is:  Sasha buys a tier of size $$$1$$$ near the $$$1$$$-st house ($$$a_1=1$$$);  Dima goes to the house $$$2$$$;  Dima buys a tier of size $$$1$$$ near the $$$2$$$-nd house ($$$a_2=1$$$);  Sasha goes to the house $$$4$$$;  Sasha buys a tier of size $$$2$$$ near the $$$4$$$-th house ($$$a_4=2$$$);  Sasha goes to the house $$$5$$$;  Sasha buys a tier of size $$$3$$$ near the $$$5$$$-th house ($$$a_5=3$$$);  Dima goes to the house $$$3$$$;  Dima buys a tier of size $$$2$$$ near the $$$3$$$-rd house ($$$a_3=2$$$);  Dima goes to the house $$$6$$$;  Dima buys a tier of size $$$3$$$ near the $$$6$$$-th house ($$$a_6=3$$$). So, Sasha goes the distance $$$3+1=4$$$, and Dima goes the distance $$$1+1+3=5$$$. In total, they cover a distance of $$$4+5=9$$$. You can make sure that with any other sequence of actions they will walk no less distance.

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 A = na(2 * N, -1)

    // 貪欲に左右に分割するのが最適
    val fst, snd = Array.fill[Int](N)(-1)
    REP(2 * N) { i =>
      if (fst(A(i)) == -1) fst(A(i)) = i
      else snd(A(i)) = i
    }

    // 1-Nを順番に辿ったときの距離
    def dist(D: Array[Int]): Long = {
      var ans = 0L
      var pre = 0
      REP(N) { i =>
        val d = abs(D(i) - pre)
        ans += d
        pre = D(i)
      }
      ans
    }

    val ans = dist(fst) + dist(snd)
    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object Codeforces1130B {

  def getMinimumDistanceForTwoCakes(n: Int, a: Seq[Int]): Long = {
    val numberPositionMap = new mutable.HashMap[Int, (Long, Long)]()
    for (i <- a.indices) {
      if (numberPositionMap.contains(a(i)))
        numberPositionMap(a(i)) = (numberPositionMap(a(i))._1, i)
      else
        numberPositionMap(a(i)) = (i, -1)
    }

    val positionStart = numberPositionMap(1)
    var totalDistance = positionStart._1 + positionStart._2
    for (cursor <- 1 until n) {
      val positionFrom = numberPositionMap(cursor)
      val positionTo = numberPositionMap(cursor + 1)
      val distance1 = math.abs(positionFrom._1 - positionTo._1) + math.abs(positionFrom._2 - positionTo._2)
      val distance2 = math.abs(positionFrom._1 - positionTo._2) + math.abs(positionFrom._2 - positionTo._1)
      totalDistance += math.min(distance1, distance2)
    }
    totalDistance
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)
    val d = getMinimumDistanceForTwoCakes(n, a)
    println(d)
  }

}

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

object Codeforces1130B {

  def getMinimumDistanceForTwoCakes(n: Int, a: Seq[Int]): Int = {
    val numberPositionMap = new mutable.HashMap[Int, (Int, Int)]()
    for (i <- a.indices) {
      if (numberPositionMap.contains(a(i))) {
        numberPositionMap(a(i)) = (numberPositionMap(a(i))._1, i)
      } else {
        numberPositionMap(a(i)) = (i, -1)
      }
    }
    var totalDistance = 0
    var cursor = n
    while (cursor > 1) {
      val positionFrom = numberPositionMap(cursor)
      val positionTo = numberPositionMap(cursor - 1)
      val distance1 = math.abs(positionFrom._1 - positionTo._1) + math.abs(positionFrom._2 - positionTo._2)
      val distance2 = math.abs(positionFrom._1 - positionTo._2) + math.abs(positionFrom._2 - positionTo._1)
      totalDistance += math.min(distance1, distance2)
      cursor -= 1
    }
    val positionStart = numberPositionMap(1)
    totalDistance += positionStart._1 + positionStart._2
    totalDistance
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)
    val d = getMinimumDistanceForTwoCakes(n, a)
    println(d)
  }

}


Polycarp is reading a book consisting of $$$n$$$ pages numbered from $$$1$$$ to $$$n$$$. Every time he finishes the page with the number divisible by $$$m$$$, he writes down the last digit of this page number. For example, if $$$n=15$$$ and $$$m=5$$$, pages divisible by $$$m$$$ are $$$5, 10, 15$$$. Their last digits are $$$5, 0, 5$$$ correspondingly, their sum is $$$10$$$.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The following $$$q$$$ lines contain queries, one per line. Each query is given as two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^{16}$$$) — the number of pages in the book and required divisor, respectively.

For each query print the answer for it — the sum of digits written down by Polycarp.

//package codeforces.contest1213

object BookReading {

  val lastDigitToSeq: Map[Int, Seq[Int]] = Map(
    0 -> Seq(0),
    1 -> Seq(1, 2, 3, 4, 5, 6, 7, 8, 9, 0),
    2 -> Seq(2, 4, 6, 8, 0),
    3 -> Seq(3, 6, 9, 2, 5, 8, 1, 4, 7, 0),
    4 -> Seq(4, 8, 2, 6, 0),
    5 -> Seq(5, 0),
    6 -> Seq(6, 2, 8, 4, 0),
    7 -> Seq(7, 4, 1, 8, 5, 2, 9, 6, 3, 0),
    8 -> Seq(8, 6, 4, 2, 0),
    9 -> Seq(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
  )

  def main(args: Array[String]): Unit = {
    println {
      (1 to io.StdIn.readInt())
        .foldLeft(List.empty[Long]) {
          case (ls, _) =>
            val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toLong)

            val lastDigit = (m % 10).toInt
            val seq = lastDigitToSeq(lastDigit)
            val (freq: Int, sum: Int) = (seq.length, seq.sum)

            val count: Long = n / m

            ( + sum * (count / freq) + seq.take((count % freq).toInt).sum) :: ls
        }
        .reverse
        .mkString("\n")
    }
  }

}