This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on $$$n$$$ are greater than in the easy version of the problem.You are given an array $$$a$$$ of $$$n$$$ integers (the given array can contain equal elements). You can perform the following operations on array elements:  choose any index $$$i$$$ ($$$1 \le i \le n$$$) and move the element $$$a[i]$$$ to the begin of the array;  choose any index $$$i$$$ ($$$1 \le i \le n$$$) and move the element $$$a[i]$$$ to the end of the array. For example, if $$$n = 5$$$, $$$a = [4, 7, 2, 2, 9]$$$, then the following sequence of operations can be performed:   after performing the operation of the first type to the second element, the array $$$a$$$ will become $$$[7, 4, 2, 2, 9]$$$;  after performing the operation of the second type to the second element, the array $$$a$$$ will become $$$[7, 2, 2, 9, 4]$$$. You can perform operations of any type any number of times in any order.Find the minimum total number of operations of the first and second type that will make the $$$a$$$ array sorted in non-decreasing order. In other words, what is the minimum number of operations must be performed so the array satisfies the inequalities $$$a[1] \le a[2] \le \ldots \le a[n]$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of the array $$$a$$$. Then follow $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — an array that needs to be sorted by the given operations. The given array can contain equal elements. The sum of $$$n$$$ for all test cases in one test does not exceed $$$2 \cdot 10^5$$$.

For each test case output one integer — the minimum total number of operations of the first and second type, which will make the array sorted in non-decreasing order.

NoteIn the first test case, you first need to move two 2, to the beginning of the array. Therefore, the desired sequence of operations: $$$[4, 7, 2, 2, 9] \rightarrow [2, 4, 7, 2, 9] \rightarrow [2, 2, 4, 7, 9]$$$.In the second test case, you need to move the 1 to the beginning of the array, and the 8 — to the end. Therefore, the desired sequence of operations: $$$[3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8]$$$.In the third test case, the array is already sorted.

//package codeforces.contests._1367

object FlyingSort {

  import java.io.{BufferedReader, InputStreamReader}
  import java.util.StringTokenizer

  val br = new BufferedReader(new InputStreamReader(System.in))

  def readInt: Int = br.readLine().toInt

  def readIntArrayZipped(n: Int): Array[(Int, Int)] = {
    val st = new StringTokenizer(br.readLine())
    val arr = new Array[(Int, Int)](n)
    var i = 0
    while (st.hasMoreElements) {
      arr(i) = (st.nextToken().toInt, i)
      i += 1
    }
    arr
  }

  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to readInt) yield {
          val n = readInt
          val original: Array[(Int, Int)] = readIntArrayZipped(n)
          val sorted = original.sortBy(_._1)

          @scala.annotation.tailrec
          def loop(idx: Int, acc: Int = 0, accM: Int = 0): Int = {
            if (idx >= n) acc max accM
            else {
              val (currValue, current) = sorted(idx)
              val (prevValue, prev) = sorted(idx - 1)

              def forwardCount(starting: Int, value: Int) = (starting until n).takeWhile(i => sorted(i)._1 == value).length

              def backwardCount(starting: Int, value: Int) = (starting to 0 by -1).takeWhile(i => sorted(i)._1 == value).length

              if (current > prev) loop(idx + 1, acc + 1, acc max accM)
              else {
                val rightTotalCount = forwardCount(idx, currValue)
                val leftTotalCount = backwardCount(idx - 1, prevValue)

                val leftRange = idx - leftTotalCount until idx

                val (considerOnlyBothAnswer, _, _, rRemaining) = leftRange.foldLeft((0, 0, idx, rightTotalCount)) {
                  case ((maxBoth, leftPassed, rIndex, rRemaining), l) =>
                    val removed = {
                      var r = rIndex
                      while (r < idx + rightTotalCount && sorted(r)._2 < sorted(l)._2) r += 1
                      r - rIndex
                    }

                    val rRemainingU = rRemaining - removed
                    (maxBoth max rRemainingU + leftPassed + 1, leftPassed + 1, rIndex + removed, rRemainingU)
                }

                val leftEndsHereAnswer = acc + rRemaining

                val relevantPrev = leftRange.takeWhile(i => sorted(i)._2 < current)

                loop(idx + 1, relevantPrev.length + 1, acc max accM max leftEndsHereAnswer max considerOnlyBothAnswer)
              }
            }
          }

          n - loop(1, 1, 1)
        }
      }.mkString("\n")
    }
  }
}

//package codeforces.contests._1367

object FlyingSort {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val original: Array[Int] = io.StdIn.readLine.split(" ").map(_.toInt)
      val zipped = original.zipWithIndex

