You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).

For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic.

NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$  $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$  $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray
      val isNSmall = nm.head <= nm.last
      println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),
        if (isNSmall) grid else grid.transpose))
    }
  }

  // assume n <= m
  def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {
    var total = 0
    for (i <- 0 to (m + n - 3) / 2) {
      var zeroCount = 0
      var oneCount = 0
      for (j <- 0 to math.min(i, n - 1)) {
        if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1
        if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1
      }
      total += math.min(zeroCount, oneCount)
    }

    total
  }

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

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

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

}

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

  val t = readInt()

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

    var a = Array.ofDim[Array[Int]](n)
    (0 until n).foreach(a(_) = readLine().split(" ").map(_.toInt))

    var b = Array.fill((n + m) / 2)(Array(0, 0))
    for {
      i <- 1 to n
      j <- 1 to m
      k = i + j - 2
      d = k min (n + m - 2 - k)
    } b(d)(a(i - 1)(j - 1)) += 1

    val ans = b.take((n + m - 1) / 2).foldLeft(0)((a, t) => a + t.min)

    println(ans)
  }
}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray
      val isNSmall = nm.head <= nm.last
      println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),
        if (isNSmall) grid else grid.transpose))
    }
  }

  // assume n <= m
  def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {
    var total = 0
    for (i <- 0 to m / 2) {
      var zeroCount = 0
      var oneCount = 0
      for (j <- 0 to math.min(i, n - 1)) {
        if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1
        if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1
      }
      total += math.min(zeroCount, oneCount)
    }

    total
  }

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

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray
      val isNSmall = nm.head <= nm.last
      println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),
        if (isNSmall) grid else grid.transpose))
    }
  }

  // assume n <= m
  def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {
    var total = 0
    for (i <- 0 to (m - (n - 1) % 2) / 2) {
      var zeroCount = 0
      var oneCount = 0
      for (j <- 0 to math.min(i, n - 1)) {
        if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1
        if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1
      }
      total += math.min(zeroCount, oneCount)
    }

    total
  }

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

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readIntLine().toArray).toArray
      val isNSmall = nm.head <= nm.last
      println(calc(math.min(nm.head, nm.last), math.max(nm.head, nm.last),
        if (isNSmall) grid else grid.transpose))
    }
  }

  // assume n <= m
  def calc(n: Int, m: Int, grid: Array[Array[Int]]): Int = {
    var total = 0
    for (i <- 0 to (m - 1) / 2) {
      var zeroCount = 0
      var oneCount = 0
      for (j <- 0 to math.min(i, n - 1)) {
        if (grid(j)(i - j) == 0) zeroCount += 1 else oneCount += 1
        if (grid(n - 1 - j)(m - 1 - i + j) == 0) zeroCount += 1 else oneCount += 1
      }
      total += math.min(zeroCount, oneCount)
    }

    total
  }

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

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

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

}


You are given two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Array $$$a$$$ contains each odd integer from $$$1$$$ to $$$2n$$$ in an arbitrary order, and array $$$b$$$ contains each even integer from $$$1$$$ to $$$2n$$$ in an arbitrary order.You can perform the following operation on those arrays:   choose one of the two arrays  pick an index $$$i$$$ from $$$1$$$ to $$$n-1$$$  swap the $$$i$$$-th and the $$$(i+1)$$$-th elements of the chosen array  Compute the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$.For two different arrays $$$x$$$ and $$$y$$$ of the same length $$$n$$$, we say that $$$x$$$ is lexicographically smaller than $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, the array $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2n$$$, all $$$a_i$$$ are odd and pairwise distinct) — array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 2n$$$, all $$$b_i$$$ are even and pairwise distinct) — array $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print one integer: the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$. We can show that an answer always exists.

NoteIn the first example, the array $$$a$$$ is already lexicographically smaller than array $$$b$$$, so no operations are required.In the second example, we can swap $$$5$$$ and $$$3$$$ and then swap $$$2$$$ and $$$4$$$, which results in $$$[3, 5, 1]$$$ and $$$[4, 2, 6]$$$. Another correct way is to swap $$$3$$$ and $$$1$$$ and then swap $$$5$$$ and $$$1$$$, which results in $$$[1, 5, 3]$$$ and $$$[2, 4, 6]$$$. Yet another correct way is to swap $$$4$$$ and $$$6$$$ and then swap $$$2$$$ and $$$6$$$, which results in $$$[5, 3, 1]$$$ and $$$[6, 2, 4]$$$.

object B extends App {

  def swaps(an: IndexedSeq[Int], bn: IndexedSeq[Int]): Int = {
    val n    = an.length
    val ab2i = Array.fill(2 * n + 1)(0)
    (0 until n).foreach { i => ab2i(an(i)) = i; ab2i(bn(i)) = i }

    (3 to (2 * n))
      .foldLeft((ab2i(1) + ab2i(2), ab2i(1), ab2i(2))) { case ((count, odd, even), ab) =>
        val i = ab2i(ab)
        (ab % 2) match {
          case 0 => (count min (i + odd), odd, even min i)
          case _ => (count, odd min i, even)
        }
      }
      ._1
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n)
    val bn = nextInts(n)