      val ls = zipped.sortBy(_._1).map(_._2).toList

      @scala.annotation.tailrec
      def loop(ls: List[Int], prevS: List[Int] = Nil, acc: Int = 0, accM: Int = 0): Int = {
        ls match {
          case Nil => acc max accM
          case ::(current, tl) =>

            prevS.headOption match {
              case Some(prev) if current > prev => loop(tl, current :: prevS, acc + 1, acc max accM)
              case Some(prev) => // breakage reached, take what we get, consider both left and right view
                val prevValue = original(prev)
                val currValue = original(current)

                val rightTotalCount = ls.takeWhile(original(_) == currValue).length // total right

                val rightAnswer = {
                  val dropRightGivenPrev = ls.takeWhile(i => original(i) == currValue && i < prev).length
                  acc + rightTotalCount - dropRightGivenPrev
                }

                val relevantPrev = prevS.dropWhile(i => original(i) == prevValue && i > current)
                  .takeWhile(i => original(i) == prevValue && i < current)

                loop(tl, current :: relevantPrev, relevantPrev.length + 1, acc max accM max rightAnswer)
              case None => loop(tl, current :: Nil, 1, accM)
            }
        }
      }

      println(n - loop(ls))
    }
  }

}


Ayush and Ashish play a game on an unrooted tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$. Players make the following move in turns:   Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $$$1$$$. A tree is a connected undirected graph without cycles.There is a special node numbered $$$x$$$. The player who removes this node wins the game. Ayush moves first. Determine the winner of the game if each player plays optimally.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$ — the number of testcases. The description of the test cases follows. The first line of each testcase contains two integers $$$n$$$ and $$$x$$$ $$$(1\leq n \leq 1000, 1 \leq x \leq n)$$$ — the number of nodes in the tree and the special node respectively. Each of the next $$$n-1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.

For every test case, if Ayush wins the game, print "Ayush", otherwise print "Ashish" (without quotes).

NoteFor the $$$1$$$st test case, Ayush can only remove node $$$2$$$ or $$$3$$$, after which node $$$1$$$ becomes a leaf node and Ashish can remove it in his turn.For the $$$2$$$nd test case, Ayush can remove node $$$2$$$ in the first move itself.

//package codeforces.contests._1363

object GameOnLeaves {

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

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

      val degree: Array[Int] = {
        val a = new Array[Int](n + 1)
        (1 until n).foreach { _ =>
          val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
          a(x) += 1
          a(y) += 1
        }
        a
      }
      val first = "Ayush"
      val second = "Ashish"

      println {
        if (degree(x) <= 1) first else {
          val maxMoves = n - 2

          if (maxMoves % 2 == 0) first else second
        }
      }
    }
  }

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nx = readIntLine()
      val n = nx.head
      val x = nx.last
      val xKids = (1 until n).count(_ => {
        val l = readIntLine()
        l.head == x || l.last == x
      })

      println(if (n == 1 || xKids == 1 || n % 2 == 0) "Ayush" else "Ashish")
    }
//          println(minNum(List[Boolean](false, false, true)))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nx = readIntLine()
      val n = nx.head
      val x = nx.last
      val xKids = (1 until n).count(_ => {
        val l = readIntLine()
        l.head == x || l.last == x
      })

      println(if (xKids == 1 || n % 2 == 0) "Ayush" else "Ashish")
    }
//          println(minNum(List[Boolean](false, false, true)))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nx = readIntLine()
      val xKids = (1 until nx.head).count(_ => {
        val l = readIntLine()
        l.head == nx.last || l.last == nx.last
      })

      println(if (xKids == 1 || nx.head - xKids % 2 == 0) "Ayush" else "Ashish")
    }
//          println(minNum(List[Boolean](false, false, true)))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nx = readIntLine()
      val xKids = (1 until nx.head).count(_ => {
        val l = readIntLine()
        l.head == nx.last || l.last == nx.last
      })

      println(if (xKids == 1 || (nx.head - xKids) % 2 == 0) "Ayush" else "Ashish")
    }
//          println(minNum(List[Boolean](false, false, true)))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nx = readIntLine()
      val n = nx.head
      val x = nx.last
      val xKids = (1 until n).count(_ => {
        val l = readIntLine()
        l.head == x || l.last == x
      })

      println(if (xKids == 1 || (n - xKids) % 2 == 0) "Ayush" else "Ashish")
    }
//          println(minNum(List[Boolean](false, false, true)))
  }

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

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

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

}


Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group.

The first line contains a single integer n (2 ≤ n ≤ 60 000) — the number of integers Petya has.