    out.println(swaps(an, bn))
    out.flush()
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {

  def swaps(an: IndexedSeq[Int], bn: IndexedSeq[Int]): Int = {
    val n             = an.length
    val element2index = Array.fill(2 * n + 1)(0)
    (0 until n).foreach { i =>
      element2index(an(i)) = i
      element2index(bn(i)) = i
    }

    val minOddIndex  = element2index(1)
    val minEvenIndex = element2index(2)

    (3 to (2 * n))
      .foldLeft((minOddIndex + minEvenIndex, minOddIndex, minEvenIndex)) {
        case ((count, minOddIndex, minEvenIndex), element) =>
          val index = element2index(element)
          if (element % 2 == 0) {
            (count min (index + minOddIndex), minOddIndex, minEvenIndex min index)
          } else {
            (count, minOddIndex min index, minEvenIndex)
          }
      }
      ._1

    // val aj2j = Array.fill(2 * an.length)(0)
    // an.indices.foreach(j => aj2j(an(j)) = j)

    // bn.indices.foldLeft(Int.MaxValue) { (count, i) =>
    //   val bi = bn(i)
    //   val aj = (1 to (bi, 2)).minBy(aj2j)
    //   val j  = aj2j(aj)
    //   count min (i + j)
    // }
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n)
    val bn = nextInts(n)

    out.println(swaps(an, bn))
    out.flush()
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

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

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

    def RecursiveBinarySearch(Element_to_Search: Int)
                             (low: Int,
                              high: Int): Int =
    {
        // If element not found
        if (high - low <= 1) {
            if (a_row(low) < Element_to_Search)
                return low
            else
                return high
        }

        // Getting the middle element
        var middle = low + (high - low + 1) / 2

        // If element found

        // Searching in the left half
        if (a_row(middle) < Element_to_Search)
            return RecursiveBinarySearch(Element_to_Search)(low, middle)

        // Searching in the right half
        else
            return RecursiveBinarySearch(Element_to_Search)(middle + 1, high)
    }
    val a_row = new ArrayBuffer[Int]()

    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (tt <- 1 to t) {
            val n = readInt()
            a_row.clear()
            var min_s = 2 * n + 1
            for (i <- 1 to n) {
                val tmp = readInt()
                min_s = min(min_s, tmp)
                a_row.append(min_s)
            }
            var ans = n + 1
            for (i <- 1 to n) {
                val tmp = readInt()
                ans = min(ans, i-1+RecursiveBinarySearch(tmp)(0, n-1))
            }
            writer.println(ans)
            writer.flush()
        }
    }
}

object B extends App {

  def swaps(an: Seq[Int], bn: Seq[Int]): Int = {

    def search(from: Int, to: Int, f: Int => Boolean): Int = {
      @annotation.tailrec
      def go(left: Int, right: Int): Int =
        if (left + 1 >= right) left
        else {
          val middle = (left + right) >>> 1

          f(middle) match {
            case true  => go(middle, right)
            case false => go(left, middle)
          }
        }
      go(from, to)
    }

    val cn = an.zipWithIndex.sorted

    bn.zipWithIndex.foldLeft(Int.MaxValue) { case (count, (bi, i)) =>
      val j = search(0, cn.length, j => cn(j)._1 < bi)
      count min (i + cn(j)._2)
    }
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n)
    val bn = nextInts(n)

    out.println(swaps(an, bn))
    out.flush()
  }

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {

  def swaps(an: Seq[Int], bn: Seq[Int]): Int = {

    def search(from: Int, to: Int, f: Int => Boolean): Int = {
      @annotation.tailrec
      def go(left: Int, right: Int): Int =
        if (left + 1 >= right) left
        else {
          val middle = (left + right) >>> 1

          f(middle) match {
            case true  => go(middle, right)
            case false => go(left, middle)
          }
        }
      go(from, to)
    }

    val cn = an.zipWithIndex.sorted

    bn.zipWithIndex.foldLeft(Int.MaxValue) { case (count, (bi, i)) =>
      val j = search(0, cn.length, j => cn(j)._1 < bi)
      count min (i + cn(j)._2)
    }
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val bn = readLine().split(" ").map(_.toInt)

    println(swaps(an, bn))
  }
}


Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:  She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her .  Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.

The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones.  The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.

Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.

NotePlease note that the answers to the questions may overflow 32-bit integer type.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toLong)
  val sum = data.tail.scan(data.head){_ + _}
  val sorted = data.sorted
  val sorsum = sorted.tail.scan(sorted.head){_ + _}
  val q = in.next().toInt
  val res = (1 to q).map { _ =>
    val Array(queryType, l, r) = in.next().split(" ").map(_.toInt)
    if (queryType == 1) {
      sum(r - 1) - (if (l >= 2) sum(l - 2) else 0)
    } else {
      sorsum(r - 1) - (if (l >= 2) sorsum(l - 2) else 0)
    }
  }
  println(res.mkString("\n"))
}

import scala.util.Try