Print the smallest possible absolute difference in the first line. In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.

NoteIn the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1.

import scala.io.StdIn

object P899C_DividingTheNumbers extends App {
  val (leftSum, rightSum, leftList) = (StdIn.readInt() to(1, -1)).foldLeft((0, 0, List.empty[Int])) {
    case ((leftSum, rightSum, leftList), num) =>
      if (leftSum > rightSum) (leftSum, rightSum + num, leftList)
      else (leftSum + num, rightSum, num :: leftList)
  }

  println(math.abs(leftSum - rightSum))
  println(s"${leftList.size} ${leftList.mkString(" ")}")

}


In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.

The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.

Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.

NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(n, s) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map{ _ =>
    val d = in.next().split(" ")
    (d(0).head, d(1).toInt, d(2).toInt)
  }
  val buy = data.filter(_._1 == 'B')
  val sell = data.filter(_._1 == 'S')

  val baggr = buy.groupBy(_._2).map{case(price, listd) => ('B', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.reverse.take(s)
  val saggr = sell.groupBy(_._2).map{case(price, listd) => ('S', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.take(s).reverse

  saggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
  baggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
}

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

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  val bestBuys = buys.toList.sortBy(_.price)(desc)
  val bestSells = sells.toList.sortBy(_.price)

  bestSells.take(s).sortBy(_.price)(desc) ++ bestBuys.take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
/****************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
  final def desc[A: Ordering] =  implicitly[Ordering[A]].reverse
}

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

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  val bestBuys = buys.toList.sortBy(-_.price)
  val bestSells = sells.toList.sortBy(_.price)

  bestSells.take(s).sortBy(-_.price) ++ bestBuys.take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object B extends App {
  val Array(n, s) = readLine().split(" ").map(_.toInt)

  val sell = Array.ofDim[Int](100001)
  val buy = Array.ofDim[Int](100001)

  for (_ <- 1 to n) {
    val input = readLine().split(" ")
    if (input(0) == "S") {
      sell(input(1).toInt) += input(2).toInt
    } else {
      buy(input(1).toInt) += input(2).toInt
    }
  }

  val S = sell.zipWithIndex.filterNot(_._1 == 0).take(s).reverse
  println(S.map(x => "S " + x._2 + " " + x._1).mkString("\n"))

  val B = buy.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse
  println(B.map(x => "B " + x._2 + " " + x._1).mkString("\n"))
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object OrderBook {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def main(args: Array[String]) {
     val ns = readInts()
     val n = ns(0)
     val s = ns(1)
     val orders = for {
       i <- 1 to n
       val line = readLine.split(' ')
     } yield ( (line(0),line(1).toInt),line(2).toInt)
     val orderBook = orders.groupBy(_._1).map{ case (k,v) => (k, v.map(_._2).sum)}
      val sellOrders = orderBook.filterKeys(_._1 == "S")
        .keys.toList.sortBy(_._2).take(s).reverse
     val buyOrders = orderBook.filterKeys(_._1 == "B")
        .keys.toList.sortBy(_._2).reverse.take(s)

     for (b <- sellOrders) {
       println(b._1 + " " + b._2 + " " + orderBook(b))
     }
      for (b <- buyOrders) {
       println(b._1 + " " + b._2 + " " + orderBook(b))
     }

   }

}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(n, s) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map{ _ =>
    val d = in.next().split(" ")
    (d(0).head, d(1).toInt, d(2).toInt)
  }
  val buy = data.filter(_._1 == 'B')
  val sell = data.filter(_._1 == 'S')

  val baggr = buy.groupBy(_._2).map{case(price, listd) => ('B', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.reverse.take(s)
  val saggr = sell.groupBy(_._2).map{case(price, listd) => ('S', price, listd.map(_._3).sum ) }.toList.sortBy{
    _._2
  }.take(s)

  saggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
  baggr.foreach(t => println(s"${t._1} ${t._2} ${t._3}"))
}

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

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  val bestBuys = buys.toList.sortBy(-_.price)
  val bestSells = sells.toList.sortBy(_.price)

  bestSells.sortBy(-_.price).take(s) ++ bestBuys.take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

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

object _572B extends CodeForcesApp[List[Entry]]({scanner => import scanner._
  def join(e1: Entry, e2: Entry) = e1.copy(qty = e1.qty + e2.qty)

  val (n, s) = (nextInt, nextInt)
  val entries = repeat(n) {
    Entry(next == "B", nextInt, nextInt)
  } groupBy {_.key} mapValues(_.reduce(join))

  val (buys, sells) = entries.values.partition(_.buy)

  sells.toList.sortBy(-_.price).take(s) ++ buys.toList.sortBy(-_.price).take(s)
}) {
  override def format(result: List[Entry]) = result mkString "\n"
}

case class Entry(buy: Boolean, price: Int, qty: Int) {
  val key = (buy, price)
  override def toString = s"${if (buy) 'B' else 'S'} $price $qty"
}
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  import scala.collection.mutable.{Map => Dict}
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = 1 to n map {_ => f}
  final def newCounter[A]: Dict[A, Int] = Dict.empty[A, Int] withDefaultValue 0
}

import scala.io.StdIn._

object B extends App {
  val Array(n, s) = readLine().split(" ").map(_.toInt)

  val sell = Array.ofDim[Int](100001)
  val buy = Array.ofDim[Int](100001)

  for (_ <- 1 to n) {
    val input = readLine().split(" ")
    if (input(0) == "S") {
      sell(input(1).toInt) += input(2).toInt
    } else {
      buy(input(1).toInt) += input(2).toInt
    }
  }

  val S = sell.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse
  println(S.map(x => "S " + x._2 + " " + x._1).mkString("\n"))

  val B = buy.zipWithIndex.filterNot(_._1 == 0).takeRight(s).reverse
  println(B.map(x => "B " + x._2 + " " + x._1).mkString("\n"))
}


There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll — inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) — the outer and inners volumes of the $$$i$$$-th matryoshka.

Print one integer — the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$.

NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example:   $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$;  $$$\{1, 6\}$$$;  $$$\{2, 4, 5\}$$$;  $$$\{2, 4, 6\}$$$;  $$$\{3, 4, 5\}$$$;  $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$.

//package codeforces.contest1197

object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        var minSpace = lastR._2._1 + r - lastR._1
        var minSpaceResult: Result = lastR._2._2

        for ((l, pairOccurrences) <- lSeq) {
          val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

          val space = prevSpace + l - prevR
          val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

          if (minSpace == space)
            minSpaceResult = (minSpaceResult + spaceResult) % MOD
          else if (space < minSpace) {
            minSpace = space
            minSpaceResult = spaceResult
          }
        }

        (r, (minSpace, minSpaceResult))
      }
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l)
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val (_, res) = {
      var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)

      for {
        r <- rValuesToConsider
        (space, spaceResult) = doneRValues(r)
      } {
        if (minSpace == space)
          minSpaceResult = (minSpaceResult + spaceResult) % MOD
        else if (space < minSpace) {
          minSpace = space
          minSpaceResult = spaceResult
        }
      }

      (minSpace, minSpaceResult)
    }

    println(res)
  }
}

import scala.language.implicitConversions
//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.floorEntry(r)

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.lastEntry()
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197
import java.util

import scala.collection.convert.ImplicitConversionsToScala.`map AsScala`
import scala.language.implicitConversions

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: util.TreeMap[R, util.TreeMap[L, R]] =
      new java.util.TreeMap[R, util.TreeMap[L, Int]]() // sorted By r

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap: util.TreeMap[L, R] = {
        Option(pairsMap.get(upper)).getOrElse {
          val res = new util.TreeMap[L, Int]()
          pairsMap.put(upper, res)
          res
        }
      }
      lowerMap.put(lower, lowerMap.getOrDefault(lower, 0) + 1)
    }

    val lastL: L = pairsMap.lastEntry()._2.lastKey()

    @scala.annotation.tailrec
    def loop(ls: List[(R, util.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey()
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.tailMap(lastL, false).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.floorEntry(r)

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.lastEntry()
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, mutable.TreeMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.lastKey

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }
}

//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      deconstruct(doneRValues.floorEntry(r))

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = deconstruct(doneRValues.lastEntry())
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197

import scala.language.implicitConversions

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {

  import collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, mutable.TreeMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.lastKey

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues = new java.util.TreeMap[R, (Space, Result)]
    doneRValues.put(1, (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.floorEntry(r)

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.lastEntry()
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues.get(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }

  implicit def deconstruct[K, V](arg: java.util.Map.Entry[K, V]): (K, V) =
    (arg.getKey, arg.getValue)
}

//package codeforces.contest1197

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL < l)
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }
}

//package codeforces.contest1197

import scala.language.implicitConversions

/**
  * https://codeforces.com/contest/1197/problem/E
  *
  * Process R values in sorted order, saving result for each
  * Consider rooftop R values and sum each with the minimum space
  */
object CultureCode {

  import collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.TreeMap[L, Int]] = // sorted By r
      mutable.TreeMap[R, mutable.TreeMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.TreeMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    val lastL: L = pairsMap.last._2.lastKey

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.TreeMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.lastKey
          if (lastL < l) // if this one's covered, then so are the rest
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List())

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        r -> lSeq.foldLeft[(Space, Result)](
          (lastR._2._1 + r - lastR._1, lastR._2._2)
        ) {
          case ((minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

            val space = prevSpace + l - prevR
            val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

            if (minSpace == space)
              (minSpace, (minSpaceResult + spaceResult) % MOD)
            else if (space < minSpace)
              (space, spaceResult)
            else
              (minSpace, minSpaceResult)
        }
      }
    }

    val (_, res) = {
      rValuesToConsider.foldLeft[(Space, Result)]((Int.MaxValue, 0L)) {
        case ((minSpace, minSpaceResult), r) =>
          val (space, spaceResult) = doneRValues(r)
          if (minSpace == space)
            (minSpace, (minSpaceResult + spaceResult) % MOD)
          else if (space < minSpace)
            (space, spaceResult)
          else
            (minSpace, minSpaceResult)
      }
    }

    println(res)
  }
}

//package codeforces.contest1197

object CultureCode {
  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val pairs: IndexedSeq[(R, Seq[(L, Int)])] = (1 to n)
      .map { _ =>
        val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
        (lower, upper)
      }
      .groupBy(_._2)
      .map {
        case (upper, pairValues) =>
          upper -> pairValues
            .map(_._1)
            .groupBy(identity)
            .mapValues(_.length)
            .toSeq
      }
      .toIndexedSeq
      .sortBy(_._1)

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues = collection.mutable.TreeSet[(R, Space, Result)]((1, 1, 1))

    def findLowerBound(r: Int): (R, Space, Result) =
      doneRValues.to((r, -1, -1L)).last

    for ((r, lSeq) <- pairs) {
      val lastR = doneRValues.last
      doneRValues.add(
        lSeq.foldLeft(lastR.copy(_1 = r, _2 = lastR._2 + r - lastR._1)) {
          case ((_, minSpace, minSpaceResult), (l, pairOccurrences)) =>
            val (_, space, spaceResult) = findLowerBound(l)

            if (minSpace == space)
              (r, minSpace, (minSpaceResult + spaceResult * pairOccurrences) % MOD)
            else if (minSpace < space)
              (r, minSpace, minSpaceResult)
            else
              (r, space, (spaceResult * pairOccurrences) % MOD)
        }
      )
    }

    val lastL: L = pairs(pairs.length - 1)._2.maxBy(_._1)._1

    val lastRValues = doneRValues.from((lastL + 1, -1, -1L))

    val minSpace = lastRValues.minBy(_._2)._2

    import collection.breakOut
    val res = lastRValues.collect {
      case (_, space, result) if space == minSpace => result
    }(breakOut).sum

    println(res)
  }
}