object B433 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readLongs(n)
    val sorted = input.sortBy(identity)
    for(i <- 1 until n) {
      input(i) += input(i-1)
    }
    for(i <- 1 until n) {
      sorted(i) += sorted(i-1)
    }

    val Array(m) = readInts(1)
    for(_ <- 0 until m) {
      val Array(t, l, r) = readInts(3)
      if(t == 1) {
        if(l-2 >= 0)
          println(input(r-1) - input(l-2))
        else
          println(input(r-1))
      } else {
        if(l-2 >= 0)
          println(sorted(r-1) - sorted(l-2))
        else
          println(sorted(r-1))
      }
    }
  }
}

import java.util.Scanner
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.math.Ordering.Implicits._
import scala.util.Random
import scala.util.control.Breaks._

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

  object Input {
    import java.lang.Character._

    lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))
    var buf: Array[Char] = Array()
    var pos: Int = 0

    def next(): String = {
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      while (isWhitespace(buf(pos))) {
        pos += 1
      }
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      val s = pos
      while (pos < buf.length && !isWhitespace(buf(pos))) {
        pos += 1
      }
      new java.lang.String(buf, s, pos - s)
    }

    def nextInt(): Int = next.toInt

    def nextLong(): Long = next.toLong

    def nextFloat(): Float = next.toFloat

    def nextDouble(): Double = next.toDouble

    val nextString: () => String = next _
  }

  import Input._

  val N = nextInt
  val V = Array.fill(N)(nextLong)
  val U = V.sorted
  val vv = Array.fill(N + 1)(0L)
  val uu = Array.fill(N + 1)(0L)
  (0 until N).foreach { i =>
    vv(i + 1) = vv(i) + V(i)
    uu(i + 1) = uu(i) + U(i)
  }
  val M = nextInt

  def solve(): Long = {

    def type1(l: Int, r: Int): Long = vv(r + 1) - vv(l)

    def type2(l: Int, r: Int): Long = uu(r + 1) - uu(l)

    val t = nextInt
    val l, r = nextInt - 1
    t match {
      case 1 => type1(l, r)
      case 2 => type2(l, r)
      case _ => throw new Exception("something wrong")
    }
  }

  for (_ <- 0 until M) out.println(solve)
  out.flush
}


Ivan is a novice painter. He has $$$n$$$ dyes of different colors. He also knows exactly $$$m$$$ pairs of colors which harmonize with each other.Ivan also enjoy playing chess. He has $$$5000$$$ rooks. He wants to take $$$k$$$ rooks, paint each of them in one of $$$n$$$ colors and then place this $$$k$$$ rooks on a chessboard of size $$$10^{9} \times 10^{9}$$$.Let's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.Ivan wants his arrangement of rooks to have following properties: For any color there is a rook of this color on a board; For any color the set of rooks of this color is connected; For any two different colors $$$a$$$ $$$b$$$ union of set of rooks of color $$$a$$$ and set of rooks of color $$$b$$$ is connected if and only if this two colors harmonize with each other.Please help Ivan find such an arrangement.

The first line of input contains $$$2$$$ integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le min(1000, \,\, \frac{n(n-1)}{2})$$$) — number of colors and number of pairs of colors which harmonize with each other. In next $$$m$$$ lines pairs of colors which harmonize with each other are listed. Colors are numbered from $$$1$$$ to $$$n$$$. It is guaranteed that no pair occurs twice in this list.

Print $$$n$$$ blocks, $$$i$$$-th of them describes rooks of $$$i$$$-th color. In the first line of block print one number $$$a_{i}$$$ ($$$1 \le a_{i} \le 5000$$$) — number of rooks of color $$$i$$$. In each of next $$$a_{i}$$$ lines print two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, \,\, y \le 10^{9}$$$) — coordinates of the next rook. All rooks must be on different cells. Total number of rooks must not exceed $$$5000$$$. It is guaranteed that the solution exists.

NoteRooks arrangements for all three examples (red is color $$$1$$$, green is color $$$2$$$ and blue is color $$$3$$$).

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val P = Array.ofDim[(Int, Int)](M)
    rep(M) { i =>
      val a, b = ni() - 1
      P(i) = (min(a, b), max(a, b))
    }

    val ans = Array.fill[ArrayBuffer[(Int, Int)]](N)(ArrayBuffer())
    rep(N) { i =>
      ans(i) += ((100 * i + i, 100 * i + i))
    }
    rep(M) { i =>
      val (a, b) = P(i)
      val xa = 100 * a + a
      val ya = 100 * a + b
      val xb = 100 * b + a
      val yb = 100 * b + b
      ans(a) += ((xa, ya))
      ans(b) += ((xb, yb))
      ans(a) += ((xb, ya)) // 結合するところ
    }

    rep(N) { i =>
      out.println(ans(i).length)
      ans(i) foreach { case (x, y) =>
        out.println(s"${x+1} ${y+1}")
      }
    }
  }

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


Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$.

If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO".

NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product.

object cf1514a {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

  def readLong(): Long= {
		Console.in.readLine().toLong
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		val res = for (nCase <- 1 to cases) yield {
			readInt()
			val data = readInts()

			!data.forall( v => {
				val sq = Math.floor(Math.sqrt(v)).toInt
				sq*sq == v
			})
		}
		res.foreach(if (_) println("YES") else println("NO"))
  }
}