//package codeforces.contest1197

object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.TreeMap[R, mutable.HashMap[L, Int]] = // sorted By r
      collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues =
      collection.mutable.TreeMap[R, (Space, Result)](1 -> (1, 1))

    def findLowerBound(r: Int): (R, (Space, Result)) =
      doneRValues.until(r + 1).last

    for ((r, lSeq) <- pairsMap) {
      val lastR: (R, (Space, Result)) = doneRValues.last
      (doneRValues.put _).tupled {

        var minSpace = lastR._2._1 + r - lastR._1
        var minSpaceResult: Result = lastR._2._2

        for ((l, pairOccurrences) <- lSeq) {
          val (prevR, (prevSpace, prevSpaceResult)) = findLowerBound(l)

          val space = prevSpace + l - prevR
          val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

          if (minSpace == space)
            minSpaceResult = (minSpaceResult + spaceResult) % MOD
          else if (space < minSpace) {
            minSpace = space
            minSpaceResult = spaceResult
          }
        }

        (r, (minSpace, minSpaceResult))
      }
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    @scala.annotation.tailrec
    def loop(ls: List[(R, mutable.HashMap[L, Int])],
             rValues: List[Int]): List[Int] = {
      ls match {
        case Nil => rValues
        case (r, lMap) :: tail =>
          val l = lMap.maxBy(_._1)._1
          if (lastL <= l)
            r :: rValues
          else
            loop(tail, r :: rValues)
      }
    }

    val rValuesToConsider =
      loop(pairsMap.from(lastL + 1).toList.reverse, List(pairsMap.last._1))

    val (_, res) = {
      var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)

      for {
        r <- rValuesToConsider
        (space, spaceResult) = doneRValues(r)
      } {
        if (minSpace == space)
          minSpaceResult = (minSpaceResult + spaceResult) % MOD
        else if (space < minSpace) {
          minSpace = space
          minSpaceResult = spaceResult
        }
      }

      (minSpace, minSpaceResult)
    }

    println(res)
  }
}

//package codeforces.contest1197

object CultureCode {
  import scala.collection.mutable

  val MOD: Long = 1000000000 + 7

  type Space = Int
  type Result = Long
  type R = Int
  type L = Int

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

    val pairsMap: mutable.Map[R, mutable.HashMap[L, R]] = // sorted By r
      collection.mutable.TreeMap[R, collection.mutable.HashMap[L, Int]]()

    for (_ <- 1 to n) {
      val Array(upper, lower) = io.StdIn.readLine().split(" ").map(_.toInt)
      val lowerMap = pairsMap.getOrElseUpdate(upper, mutable.HashMap())
      lowerMap.update(lower, lowerMap.getOrElse(lower, 0) + 1)
    }

    implicit val ordering: Ordering[(R, Space, Result)] =
      (x: (R, Space, Result), y: (R, Space, Result)) => x._1 - y._1

    val doneRValues = collection.mutable.TreeSet[(R, Space, Result)]((1, 1, 1))

    def findLowerBound(r: Int): (R, Space, Result) =
      doneRValues.until((r + 1, -1, -1L)).last

    for ((r, lSeq) <- pairsMap) {
      val lastR = doneRValues.last
      doneRValues.add {

        var minSpace = lastR._2 + r - lastR._1
        var minSpaceResult = lastR._3

        for ((l, pairOccurrences) <- lSeq) {
          val (prevR, prevSpace, prevSpaceResult) = findLowerBound(l)

          val space = prevSpace + l - prevR
          val spaceResult = (prevSpaceResult * pairOccurrences) % MOD

          if (minSpace == space)
            minSpaceResult = (minSpaceResult + spaceResult) % MOD
          else if (space < minSpace) {
            minSpace = space
            minSpaceResult = spaceResult
          }
        }

        (r, minSpace, minSpaceResult)
      }
    }