object Solver {
  import InOut._
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to nextInt) {
      val n = nextInt
      val arr = nextInts(n)
      var ans = "NO"
      for (num <- arr) {
        val rt = Math.round(Math.sqrt(num))
        if (rt * rt != num)
          ans = "YES"
      }
      out.println(ans)
    }
    out.flush()
  }
}

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


Let's call a positive integer composite if it has at least one divisor other than $$$1$$$ and itself. For example:  the following numbers are composite: $$$1024$$$, $$$4$$$, $$$6$$$, $$$9$$$;  the following numbers are not composite: $$$13$$$, $$$1$$$, $$$2$$$, $$$3$$$, $$$37$$$. You are given a positive integer $$$n$$$. Find two composite integers $$$a,b$$$ such that $$$a-b=n$$$.It can be proven that solution always exists.

The input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^7$$$): the given integer.

Print two composite integers $$$a,b$$$ ($$$2 \leq a, b \leq 10^9, a-b=n$$$). It can be proven, that solution always exists. If there are several possible solutions, you can print any.

import java.util.Scanner

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

  val n = sc.nextInt

  val (a, b) =
    if(n == 1) (9,8)
    else (3 * n, 2 * n)

  println(s"$a $b")

}

import java.util.Scanner

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

  val n = sc.nextInt
  val a = 3 * n
  val b = 3 * n

  println(s"$a $b")

}

import java.util.Scanner

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

  val n = sc.nextInt
  val a = 3 * n
  val b = 2 * n

  println(s"$a $b")

}

import java.util.Scanner

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

  val n = sc.nextInt

  val (a, b) =
    if(n == 1) (8,9)
    else (3 * n, 2 * n)

  println(s"$a $b")

}


This is an interactive problem.In good old times dwarves tried to develop extrasensory abilities:  Exactly n dwarves entered completely dark cave.  Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves.  Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information.  The task for dwarves was to got diverged into two parts — one with dwarves with white hats and one with black hats. After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?You are asked to successively name n different integer points on the plane. After naming each new point you will be given its color — black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.In this problem, the interactor is adaptive — the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.

NoteIn the sample input and output values are aligned only for simplicity of interpreting them chronologically. In real interaction no "extra" line breaks should appear.The following picture illustrates the first test.

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

    /**
      * yの高さの左右を左から白,右から黒で埋めていって、中間の未定義部分を返す
      */
    def ask(y: Int, cnt: Int): (Int, Int) = {
      var l = 0
      var h = 1e9.toInt
      rep(cnt) { _ =>
        val mid = (h + l) / 2
        println(s"$mid $y")
        ns() match {
          case "black" => h = mid
          case "white" => l = mid
        }
      }
      (l, h)
    }

    val (x0_l, x0_r) = ask(0, N/2)
    val (x1_l, x1_r) = ask(5e8.toInt, N - N/2)

    println(s"${(x0_l + x0_r)/2} 0 ${(x1_l+ x1_r)/2} ${5e8.toInt}")
  }

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


Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.

The only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only.

Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if

NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.

object B extends App {

  val s = readLine.map(_ - 'a')
  val l = s.length

  val positionsOfLetter = s.zipWithIndex.groupBy(_._1).map {
    case (key, values) =>
      key -> values.map(_._2)
  }

  var goodCount = 0

  for (first <- positionsOfLetter.keys) {
    var max = 0
    for (i <- 1 until l) {
      val counts = Array.fill('z' - 'a' + 1){ 0 }
      for (k <- positionsOfLetter(first)) {
        counts(s((i + k) % l)) += 1
      }
      max = Math.max(max, counts.count(_ == 1))
    }
    goodCount += max
  }

  println(goodCount.toDouble / l)
}

import java.util

object B extends App {

  val s = readLine.map(_ - 'a')
  val l = s.length
  val letters = s.distinct

  def get(i: Int): Int = s((i + l) % l )

  val sByLet = s.groupBy(identity).map {
    case (k, v) => k -> v.size
  }

  val counts = Array.fill(letters.max + 1, letters.max + 1, l)(0)

  for (k <- 0 until l) {
    val first = get(k)
    //util.Arrays.fo(counts, 0)
    for (i <- 1 until l) {
      counts(first)(get(i + k))(i) += 1
      //if (counts(first)(get(i + k))(i) > 1) good = false
    }
  }

  var goodCount = 0d

  for (k <- 0 until l) {
    val first = get(k)
    var good = false
    for (i <- 1 until l) {
      if (counts(first)(get(i + k))(i) == 1) good = true
    }
    //println(k, first, good)
    if (good) goodCount += 1d // sByLet(first)
  }

  val res = goodCount / l

  println(res)
}


Pavel has several sticks with lengths equal to powers of two.He has $$$a_0$$$ sticks of length $$$2^0 = 1$$$, $$$a_1$$$ sticks of length $$$2^1 = 2$$$, ..., $$$a_{n-1}$$$ sticks of length $$$2^{n-1}$$$. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.It is forbidden to break sticks, and each triangle should consist of exactly three sticks.Find the maximum possible number of triangles.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 300\,000$$$) — the number of different lengths of sticks. The second line contains $$$n$$$ integers $$$a_0$$$, $$$a_1$$$, ..., $$$a_{n-1}$$$ ($$$1 \leq a_i \leq 10^9$$$), where $$$a_i$$$ is the number of sticks with the length equal to $$$2^i$$$.

Print a single integer — the maximum possible number of non-degenerate triangles that Pavel can make.

NoteIn the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^4, 2^4)$$$, $$$(2^1, 2^3, 2^3)$$$, $$$(2^1, 2^2, 2^2)$$$.In the second example, Pavel cannot make a single triangle.In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^0, 2^0)$$$, $$$(2^1, 2^1, 2^1)$$$, $$$(2^2, 2^2, 2^2)$$$.

object E extends App {

  val numCount = scala.io.StdIn.readLine()

  val stickCounts = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

  val answer = solve(stickCounts, 0L, 0L)

  println(answer)

  private def solve(list: List[Int], count: Long, debt: Long): Long = {
//    println(s"Before: left: $list, count: $count, debt $debt")
    list match {
      case Nil     => count - debt
      case x :: xs => {
        val forDebt = Math.min(x / 2, debt)
        val (updDebt, xAfterDebt) = (debt - forDebt, x - (forDebt * 2))

        val forFull = xAfterDebt / 3
        val (updCount, xAfterFull) = (count + forFull, xAfterDebt - (forFull * 3))

        solve(xs, updCount + xAfterFull, updDebt + xAfterFull)
      }
    }
  }
}

object E extends App {
  val numCount = scala.io.StdIn.readLine()

  val stickCounts = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

  val (simplifiedSeq, count) = simplify(stickCounts)

  val answer = solve(simplifiedSeq, count, 0L)

  println(answer)

  private def simplify(list: List[Int]): (List[Int], Long) = {
    var accCount = 0L
    val accList = list.map { el =>
      accCount += (el / 3)
      el % 3
    }
    (accList, accCount)
  }

  private def solve(seq: List[Int], count: Long, debt: Long): Long = {
    seq match {
      case Nil     => count - debt
      case x :: xs => {
        if (x == 2 && debt > 0) solve(xs, count, debt - 1)
        else solve(xs, count + x, debt + x)
      }
    }
  }
}


Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $$$a=[1, 3, 3, 7]$$$ is good because there is the element $$$a_4=7$$$ which equals to the sum $$$1 + 3 + 3$$$.You are given an array $$$a$$$ consisting of $$$n$$$ integers. Your task is to print all indices $$$j$$$ of this array such that after removing the $$$j$$$-th element from the array it will be good (let's call such indices nice).For example, if $$$a=[8, 3, 5, 2]$$$, the nice indices are $$$1$$$ and $$$4$$$:   if you remove $$$a_1$$$, the array will look like $$$[3, 5, 2]$$$ and it is good;  if you remove $$$a_4$$$, the array will look like $$$[8, 3, 5]$$$ and it is good. You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — elements of the array $$$a$$$.

In the first line print one integer $$$k$$$ — the number of indices $$$j$$$ of the array $$$a$$$ such that after removing the $$$j$$$-th element from the array it will be good (i.e. print the number of the nice indices). In the second line print $$$k$$$ distinct integers $$$j_1, j_2, \dots, j_k$$$ in any order — nice indices of the array $$$a$$$. If there are no such indices in the array $$$a$$$, just print $$$0$$$ in the first line and leave the second line empty or do not print it at all.

NoteIn the first example you can remove any element with the value $$$2$$$ so the array will look like $$$[5, 1, 2, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 1 + 2 + 2$$$).In the second example you can remove $$$8$$$ so the array will look like $$$[3, 5, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 3 + 2$$$). You can also remove $$$2$$$ so the array will look like $$$[8, 3, 5]$$$. The sum of this array is $$$16$$$ and there is an element equals to the sum of remaining elements ($$$8 = 3 + 5$$$).In the third example you cannot make the given array good by removing exactly one element.

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(N)
    val S = sumL(A)
    val mx = A.max
    val mxIx = A.indexWhere(_ == mx)
    val A2 = A.take(mxIx) ++ A.drop(mxIx + 1)
    val mx2 = A2.max
    val mx2Ix = A2.indexWhere(_ == mx2)
    val S1 = S - mx

    val ans = ArrayBuffer[Int]()
    rep(N) { i =>
      if (A(i) == mx) {
        if (S1 - mx2 == mx2) ans += i + 1
      } else {
        if (S1 - A(i) == mx) ans += i + 1
      }
    }

    out.println(ans.length)
    out.println(ans.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, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    rep(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    rep(n) { i =>
      rep(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

import java.io._

object C extends App {
	val n = InputReader.readLine.toInt
	var arr = InputReader.readLine.split(" ").map(_.toLong)

	def op(par: Array[Long], e: Long) = {
		if(e > par(0))
			Array(e, par(0))

		else if(e > par(1))
			Array(par(0), e)

		else par
	}

	val res = arr.foldLeft(Array(0L, 0L))(op)
	val s = arr.sum

	def whom = (x: Long) => if (x == res(0)) res(1) else res(0)
	val ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))

	val out = new PrintWriter(System.out)
	out.println(ans.length)
	ans.foreach(x => out.print(s"${x._2 + 1} "))
	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	def readLine() = rd.readLine
}

import java.io._

object C extends App {
	val n = InputReader.readLine.toInt
	var arr = InputReader.readLine.split(" ").map(_.toLong)

	val res = arr.foldLeft(Array(0L, 0L)) (
		(par, e) => {
			if(e > par(0))
				Array(e, par(0))

			else if(e > par(1))
				Array(par(0), e)

			else par
		}
	)

	val s = arr.sum
	def whom(x: Long) = if (x == res(0)) res(1) else res(0)
	val ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))

	val out = new PrintWriter(System.out)
	out.println(ans.length)
	ans.foreach(x => out.print(s"${x._2 + 1} "))
	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	def readLine() = rd.readLine
}

object CF_521_3_C {
    // The "good" number must always be the largest
    // In the case where we're examining the max for niceness, use the second largest
    // An element e is nice if the subtotal of the rest is 2 * the max, i.e. total - e = 2 *

  def solve(n: Int, as: Seq[Long]): (Int, Seq[Int]) = {
    val total = as.sum
    val max = as.max
    val secondMax = as.diff(Seq(max)).max
    val nices = for {
      (e, i) <- as.zipWithIndex
      if (e != max && total - e == 2 * max) || (e == max && total - e == 2 * secondMax)
    } yield i + 1
    (nices.size, nices)
  }

  // `solution` is defined by the input format - and can be called both from main and test script without repeating
  def solution(i: Input) = solve(i.int, {i.nextLine; i.collect(_.toLong)})

//     ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val sol = solution(new Input(System.in))
    out.println(sol._1)
    out.println(sol._2 mkString " ")
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
}

import java.io._

object C extends App {
	val n = InputReader.readLine.toInt
	var arr = InputReader.readLine.split(" ").map(_.toInt)

	def op(par: Array[Int], e: Int) = {
		if(e > par(0))
			Array(e, par(1))

		else if(e > par(1))
			Array(par(0), e)

		else par
	}

	val res = arr.foldLeft(Array(0, 0))(op)
	val s = arr.sum

	def whom = (x: Int) => if (x == res(0)) res(1) else res(0)
	val ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))

	// println(ans.length)
	// ans.foreach(x => print(s"${x._2 + 1} "))

	val out = new PrintWriter(System.out)
	out.println(ans.length)
	ans.foreach(x => out.print(s"${x._2 + 1} "))
	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	def readLine() = rd.readLine
}