    val lastL: L = pairsMap.last._2.maxBy(_._1)._1

    val lastRValues = doneRValues.from((lastL + 1, -1, -1L))

    val (_, res) = {
      var (minSpace, minSpaceResult) = (Int.MaxValue, 0L)

      for ((_, space, spaceResult) <- lastRValues) {
        if (minSpace == space)
          minSpaceResult = (minSpaceResult + spaceResult) % MOD
        else if (space < minSpace) {
          minSpace = space
          minSpaceResult = spaceResult
        }
      }

      (minSpace, minSpaceResult)
    }

    println(res)
  }
}


You have got a shelf and want to put some books on it.You are given $$$q$$$ queries of three types:  L $$$id$$$ — put a book having index $$$id$$$ on the shelf to the left from the leftmost existing book;  R $$$id$$$ — put a book having index $$$id$$$ on the shelf to the right from the rightmost existing book;  ? $$$id$$$ — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $$$id$$$ will be leftmost or rightmost. You can assume that the first book you will put can have any position (it does not matter) and queries of type $$$3$$$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $$$id$$$s don't repeat in queries of first two types.Your problem is to answer all the queries of type $$$3$$$ in order they appear in the input.Note that after answering the query of type $$$3$$$ all the books remain on the shelf and the relative order of books does not change.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th line contains the $$$i$$$-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type $$$3$$$, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before). It is guaranteed that there is at least one query of type $$$3$$$ in the input. In each query the constraint $$$1 \le id \le 2 \cdot 10^5$$$ is met.

Print answers to queries of the type $$$3$$$ in order they appear in the input.

NoteLet's take a look at the first example and let's consider queries:   The shelf will look like $$$[1]$$$;  The shelf will look like $$$[1, 2]$$$;  The shelf will look like $$$[1, 2, 3]$$$;  The shelf looks like $$$[1, \textbf{2}, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[4, 1, 2, 3]$$$;  The shelf looks like $$$[4, \textbf{1}, 2, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[5, 4, 1, 2, 3]$$$;  The shelf looks like $$$[5, 4, \textbf{1}, 2, 3]$$$ so the answer is $$$2$$$. Let's take a look at the second example and let's consider queries:   The shelf will look like $$$[100]$$$;  The shelf will look like $$$[100, 100000]$$$;  The shelf will look like $$$[100, 100000, 123]$$$;  The shelf will look like $$$[101, 100, 100000, 123]$$$;  The shelf looks like $$$[101, 100, 100000, \textbf{123}]$$$ so the answer is $$$0$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123]$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115]$$$;  The shelf looks like $$$[10, 101, \textbf{100}, 100000, 123, 115]$$$ so the answer is $$$2$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115, 110]$$$;  The shelf looks like $$$[10, 101, 100, 100000, 123, \textbf{115}, 110]$$$ so the answer is $$$1$$$.

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

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

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

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

  def solve(): Unit = {
    import java.util.concurrent.LinkedBlockingDeque
    val Q = ni()
    val q = new LinkedBlockingDeque[Int]()
    val qs = ArrayBuffer[(Int, (Int, Int))]()
    val ids = mutable.Map[Int, Int]()
    var idGen = 0
    var L, R = 0
    rep(Q) { _ =>
      val command = nc()
      val id_v = ni()
      val id = ids.getOrElseUpdate(id_v, {
        val id = idGen
        idGen += 1
        id
      })
      command match {
        case 'L' =>
          L += 1
          q.addFirst(id)

        case 'R' =>
          R += 1
          q.addLast(id)

        case '?' =>
          qs += ((id, (L, R)))
          L = 0
          R = 0
      }
    }

    val N = q.size()
    val as = Array.ofDim[Int](N)
    var i = 0
    while(!q.isEmpty){
      as(i) = q.poll()
      i += 1
    }
    val rev = Array.ofDim[Int](N)
    rep(as.length) { i =>
      rev(as(i)) = i
    }

    val ans = ArrayBuffer[Int]()
    qs.reverse foreach { case (id, (l, r)) =>
      ans += min(rev(id) - L, N - rev(id) - 1 - R)
      L += l
      R += r
    }

    ans.reverse foreach out.println
  }

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


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation.

For each test case print the lexicographically smallest permutation you can obtain.

NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$.

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.immutable.TreeSet
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 optionIndex = a.zipWithIndex.find {
      case (a, index) => a != index + 1
    }
    val answer = optionIndex match {
      case None => a
      case Some((_, index)) =>
        val l = index
        val r = a.indexOf(index + 1)
        a.slice(0, l) ++ a.slice(l, r + 1).reverse ++ a.slice(r + 1, a.length)
    }
    println(answer.mkString(" "))
  }

  //=====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 isEmpty() = multiSet.isEmpty
    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.collection.mutable.ArrayBuffer
import scala.io.Source

object Main extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val res = new ArrayBuffer[String]()
  for (i <- 0 until t) {
    val n = input.next().toInt
    val p = input.next().split(" ").map(_.toInt).toList

    val plr = p.zipWithIndex.map(x => (x._1, x._2 + 1)).filter(x => x._1 != x._2)
    if (plr.isEmpty) res.append(p.mkString(" "))
    else {
      val minInd = plr.min._2 - 1
      val startingInd = plr.head._2 - 1

      val start = p.slice(0, startingInd)
      val md = p.slice(startingInd, minInd + 1).reverse
      val end = if (minInd + 1 == n) Nil else p.slice(minInd + 1, n)
      res.append((start ++ md ++ end).mkString(" "))
    }
  }
  res.foreach(println)
}


One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.

The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.

In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.

import java.util._
import java.io._
import java.math._
import java.awt.Point
import java.awt.geom._
import java.lang.System._
import java.lang.Math._

object A {
  var n = -1
  var r: Array[Int] = null
  var l: Array[Int] = null

  def solve(){
    var cl = 0
    var cr = 0
    for(i <- 0 until n) if(l(i) == 1) cl = cl + 1;
    for(i <- 0 until n) if(r(i) == 1) cr = cr + 1;
    println(min(n-cl, cl)+min(n-cr, cr))
  }
  def main(args: Array[String]){
    val sc = new Scanner(in)
    n = sc.nextInt
    l = new Array(n)
    r = new Array(n)
    for(i <- 0 until n){
      l(i) = sc.nextInt
      r(i) = sc.nextInt
    }
    solve
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt

  val data = (1 to n).map{ _ => in.next()}
  val left = data.count(_.head == '1')
  val right = data.count(_.last == '1')

  println(Math.min(left, n - left) + Math.min(right, n - right))
}

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

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

  val N = sc.nextInt
  val ds = Array.fill(N, 2)(sc.nextInt)

  val answer: Int = {
    for (i <- 0 until 2) yield {
      val closed = (0 until N).map(ds(_)(i)).sum
      closed min (N - closed)
    }
  }.sum