import java.io._

object C extends App {
	val n = InputReader.readLine.toInt
	var arr = InputReader.readLine.split(" ").map(_.toLong)

	def op(par: Array[Long], e: Long) = {
		if(e > par(0))
			Array(e, par(1))

		else if(e > par(1))
			Array(par(0), e)

		else par
	}

	val res = arr.foldLeft(Array(0L, 0L))(op)
	val s = arr.sum

	def whom = (x: Long) => if (x == res(0)) res(1) else res(0)
	val ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))

	val out = new PrintWriter(System.out)
	out.println(ans.length)
	ans.foreach(x => out.print(s"${x._2 + 1} "))
	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	def readLine() = rd.readLine
}

import java.io._

object C extends App {
	val n = InputReader.readLine.toInt
	var arr = InputReader.readLine.split(" ").map(_.toInt)

	def op(par: Array[Int], e: Int) = {
		if(e > par(0))
			Array(e, par(1))

		else if(e > par(1))
			Array(par(0), e)

		else par
	}

	val res = arr.foldLeft(Array(0, 0))(op)
	val s = arr.sum

	def whom = (x: Int) => if (x == res(0)) res(1) else res(0)
	val ans = arr.zipWithIndex.filter(x => s - x._1 == 2 * whom(x._1))

	// println(ans.length)
	// ans.foreach(x => print(s"${x._2 + 1} "))

	val out = new PrintWriter(System.out)
	out.println(ans.length)
	ans.foreach(x => out.print(s"${x._2 + 1} "))
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	def readLine() = rd.readLine
}

object CF_521_3_C {
  def isGood(xs: Map[Long,Int], sum: Long) = sum % 2 == 0 && xs(sum/2) > 0

  def solve(n: Int, as: Seq[Long]): (Int, Seq[Int]) = {
    val total = as.sum
    val counts: Map[Long, Int] = as.groupBy(identity).mapValues(_.size).withDefaultValue(0)
    val nices = for {
      (a, i) <- as.zipWithIndex
      if isGood(counts + (a -> (counts(a) - 1)), total - a)
    } yield i + 1
    (nices.size, nices)
  }

  // `solution` is defined by the input format - and can be called both from main and test script without repeating
  def solution(i: Input) = solve(i.int, {i.nextLine; i.collect(_.toLong)})

//     ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val sol = solution(new Input(System.in))
    out.println(sol)
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
}


Lunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself.Let's describe this problem in a mathematical way. Consider a timeline from time $$$1$$$ to $$$n$$$. The $$$i$$$-th red envelope will be available from time $$$s_i$$$ to $$$t_i$$$, inclusive, and contain $$$w_i$$$ coins. If Bob chooses to collect the coins in the $$$i$$$-th red envelope, he can do it only in an integer point of time between $$$s_i$$$ and $$$t_i$$$, inclusive, and he can't collect any more envelopes until time $$$d_i$$$ (inclusive) after that. Here $$$s_i \leq t_i \leq d_i$$$ holds.Bob is a greedy man, he collects coins greedily — whenever he can collect coins at some integer time $$$x$$$, he collects the available red envelope with the maximum number of coins. If there are multiple envelopes with the same maximum number of coins, Bob would choose the one whose parameter $$$d$$$ is the largest. If there are still multiple choices, Bob will choose one from them randomly.However, Alice — his daughter — doesn't want her father to get too many coins. She could disturb Bob at no more than $$$m$$$ integer time moments. If Alice decides to disturb Bob at time $$$x$$$, he could not do anything at time $$$x$$$ and resumes his usual strategy at the time $$$x + 1$$$ (inclusive), which may lead to missing some red envelopes.Calculate the minimum number of coins Bob would get if Alice disturbs him optimally.

The first line contains three non-negative integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq 200$$$, $$$1 \leq k \leq 10^5$$$), denoting the length of the timeline, the number of times Alice can disturb Bob and the total number of red envelopes, respectively. The following $$$k$$$ lines describe those $$$k$$$ red envelopes. The $$$i$$$-th line contains four positive integers $$$s_i$$$, $$$t_i$$$, $$$d_i$$$ and $$$w_i$$$ ($$$1 \leq s_i \leq t_i \leq d_i \leq n$$$, $$$1 \leq w_i \leq 10^9$$$) — the time segment when the $$$i$$$-th envelope is available, the time moment Bob can continue collecting after collecting the $$$i$$$-th envelope, and the number of coins in this envelope, respectively.

Output one integer — the minimum number of coins Bob would get if Alice disturbs him optimally.

NoteIn the first sample, Alice has no chance to disturb Bob. Therefore Bob will collect the coins in the red envelopes at time $$$1$$$ and $$$5$$$, collecting $$$13$$$ coins in total.In the second sample, Alice should disturb Bob at time $$$1$$$. Therefore Bob skips the first envelope, collects the second one and can not do anything after that. So the answer is $$$2$$$.

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

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

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val S, T, D, W = Array.ofDim[Int](K)
    REP(K) { i =>
      S(i) = ni() - 1
      T(i) = ni() - 1
      D(i) = ni() - 1
      W(i) = ni()
    }

    // Bobがおのおのの時点で選ぶ選択肢
    def calcGreedy: Array[Int] = {
      import java.util
      import java.util.Comparator

      val choise = Array.fill[Int](N)(-1)
      val t = new util.TreeSet[Integer](new Comparator[Integer] {
        // (W, D, id) のdesc
        override def compare(o1: Integer, o2: Integer): Int = {
          if (W(o1) == W(o2)) {
            if (D(o1) == D(o2))
              o2.compareTo(o1)
            else
              Integer.compare(D(o2), D(o1))
          } else Integer.compare(W(o2), W(o1))
        }
      })

      val starts, ends = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())
      REP(K) { i =>
        starts(S(i)) += i
        ends(T(i)) += i
      }

      REP(N) { i =>
        val ss = starts(i)
        REP(ss.length) { j =>
          t.add(ss(j))
        }

        if (!t.isEmpty) choise(i) = t.first()

        val es = ends(i)
        REP(es.length) { j =>
          t.remove(es(j))
        }
      }

      choise
    }

    val choise = calcGreedy
//        debug(choise)

    val INF = Long.MaxValue / 2

    // i=Nは時間を超えた向こう側をまとめたもの
    val dp = Array.fill[Long](N + 1, M + 1)(INF)
    dp(0)(M) = 0
    REP(N) { i =>
      REP(M + 1) { m =>
        if (m > 0) dp(i + 1)(m - 1) = min(dp(i + 1)(m - 1), dp(i)(m)) // skip

        // 遷移
        if (choise(i) != -1) {
          val k = choise(i)

          // 時間を溢れても選ぶことはできる
          val dest = min(D(k) + 1, N)
          dp(dest)(m) = min(dp(dest)(m), dp(i)(m) + W(k))
        } else {
          // 選ぶものがないので単に時間が過ぎる
          dp(i + 1)(m) = min(dp(i + 1)(m), dp(i)(m))
        }
      }
    }