  out.println(answer)
  out.close
}

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

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

  val f = Array[Int => Int](x => x, 1-, _ => 0, _ => 1)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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

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

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

  val f = Array[Int => Int](x => x, 1-, 0*, 1|)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_^_))).sum
  }.min

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

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

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

  val f = Array[Int => Int](x => x, 1-, 0*, 1|)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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

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

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

  val f = Array((x: Int) => x, (x: Int) => 1 - x, (x: Int) => 0, (x: Int) => 1)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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

import java.util.Scanner
import java.math._

object B extends App
{
	val cin=new Scanner(System.in);
	val n=cin.nextInt()
	var l,r=0
	for(i <- 1 to n)
	{
		val a,b=cin.nextInt()
		l+=a
		r+=b
	}
	println(math.min(l,n-l)+math.min(r,n-r))
}

import collection.mutable.ArrayBuffer

object test2 extends App {
    val n=readLine.toInt
    var left=0
    var right=0
    0 until n foreach{i=>
    	val Array(l,r)=readLine.split(" ").map(_.toInt)
    	if(l==0) left+=1
    	if(r==0) right+=1
    }

    if(left>n/2) left=n-left
    if(right>n/2) right=n-right

    println(left+right)
}

object Main {
  def readDoor() = {
    val a = readLine().split(" ").map(_.toInt)
    (a(0), a(1))
  }

  def main(args: Array[String]) {
    val n = readInt
    val a = (1 to n).map(_ => readDoor())
    val left = a.map(_._1).sum
    val right = a.map(_._2).sum
    println(left.min(n - left) + right.min(n - right))
  }
}

import java.util._
import java.io._
import java.math._
import java.awt.Point
import java.awt.geom._
import java.lang.System._
import java.lang.Math._

object A {
  def main(args: Array[String]){
    val sc = new Scanner(in)
    n = sc.nextInt
    solve
  }

  var n = -1
  def solve(){
    println(-1)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt

  val data = (1 to n).foldLeft((0, 0)){
    case ((left, right), _) =>
      val str = in.next()
      var newLeft = left
      var newRight = right
      if (str.head == '0')
        newLeft += 1
      else
        newRight += 1
      if (str.last == '0')
        newRight += 1
      else
        newLeft += 1
      (newLeft, newRight)
  }
  println(Math.min(data._1, data._2))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt

  val data = (1 to n).map{ _ => in.next()}
  val left = data.count(_.head == '1')
  val right = data.count(_.head == '1')

  println(Math.min(left, data.size - left) + Math.min(right, data.size - right))
}

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

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

  val f = Array((x: Int) => x, (x: Int) => 1 - x)
  val a = for(_ <- 1 to readInt) yield readInts
  def ans = f.map { func =>
    val need = Array(0, 1).map(func)
    a.flatMap(x => (x zip need).map(_.productIterator.map(_.asInstanceOf[Int]).reduce(_ - _).abs)).sum
  }.min

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


IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.

The only line of the input contains three integers l3, l4, l5 (1 ≤ l3, l4, l5 ≤ 1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.

Output one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10 - 9.

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

object Main {

  def sqr(x: Long) = x * x

  def powmod(x: Long, n: Long, p: Long): Long = {
    if (n == 1) x
    else if (n % 2 == 1) (powmod(x, n - 1, p) * x) % p
    else sqr(powmod(x, n / 2, p)) % p
  }

  def C(n: Int, k: Int) = {
    var res = BigInt(1)
    for (i <- n - k + 1 to n) {
      res = res * i
    }
    for (i <- 1 to k.toInt) {
      res = res / i
    }
    res
  }

  def fact(n: Int) = {
    var res = BigInt(1)
    for (i <- 1 to n) {
      res = res * i
    }
    res
  }

  def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a % b)

  def lcm(a: Long, b: Long) = a / gcd(a, b) * b

  def foo(n: Int, a: Double) = {
    var sx = 0.0
    var sy = 0.0
    var curx = 0.0
    var cury = 0.0
    for (i <- 0 until n) {
      sx = sx + curx
      sy = sy + cury
      curx = curx + Math.cos(Math.PI * 2 / n * i) * a
      cury = cury + Math.sin(Math.PI * 2 / n * i) * a
    }
    sx = sx / n
    sy = sy / n
    val d = Math.sqrt(sx * sx + sy * sy)
    val h = Math.sqrt(a * a - d * d)
    val area = n * a * a / (4 * Math.tan(Math.PI / n))
    1.0 / 3 * h * area
  }

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

    val Array(a, b, c) = in.nextLine().split(' ').map(_.toDouble)

    val res = foo(3, a) + foo(4, b) + foo(5, c)

    println(res)
  }
}