//        REP(N + 1) { i =>
//          debug(dp(i))
//        }

    val ans = dp(N).min
    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    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 map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val S, T, D, W = Array.ofDim[Int](K)
    REP(K) { i =>
      S(i) = ni() - 1
      T(i) = ni() - 1
      D(i) = ni()
      W(i) = ni()
    }

    // Bobがおのおのの時点で選ぶ選択肢
    def calcGreedy: Array[Int] = {
      import java.util
      import java.util.Comparator

      val choise = Array.fill[Int](N)(-1)
      val t = new util.TreeSet[Integer](new Comparator[Integer] {
        // (W, D, id) のdesc
        override def compare(o1: Integer, o2: Integer): Int = {
          if (W(o1) == W(o2)) {
            if (D(o1) == D(o2))
              Integer.compare(o2, o1)
            else
              Integer.compare(D(o2), D(o1))
          } else Integer.compare(W(o2), W(o1))
        }
      })

      val starts, ends = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())
      REP(K) { i =>
        starts(S(i)) += i
        ends(T(i)) += i
      }

      REP(N) { i =>
        val ss = starts(i)
        val es = ends(i)
        REP(ss.length) { j =>
          t.add(ss(j))
        }

        if (!t.isEmpty) choise(i) = t.first()

        REP(es.length) { j =>
          t.remove(es(j))
        }
      }

      choise
    }

    val choise = calcGreedy
    //    debug(choise)

    val INF = Long.MaxValue / 2

    // i=Nは時間を超えた向こう側をまとめたもの
    val dp = Array.fill[Long](N + 1, M + 1)(INF)
    dp(0)(M) = 0
    REP(N) { i =>
      REP(M + 1) { m =>
        if (m > 0) dp(i + 1)(m - 1) = min(dp(i + 1)(m - 1), dp(i)(m)) // skip

        // 遷移
        if (choise(i) != -1) {
          val k = choise(i)

          // 時間を溢れても選ぶことはできる
          val dest = min(i + D(k), N)
          dp(dest)(m) = min(dp(dest)(m), dp(i)(m) + W(k))
        } else {
          // 選ぶものがないので単に時間が過ぎる
          dp(i + 1)(m) = min(dp(i + 1)(m), dp(i)(m))
        }
      }
    }

    //    REP(N + 1) { i =>
    //      debug(dp(i))
    //    }

    val ans = dp(N).min
    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    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 map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val S, T, D, W = Array.ofDim[Int](K)
    REP(K) { i =>
      S(i) = ni() - 1
      T(i) = ni() - 1
      D(i) = ni()
      W(i) = ni()
    }

    // Bobがおのおのの時点で選ぶ選択肢
    def calcGreedy: Array[Int] = {
      import java.util
      import java.util.Comparator

      val choise = Array.fill[Int](N)(-1)
      val t = new util.TreeSet[Integer](new Comparator[Integer] {
        // (W, D) のdesc
        override def compare(o1: Integer, o2: Integer): Int = {
          if (W(o1) == W(o2)) Integer.compare(D(o2), D(o1))
          else Integer.compare(W(o2), W(o1))
        }
      })

      val starts, ends = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())
      REP(K) { i =>
        starts(S(i)) += i
        ends(T(i)) += i
      }

      REP(N) { i =>
        val ss = starts(i)
        val es = ends(i)
        REP(ss.length) { j =>
          t.add(ss(j))
        }

        if (!t.isEmpty) choise(i) = t.first()

        REP(es.length) { j =>
          t.remove(es(j))
        }
      }

      choise
    }

    val choise = calcGreedy
//    debug(choise)

    val INF = Long.MaxValue / 2

    // i=Nは時間を超えた向こう側をまとめたもの
    val dp = Array.fill[Long](N + 1, M + 1)(INF)
    dp(0)(M) = 0
    REP(N) { i =>
      REP(M + 1) { m =>
        if (m > 0) dp(i + 1)(m - 1) = min(dp(i + 1)(m - 1), dp(i)(m)) // skip

        // 遷移
        if (choise(i) != -1) {
          val k = choise(i)

          // 時間を溢れても選ぶことはできる
          val dest = min(i + D(k), N)
          dp(dest)(m) = min(dp(dest)(m), dp(i)(m) + W(k))
        } else {
          // 選ぶものがないので単に時間が過ぎる
          dp(i + 1)(m) = min(dp(i + 1)(m), dp(i)(m))
        }
      }
    }

//    REP(N + 1) { i =>
//      debug(dp(i))
//    }

    val ans = dp(N).min
    out.println(ans)
  }

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

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

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

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

  def debug(num: Long): Unit = {
    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 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
  }
}


There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$).  Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.

Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.

NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).

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, K = ni()
    val H = na(N)
    val ms = H.min
    val mx = H.max
    val H2 = Array.ofDim[Int](mx + 1)
    rep(N) { i =>
      H2(H(i)) += 1
    }

    var ans = 0
    var cnt = 0
    var num = 0
    rep_r(mx - ms, ms + 1) { h =>
      num += H2(h)
      if (cnt + num > K) {
        ans += 1
        cnt = num
      } else {
        cnt += num
      }
    }

    if (cnt > 0) ans += 1

    out.println(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()
    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, K = ni()
    val H = na(N)
    val ms = H.min
    val mx = H.max
    val H2 = Array.ofDim[Int](mx + 1)
    rep(N) { i =>
      H2(H(i)) += 1
    }

    var ans = 0
    var cnt = 0
    var num = 0
    rep_r(mx - ms, ms + 1) { h =>
      num += H2(h)
      if (cnt + num >= K) {
        ans += 1
        cnt = num
      } else {
        cnt += num
      }
    }

    if (cnt > 0) ans += 1

    out.println(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
  }
}