Amugae has a hotel consisting of $$$10$$$ rooms. The rooms are numbered from $$$0$$$ to $$$9$$$ from left to right.The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.

The first line consists of an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of events in Amugae's memory. The second line consists of a string of length $$$n$$$ describing the events in chronological order. Each character represents:    'L': A customer arrives from the left entrance.  'R': A customer arrives from the right entrance.  '0', '1', ..., '9': The customer in room $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$ respectively) leaves.  It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room $$$x$$$ when $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$) is given. Also, all the rooms are initially empty.

In the only line, output the hotel room's assignment status, from room $$$0$$$ to room $$$9$$$. Represent an empty room as '0', and an occupied room as '1', without spaces.

NoteIn the first example, hotel room's assignment status after each action is as follows.   First of all, all rooms are empty. Assignment status is 0000000000.  L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000.  L: one more customer from the left entrance. Assignment status is 1100000000.  R: one more customer from the right entrance. Assignment status is 1100000001.  L: one more customer from the left entrance. Assignment status is 1110000001.  1: the customer in room $$$1$$$ leaves. Assignment status is 1010000001.  R: one more customer from the right entrance. Assignment status is 1010000011.  L: one more customer from the left entrance. Assignment status is 1110000011.  1: the customer in room $$$1$$$ leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011.In the second example, hotel room's assignment status after each action is as follows.   L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000.  0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000.  L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again.  0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000.  L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000.  L: one more customer from the left entrance. Assignment status is 1100000000.  R: one more customer from the right entrance. Assignment status is 1100000001.  R: one more customer from the right entrance. Assignment status is 1100000011.  9: the customer in room $$$9$$$ leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010.

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

object Hotelier extends App {

  StdIn.readLine()

  val n = 10
  val events = StdIn.readLine()

  val rooms = mutable.Buffer[Int]()
  rooms ++= Seq.fill(n)(0)

  events.foreach {
    case 'R' => rooms.update(rooms.lastIndexOf(0), 1)
    case 'L' => rooms.update(rooms.indexOf(0), 1)
    case num => rooms(Integer.parseInt(num.toString)) = 0
  }

  println(rooms.mkString(""))
}

object A {

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

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

  val Array(n) = readInts(1)
  val s = readLine
  val rooms = Array.fill(10)(0)

  for (c <- s) {
    c match {
      case 'L' =>
        var i = 0
        while (rooms(i) == 1) i += 1
        rooms(i) = 1
      case 'R' =>
        var i = 9
        while (rooms(i) == 1) i -= 1
        rooms(i) = 1
      case _ =>
        rooms(c - '0') = 0
    }
  }

  println(rooms.mkString)

  Console.flush
}
}

object A extends App {

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

  val Array(n) = readInts(1)
  val s = readLine
  val rooms = Array.fill(10)(0)

  for (c <- s) {
    c match {
      case 'L' =>
        var i = 0
        while (rooms(i) == 1) i += 1
        rooms(i) = 1
      case 'R' =>
        var i = 9
        while (rooms(i) == 1) i -= 1
        rooms(i) = 1
      case _ =>
        rooms(c - '0') = 0
    }
  }

  println(rooms.mkString)

  Console.flush
}

import scala.collection.convert.ImplicitConversionsToScala._

object AMega extends App {

  val MaxRoom = 9
  val n = readLine.toInt
  val rooms = new java.util.TreeMap[Integer, Integer]
  if (MaxRoom == 999999) rooms.put(0, MaxRoom)

  val readCommand: Unit => String = if (MaxRoom == 9) { val l = readLine.sliding(1); _ => l.next } else { _ => readLine }

  for (_ <- 1 to n) {
    readCommand() match {
      case "L" =>
        val goTo = rooms.getOrDefault(0, -1) + 1
        val nextKey = goTo + 1
        val right: Integer = if (rooms.containsKey(nextKey)) rooms.remove(nextKey) else goTo
        rooms.put(0, right)
      case "R" =>
        if (rooms.isEmpty) rooms.put(MaxRoom, MaxRoom)
        else {
          val lastKey = rooms.lastKey
          val goTo = if (rooms.get(lastKey) == MaxRoom) {
            rooms.remove(lastKey)
            lastKey - 1
          } else MaxRoom
          val prevKey = rooms.floorKey(goTo)
          val left: Integer = if (prevKey != null && rooms.get(prevKey) == goTo - 1) prevKey else goTo
          rooms.put(left, MaxRoom)
        }
      case s =>
        val pos = s.toInt
        val left = rooms.floorKey(pos)
        val right = rooms.remove(left)
        if (left < pos) rooms.put(left, pos - 1)
        if (right > pos) rooms.put(pos + 1, right)
    }
  }

  val result = Array.fill[Byte](MaxRoom + 1)(0)

  for (entry <- rooms.entrySet()) {
    for (i <- entry.getKey.toInt to entry.getValue) result(i) = 1
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(result.mkString)
  Console.flush
}

object A extends App {

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

  val Array(n) = readInts(1)
  val s = readLine
  val rooms = Array.fill(10)(0)

  for (c <- s) {
    c match {
      case 'L' =>
        var i = 0
        while (rooms(i) == 1) i += 1
        rooms(i) = 1
      case 'R' =>
        var i = 9
        while (rooms(i) == 1) i -= 1
        rooms(i) = 1
      case _ =>
        rooms(c - '0') = 0
    }
  }

  println(rooms.mkString)

  Console.flush
}

object A {

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

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

  val Array(n) = readInts(1)
  val s = readLine
  val rooms = Array.fill(10)(0)

  for (c <- s) {
    c match {
      case 'L' =>
        var i = 0
        while (rooms(i) == 1) i += 1
        rooms(i) = 1
      case 'R' =>
        var i = 9
        while (rooms(i) == 1) i -= 1
        rooms(i) = 1
      case _ =>
        rooms(c - '0') = 0
    }
  }

  println(rooms.mkString)

  Console.flush
}

import java.io.BufferedReader

object Main {

  type RoomStatus = Boolean
  type Rooms = java.util.BitSet

  val FREE = false
  val OCCUPIED = true
  val MAX = 10

  def roomsToString(rooms: Rooms): String = {
    (for (i <- Range(0, MAX)) yield {
      if (rooms.get(i) == FREE) '0' else '1'
    }).mkString
  }

  def result(input: Stream[Char]): Rooms = {
    val rooms: Rooms = new Rooms(MAX)

    input.foreach {

      case 'L' =>
        val freeIndex = rooms.nextClearBit(0)
        rooms.set(freeIndex, OCCUPIED)
        rooms
      case 'R' =>
        val freeIndex = rooms.previousClearBit(MAX - 1)
        rooms.set(freeIndex, OCCUPIED)
        rooms
      case room =>
        rooms.set(room - '0', FREE)
        rooms

    }

    rooms
  }

  def main(args: Array[String]) = {
    val input: BufferedReader = Console.in
    val length = input.readLine().toInt
    if (length != 0) {
      var read = 0
      val buf = new Array[Char](1)
      val ops = Stream
        .continually {
          read += 1
          input.read(buf)
        }
        .takeWhile(bufRead => bufRead > 0 && read <= length)
        .map {
          _ => buf(0)
        }

      Console.out.write(roomsToString(result(ops)).getBytes)
    }

  }
}

import java.io.BufferedReader

object Main2 {

  sealed trait Input

  case object L extends Input

  case object R extends Input

  case class Leave(roomNo: Byte) extends Input

  type RoomStatus = Boolean
  type Rooms = Vector[RoomStatus]

  val FREE = false
  val OCCUPIED = true
  val ALL_EMPTY: Rooms = Vector.fill(10)(FREE)

  def handle(rooms: Rooms, input: Input): Rooms = input match {
    case L =>
      val freeIndex = rooms.indexOf(FREE)
      rooms.updated(freeIndex, OCCUPIED)
    case R =>
      val freeIndex = rooms.lastIndexOf(FREE)
      rooms.updated(freeIndex, OCCUPIED)
    case Leave(roomNo) =>
      rooms.updated(roomNo, FREE)
  }

  def roomsToString(rooms: Rooms): String = {
    rooms.map {
      case FREE => '0'
      case OCCUPIED => '1'
    }.mkString
  }

  def result(input: Stream[Char]): Rooms = {
    input.map {
      case 'L' => L
      case 'R' => R
      case c if c >= '0' && c <= '9' => Leave(Seq(c).mkString.toByte)
    }.foldLeft(ALL_EMPTY)(handle)
  }

  def main(args: Array[String]) = {
    val input: BufferedReader = Console.in
    val length = input.readLine().toInt
    if (length != 0) {
      var read = 0
      val buf = new Array[Char](1)
      val ops = Stream
        .continually {
          read += 1
          input.read(buf)
        }
        .takeWhile(bufRead => bufRead > 0 && read <= length)
        .map {
          _ => buf(0)
        }

      Console.out.write(roomsToString(result(ops)).getBytes)
    }

  }
}

/**
  * Created by lilisun on 8/12/19.
  */
import scala.io.StdIn.readLine
object cf578 {

  def PA():Unit = {
    val n = readLine().toInt
    val line = readLine()
    val room = Array.fill(10)(0)
    line foreach {
      case 'L' => (0 until 10).dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case 'R' => (0 until 10).reverse.dropWhile(i => room(i) == 1).headOption match {
        case None => {}
        case Some(i) => room(i) = 1
      }
      case ch => room(ch - '0') = 0
    }
    println(room.toList.mkString)
  }
  def main(args: Array[String]): Unit = {
    PA()
  }
}

import scala.io.StdIn._

object A_1200 extends App {
  val n = readInt()
  val A = readLine()
  var S = Array.ofDim[Boolean](10)

  A.foreach { x =>
    if (x == 'L') {
      var left = 0
      while (S(left)) left += 1
      S(left) = true
      left += 1
    } else if (x == 'R') {
      var right = 9
      while (S(right)) right -= 1
      S(right) = true
      right -= 1
    } else {
      val xx = ("" + x).toInt
      S(xx) = false
    }
  }

  println(
    S.map(x => if (x) 1 else 0).mkString
  )
}


Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if t = "nastya" and a = [4, 1, 5, 3, 2, 6] then removals make the following sequence of words "nastya"  "nastya"  "nastya"  "nastya"  "nastya"  "nastya"  "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.

The first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1 ≤ |p| < |t| ≤ 200 000). It is guaranteed that the word p can be obtained by removing the letters from word t. Next line contains a permutation a1, a2, ..., a|t| of letter indices that specifies the order in which Nastya removes letters of t (1 ≤ ai ≤ |t|, all ai are distinct).

Print a single integer number, the maximum number of letters that Nastya can remove.

NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba"  "ababcba"  "ababcba"  "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters.

object CF extends App{
import scala.io.StdIn.readLine
val t = readLine().toArray
val p = readLine().toArray
val a = readLine().split(" ").map(_.toInt - 1)

val rank = {
    val rank = Array.fill(a.length)(0)
    for( i <- 0 until a.length)
        rank(a(i)) = i
    rank
}

val newt: Array[Char] = Array.fill(t.length)(0)

def getNewt(n: Int) = {
    for(i <- 0 until t.length){
        if(rank(i) > n) newt(i) = t(i)
        else newt(i) = 0
    }
}

def isComposable(i:Int, j: Int): Boolean = {
    if(i >= t.length) return false
    if(j >= p.length) return true
    if(newt.length - i < p.length - j) return false
    if(newt(i) == p(j) && j==p.length-1) return true
    if(newt(i) == p(j)) return isComposable(i+1, j+1)
    else return isComposable(i+1, j)
}

var lo = 0
var hi = t.length - p.length + 1
var mid = (hi+lo) / 2
var end = false

while(lo < hi){
    getNewt(mid)
    //println(f"$hi $lo $mid " + newt.mkString(""))
    if(isComposable(0, 0)) lo = mid+1
    else hi = mid
    mid = (hi+lo) / 2
}

println(hi)
}

import scala.io.StdIn.readLine
object CF extends App{
val t = readLine().toArray
val p = readLine().toArray
val a = readLine().split(" ").map(_.toInt - 1)

val rank = Array.fill(a.length)(0)
for( i <- 0 until a.length)
    rank(a(i)) = i

def isComposable(n: Int): Boolean = {
    var j = 0
    for(i <- 0 until t.length){
        if(rank(i) > n) {
            if(t.length - i < p.length - j) return false
            if(t(i) == p(j)) j+=1
            if(j==p.length) return true
        }
    }
    return false
}

var lo = 0
var hi = t.length - p.length + 1
var mid = (hi+lo) / 2

while(lo < hi){
    //println(f"$hi $lo $mid " + newt.mkString(""))
    if(isComposable(mid)) lo = mid+1
    else hi = mid
    mid = (hi+lo) / 2
}

println(hi)
}

object CF extends App{
import scala.io.StdIn.readLine
val t = readLine().toArray
val p = readLine().toArray
val a = readLine().split(" ").map(_.toInt - 1)

val rank = {
    val rank = Array.fill(a.length)(0)
    for( i <- 0 until a.length)
        rank(a(i)) = i
    rank
}

val newt: Array[Char] = Array.fill(t.length)(0)

def getNewt(n: Int) = {
    for(i <- 0 until t.length){
        if(rank(i) > n) newt(i) = t(i)
        else newt(i) = 0
    }
}

def isComposable(): Boolean = {
    var j = 0
    for(i <- 0 until newt.length){
        if(newt.length - i < p.length - j) return false
        if(newt(i) == p(j)) j+=1
        if(j==p.length) return true
    }
    return false
}

var lo = 0
var hi = t.length - p.length + 1
var mid = (hi+lo) / 2

while(lo < hi){
    getNewt(mid)
    //println(f"$hi $lo $mid " + newt.mkString(""))
    if(isComposable()) lo = mid+1
    else hi = mid
    mid = (hi+lo) / 2
}

println(hi)
}

import scala.io.StdIn.readLine
object CF extends App{
val t = readLine().toArray
val p = readLine().toArray
val a = readLine().split(" ").map(_.toInt - 1)

val rank = Array.fill(a.length)(0)
for( i <- 0 until a.length)
    rank(a(i)) = i

val newt: Array[Char] = Array.fill(t.length)(0)

def getNewt(n: Int) = {
    for(i <- 0 until t.length){
        if(rank(i) > n) newt(i) = t(i)
        else newt(i) = 0
    }
}

def isComposable(): Boolean = {
    var j = 0
    for(i <- 0 until newt.length){
        if(newt.length - i < p.length - j) return false
        if(newt(i) == p(j)) j+=1
        if(j==p.length) return true
    }
    return false
}

var lo = 0
var hi = t.length - p.length + 1
var mid = (hi+lo) / 2

while(lo < hi){
    getNewt(mid)
    //println(f"$hi $lo $mid " + newt.mkString(""))
    if(isComposable()) lo = mid+1
    else hi = mid
    mid = (hi+lo) / 2
}

println(hi)
}

//package solutions

import java.io.PrintWriter
import java.util.Scanner

/**
  * @author traff
  */

object SolTaskD extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def filter(s: String, a: Array[Int], n: Int): String = {
    var ss = new StringBuffer(s)
    for (i <- 0 until n) {
      ss.setCharAt(a(i)-1, 0)
    }

    ss.toString.filter(_ != 0)
  }

  def check(s1: String, s2: String): Boolean = {
    var i1 = 0
    var i2 = 0

    while (i1 < s1.length && i2 < s2.length) {
      if (s1(i1) == s2(i2)) {
        i1 += 1
        i2 += 1
      } else {
        i1 += 1
      }
    }

    i2 == s2.length
  }

  def find(l: Int, r: Int, s1: String, s2: String, a: Array[Int]): Int = {
    if (l >= r) {
      l
    } else if (check(filter(s1, a, r), s2)) {
      r
    }
    else {

      var mid = l + (r - l) / 2
      if (mid == l) {
        mid = l + 1
      }

      if (check(filter(s1, a, mid), s2)) {
        find(mid, r, s1, s2, a)
      } else {
        find(l, mid - 1, s1, s2, a)
      }
    }
  }

  def run(s: Scanner, out: PrintWriter): Unit = {
    val p = s.nextLine()
    val t = s.nextLine()

    val a = s.nextLine().split(" ").map(_.toInt)

    out.println(find(0, a.length, p, t, a))
  }

}

object CF extends App{
import scala.io.StdIn.readLine
val t = readLine().toArray
val p = readLine().toArray
val a = readLine().split(" ").map(_.toInt - 1)

val rank = {
    val rank = Array.fill(a.length)(0)
    for( i <- 0 until a.length)
        rank(a(i)) = i
    rank
}

val newt: Array[Char] = Array.fill(t.length)(0)

def getNewt(n: Int) = {
    for(i <- 0 until t.length){
        if(rank(i) > n) newt(i) = t(i)
        else newt(i) = 0
    }
}

def isComposable(i:Int, j: Int): Boolean = {
    if(i >= t.length) return false
    if(j >= p.length) return true
    if(newt.length - i < p.length - j) return false
    if(newt(i) == p(j) && j==p.length-1) return true
    if(newt(i) == p(j)) return isComposable(i+1, j+1)
    else return isComposable(i+1, j)
}

var lo = 0
var hi = t.length - p.length + 1
var mid = (hi+lo+1) / 2
var end = false

while(lo < hi){
    getNewt(mid)
    //println(f"$hi $lo $mid " + newt.mkString(""))
    if(isComposable(0, 0)) lo = mid
    else hi = mid-1
    mid = (hi+lo+1) / 2
}

println(mid+1)
}


Maksim has $$$n$$$ objects and $$$m$$$ boxes, each box has size exactly $$$k$$$. Objects are numbered from $$$1$$$ to $$$n$$$ in order from left to right, the size of the $$$i$$$-th object is $$$a_i$$$.Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the $$$i$$$-th object fits in the current box (the remaining size of the box is greater than or equal to $$$a_i$$$), he puts it in the box, and the remaining size of the box decreases by $$$a_i$$$. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).

The first line of the input contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^9$$$) — the number of objects, the number of boxes and the size of each box. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the size of the $$$i$$$-th object.

Print the maximum number of objects Maksim can pack using the algorithm described in the problem statement.

NoteIn the first example Maksim can pack only $$$4$$$ objects. Firstly, he tries to pack all the $$$5$$$ objects. Distribution of objects will be $$$[5], [2, 1]$$$. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be $$$[2, 1], [4, 2]$$$. So the answer is $$$4$$$.In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is $$$[4]$$$), but he can pack the last object ($$$[1]$$$).In the third example Maksim can pack all the objects he has. The distribution will be $$$[1, 2], [3], [1, 1]$$$.

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

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

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

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

  def solve(): Unit = {
    val N, M, K = ni()
    val A = na(N).reverse

    def count: Int = {
      var cnt = 0
      var box = M
      var i = 0
      while(box > 0 && i < N) {
        if (cnt + A(i) > K) {
          cnt = A(i)
          box -= 1
        } else {
          cnt += A(i)
        }
        if (box == 0) return i
        i += 1
      }
      i
    }

    out.println(count)
  }

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


Yelisey has an array $$$a$$$ of $$$n$$$ integers.If $$$a$$$ has length strictly greater than $$$1$$$, then Yelisei can apply an operation called minimum extraction to it:   First, Yelisei finds the minimal number $$$m$$$ in the array. If there are several identical minima, Yelisey can choose any of them.  Then the selected minimal element is removed from the array. After that, $$$m$$$ is subtracted from each remaining element. Thus, after each operation, the length of the array is reduced by $$$1$$$.For example, if $$$a = [1, 6, -4, -2, -4]$$$, then the minimum element in it is $$$a_3 = -4$$$, which means that after this operation the array will be equal to $$$a=[1 {- (-4)}, 6 {- (-4)}, -2 {- (-4)}, -4 {- (-4)}] = [5, 10, 2, 0]$$$.Since Yelisey likes big numbers, he wants the numbers in the array $$$a$$$ to be as big as possible.Formally speaking, he wants to make the minimum of the numbers in array $$$a$$$ to be maximal possible (i.e. he want to maximize a minimum). To do this, Yelisey can apply the minimum extraction operation to the array as many times as he wants (possibly, zero). Note that the operation cannot be applied to an array of length $$$1$$$.Help him find what maximal value can the minimal element of the array have after applying several (possibly, zero) minimum extraction operations to the array.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. In the description of each test case, the first line contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the original length of the array $$$a$$$. The second line of the description lists $$$n$$$ space-separated integers $$$a_i$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each of them containing the answer to the corresponding test case. The answer to the test case is a single integer — the maximal possible minimum in $$$a$$$, which can be obtained by several applications of the described operation to it.

NoteIn the first example test case, the original length of the array $$$n = 1$$$. Therefore minimum extraction cannot be applied to it. Thus, the array remains unchanged and the answer is $$$a_1 = 10$$$.In the second set of input data, the array will always consist only of zeros.In the third set, the array will be changing as follows: $$$[\color{blue}{-1}, 2, 0] \to [3, \color{blue}{1}] \to [\color{blue}{2}]$$$. The minimum elements are highlighted with $$$\color{blue}{\text{blue}}$$$. The maximal one is $$$2$$$.In the fourth set, the array will be modified as $$$[2, 10, \color{blue}{1}, 7] \to [\color{blue}{1}, 9, 6] \to [8, \color{blue}{5}] \to [\color{blue}{3}]$$$. Similarly, the maximum of the minimum elements is $$$5$$$.

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

  override def solve(io: IO) = io.repeat {
    val arr = io.read[Vector[Int]].sorted

    var ans = Int.MinValue
    var delta = 0

    for {a <- arr} {
      val actual = a + delta
      ans = ans max actual
      delta -= actual
    }

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

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

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

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

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

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

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

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

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

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

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

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

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

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

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

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

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

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

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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


In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.

First line of input contains single integer number n (2 ≤ n ≤ 100 000)  — number of inflorescences. Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.

Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.

NoteIn first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it.

import scala.collection.mutable

object A extends App {

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

  val Array(n) = readInts(1)
  val ps = readInts(n - 1)

  val childBuilders = Array.fill(n + 1){ new mutable.ArrayBuilder.ofInt }
  for (i <- ps.indices) {
    childBuilders(ps(i)) += i + 2
  }

  val children = childBuilders.map(_.result())
  val counts = Array.fill(n + 1){ 0 }

  def dfs(u: Int, depth: Int): Unit = {
    var i = 0
    counts(depth) += 1
    while (i < children(u).length) {
      dfs(children(u)(i), depth + 1)
      i += 1
    }
  }

  dfs(1, 0)

  println(counts.map(_ % 2).sum)

  Console.flush
}


You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something.More precisely, you want to spam the emote triangle of size $$$k$$$. It consists of $$$2k-1$$$ messages. The first message consists of one emote, the second one — of two emotes, ..., the $$$k$$$-th one — of $$$k$$$ emotes, the $$$k+1$$$-th one — of $$$k-1$$$ emotes, ..., and the last one — of one emote.For example, the emote triangle for $$$k=3$$$ consists of $$$5$$$ messages:  Of course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least $$$x$$$ emotes in succession (you can assume you are the only user in the chat). Now you are interested — how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all $$$2k-1$$$ messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains integers $$$k$$$ and $$$x$$$ ($$$1 \le k \le 10^9; 1 \le x \le 10^{18}$$$).

For each test case, print the number of messages you will write before getting banned for the corresponding values $$$k$$$ and $$$x$$$.

NoteLet's analyze the test cases of the example.  In the first test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$3$$$ emotes respectively, and since $$$1 + 2 + 3 \ge 6$$$, you get banned after that.  In the second test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$4$$$ emotes respectively, and since $$$1 + 2 + 3 + 4 \ge 7$$$, you get banned after that.  In the third test case, you write one message containing exactly $$$1$$$ emote. It doesn't get you banned, since $$$1 < 2$$$, but you have already finished posting your emote triangle. So you wrote one message successfully.  In the fourth test case, you write four messages containing $$$1$$$, $$$2$$$, $$$3$$$ and $$$2$$$ emotes respectively, and since $$$1 + 2 + 3 + 2 \ge 7$$$, you get banned after that.  In the fifth test case, you write three messages containing $$$1$$$, $$$2$$$ and $$$1$$$ emote respectively. It doesn't get you banned, since $$$1 + 2 + 1 < 5$$$, but you have already finished posting your emote triangle. So you wrote three messages successfully.  In the sixth test case, since $$$x = 1$$$, you get banned as soon as you send your first message.  The seventh test case is too large to analyze, so we'll skip it.

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    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()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 10010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readLong()
        val m = readLong()
        def cnt (inp: Long): Long = {
            var k = inp
            var ans = 0L
            if (k <= n) {
                ans = k * k
                ans -= k
                ans /= 2
                ans += k
                return ans
            } else {
                ans = n * n
                k -= n
                var tmp = (n-k-1L)*(n-k-1L)
                tmp -= (n-k-1L)
                tmp /= 2
                tmp += (n-k-1L)
                ans -= tmp
                return ans
            }
        }
        def bs(st: Long, en: Long): Long = {
            if (en - st <= 1L) {
                if (cnt(st) >= m)
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2
            if (cnt(mid) < m)
                return bs(mid, en)
            else
                return bs(st, mid)
        }
        writer.println(bs(1L, 2L*n-1L))
    }
    writer.flush()
}


You've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n.You need to permute the array elements so that value  became minimal possible. In particular, it is allowed not to change order of elements at all.

The first line contains two integers n, k (2 ≤ n ≤ 3·105, 1 ≤ k ≤ min(5000, n - 1)).  The second line contains n integers A[1], A[2], ..., A[n] ( - 109 ≤ A[i] ≤ 109), separate by spaces — elements of the array A.

Print the minimum possible value of the sum described in the statement.

NoteIn the first test one of the optimal permutations is 1 4 2. In the second test the initial order is optimal. In the third test one of the optimal permutations is 2 3 4 4 3 5.

object B extends App {

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

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

  val delta = Array.ofDim[Long](n - 1)
  for (i <- 1 until n) delta(i - 1) = Math.abs(as(i - 1) - as(i))
  val ds = delta.scan(0L)(_ + _)
  val memo = Array.fill(k - n % k + 1, n % k + 1)(-1L)

  def solve(from: Int, depthS: Int, depthL: Int): Long = {
    if (from >= n || depthL > n % k || depthS > k - n % k) {
      if (from == n && depthS + depthL == k) 0L
      else Long.MaxValue / 2
    } else if (memo(depthS)(depthL) == -1) {
      var res = Long.MaxValue / 2
      val to1 = from + n / k
      val x = ds(to1 - 1) - ds(from) + solve(to1, depthS + 1, depthL)
        if (x < res) {
          res = x
          memo(depthS)(depthL) = res
        }
      if (to1 < n) {
        val to2 = to1 + 1
        val x = ds(to2 - 1) - ds(from) + solve(to2, depthS, depthL + 1)
        if (x < res) {
          res = x
          memo(depthS)(depthL) = res
        }
      }
      res
    } else memo(depthS)(depthL)
  }

  println(solve(0, 0, 0))
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n).sorted
  val bs = Array.ofDim[Int](n)

  var res = Long.MaxValue

  for (d <- 0 to n % k) {
    var offset = d
    var j = d
    var sum = 0L
    var i = 0
    while (i < n) {
      bs(j) = as(i)
      j += k
      if (j >= n) {
        offset += 1
        if (offset >= k) offset -= k
        j = offset
      }
      i += 1
    }
    i = 0
    while (i < n - k) {
      sum += Math.abs(bs(i) - bs(i + k))
      i += 1
    }
    if (sum < res) res = sum
  }

  println(res)
}

object B extends App {

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

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

  val delta = Array.ofDim[Long](n - 1)
  for (i <- 1 until n) delta(i - 1) = Math.abs(as(i - 1) - as(i))
  val ds = delta.scan(0L)(_ + _)
  val memo = Array.fill(n)(-1L)

  def solve(from: Int, depth: Int): Long = {
    if (from >= n) {
      if (from == n && depth == k) 0L
      else Long.MaxValue / 2
    } else if (memo(from) == -1) {
      var res = Long.MaxValue / 2
      for (_to <- n / k to n / k + 1) {
        val to = from + _to
        if (to <= n) {
          val x = ds(to - 1) - ds(from) + solve(to, depth + 1)
          if (x < res) {
            res = x
            memo(from) = res
          }
        }
      }
      res
    } else memo(from)
  }

  println(solve(0, 0))
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n).sorted
  val bs = Array.ofDim[Int](n)

  var res = Long.MaxValue

  for (d <- 0 to k) {
    var offset = d
    var j = d
    var sum = 0L
    var i = 0
    while (i < n) {
      bs(j) = as(i)
      j += k
      if (j >= n) {
        offset += 1
        if (offset >= k) offset -= k
        j = offset
      }
      i += 1
    }
    i = 0
    while (i < n - k) {
      sum += Math.abs(bs(i) - bs(i + k))
      i += 1
    }
    //println(d, sum)
    //println(bs.mkString(" "))
    if (sum < res) {
      res = sum
    }
  }

  println(res)
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n).sorted
  val bs = Array.ofDim[Int](n)

  var res = Long.MaxValue

  for (d <- 0 until n) {
    var offset = 0
    var j = 0
    var sum = 0L
    var i = 0
    while (i < n) {
      var ii = i + d
      if (ii >= n) ii -= n
      bs(j) = as(ii)
      j += k
      if (j >= n) {
        offset += 1
        if (offset >= k) offset -= k
        j = offset
      }
      i += 1
    }
    i = 0
    while (i < n - k) {
      sum += Math.abs(bs(i) - bs(i + k))
      i += 1
    }
    //println(d, sum)
    //println(bs.mkString(" "))
    if (sum < res) {
      res = sum
    }
  }

  println(res)
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n).sorted
  val bs = Array.ofDim[Int](n)

  var res = Long.MaxValue

  for (d <- 0 until Math.min(n, 2 * k)) {
    var offset = 0
    var j = 0
    var sum = 0L
    var i = 0
    while (i < n) {
      var ii = i + d
      if (ii >= n) ii -= n
      bs(j) = as(ii)
      j += k
      if (j >= n) {
        offset += 1
        if (offset >= k) offset -= k
        j = offset
      }
      i += 1
    }
    i = 0
    while (i < n - k) {
      sum += Math.abs(bs(i) - bs(i + k))
      i += 1
    }
    //println(d, sum)
    //println(bs.mkString(" "))
    if (sum < res) {
      res = sum
    }
  }

  println(res)
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n).sorted
  val bs = Array.ofDim[Int](n)

  var res = Long.MaxValue

  for (d <- 0 to k) {
    var offset = 0
    var j = 0
    var sum = 0L
    var i = 0
    while (i < n) {
      var ii = i + d
      if (ii >= n) ii -= n
      bs(j) = as(ii)
      j += k
      if (j >= n) {
        offset += 1
        if (offset >= k) offset -= k
        j = offset
      }
      i += 1
    }
    i = 0
    while (i < n - k) {
      sum += Math.abs(bs(i) - bs(i + k))
      i += 1
    }
    //println(d, sum)
    //println(bs.mkString(" "))
    if (sum < res) {
      res = sum
    }
  }

  println(res)
}

object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n).sorted
  val bs = Array.ofDim[Int](n)

  var res = Long.MaxValue

  for (d <- 0 until Math.min(n, 2 * k)) {
    var offset = d
    var j = d
    var sum = 0L
    var i = 0
    while (i < n) {
      bs(j) = as(i)
      j += k
      if (j >= n) {
        offset += 1
        if (offset >= k) offset -= k
        j = offset
      }
      i += 1
    }
    i = 0
    while (i < n - k) {
      sum += Math.abs(bs(i) - bs(i + k))
      i += 1
    }
    //println(d, sum)
    //println(bs.mkString(" "))
    if (sum < res) {
      res = sum
    }
  }

  println(res)
}


Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.

The only line of the input contains a sequence of characters "+" and "-", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.

Print the sought minimum number of people

import math._

object Main extends App{
  val s = readLine()
  var maxVal, minVal, curVal = 0
  for (c <- s){
    if (c == '+')
      curVal += 1
    else
      curVal -= 1
    maxVal = max(maxVal, curVal)
    minVal = min(minVal, curVal)
  }
  println(maxVal - minVal)
}

import scala.io.StdIn

object MishapInClub {
  //+ in, - out
  def minNum(l:String):Int={
    var in = 0
    var out = 0
    var minNeeded = 0
    for (a<-0 to l.length()-1){
      if (l(a)=='+'){
        in = in + 1
        if (out==0){
          minNeeded = minNeeded + 1
        }else{
          out = out -1
        }
      }else if (l(a)=='-'){
        out = out + 1
        if (in==0){
          minNeeded = minNeeded + 1
        }else{
          in = in -1
        }
      }
    }
    minNeeded
  }

  def main(args:Array[String]){
    val l = StdIn.readLine()
    println(minNum(l))
  }

}

object Main extends App{
  val s = readLine()
  var maxAbs, curVal = 0
  for (c <- s){
    if (c == '+')
      curVal += 1
    else
      curVal -= 1
    maxAbs = math.max(maxAbs, math.abs(curVal))
  }
  println(maxAbs)
}

import scala.io.StdIn

object MishapInClub {
  //+ in, - out
  def minNum(l:String):Int={

    //net in or net out or consecutive in or consecutive out
    var netIn = 0;
    var netOut = 0;
    var last = ' ';
    var conIn = 0;
    var conOut = 0;
    var conInMax = 0;
    var conOutMax = 0;

    def checkConInMax(a:Int)={
      if (a>=conInMax){
        conInMax = a
      }
    }

    def checkConOutMax(a:Int)={
      if (a>=conOutMax){
        conOutMax = a
      }
    }

    for (a<-0 to l.length()-1){
      if (l(a)=='+'){
        netIn = netIn + 1
        netOut = netOut -1
      }else{
        netOut = netOut + 1
        netIn = netIn -1
      }
      if (l(a)==last){
        if (l(a)=='+'){
          conIn = conIn + 1
          checkConInMax(conIn)
        }else{
          conOut = conOut + 1
          checkConOutMax(conOut)
        }
      }else{
        if (l(a)=='+'){
          checkConInMax(conIn)
          conIn = 1
        }else{
          checkConOutMax(conOut)
          conOut = 1
        }
      }
      last = l(a)
    }

    checkConOutMax(conOut)
    checkConInMax(conIn)
    if (l(l.length()-1)=='+'){
      netOut = netOut + 1
    }
    if (l(l.length()-1)=='-'){
      netIn = netIn + 1
    }

    Math.max(Math.max(netIn, netOut), Math.max(conInMax, conOutMax))
  }

  def main(args:Array[String]){
    val l = StdIn.readLine()
    println(minNum(l))
  }

}

import scala.io.StdIn

object MishapInClub {
  //+ in, - out
  def minNum(l:String):Int={
    //net in or net out or consecutive in or consecutive out
    var netIn = 0;
    var netOut = 0;
    var last = ' ';
    var conIn = 0;
    var conOut = 0;
    for (a<-0 to l.length()-1){
      if (l(a)=='+'){
        netIn = netIn + 1
        netOut = netOut -1
      }else{
        netOut = netOut + 1
        netIn = netIn -1
      }
      if (l(a)==last){
        if (l(a)=='+'){
          conIn = conIn + 1
        }else{
          conOut = conOut + 1
        }
      }else{
        if (l(a)=='+'){
          conIn = 1
        }else{
          conOut = 1
        }
      }
      last = l(a)
    }
    Math.max(Math.max(netIn, netOut), Math.max(conIn, conOut))
  }

  def main(args:Array[String]){
    val l = StdIn.readLine()
    println(minNum(l))
  }

}

import scala.io.StdIn

object MishapInClub {

  def minNum(l:String):Int={
    //net in or net out or consecutive in or consecutive out
    var netIn = 0;
    var netOut = 0;
    var last = l(0)
    var conIn = if (last=='+') 1 else 0
    var conOut = if (last=='-') 1 else 0
    for (a<-0 to l.length()-1){
      if (l(a)=='+'){
        netIn = netIn + 1
        netOut = netOut -1
      }else{
        netOut = netOut + 1
        netIn = netIn -1
      }
      if (a>0 && l(a)==last){
        if (l(a)=='+'){
          conIn = conIn + 1
          conOut = 0
        }else{
          conOut = conOut + 1
          conIn = 0
        }
      }
      last = l(a)
    }
    Math.max(Math.max(netIn, netOut), Math.max(conIn, conOut))
  }

  def main(args:Array[String]){
    val l = StdIn.readLine()
    println(minNum(l))
  }

}

import scala.io.StdIn

object MishapInClub {
  //+ in, - out
  def minNum(l:String):Int={

    //net in or net out or consecutive in or consecutive out
    var netIn = 0;
    var netOut = 0;
    var last = ' ';
    var conIn = 0;
    var conOut = 0;
    var conInMax = 0;
    var conOutMax = 0;

    def checkConInMax(a:Int)={
      if (a>=conInMax){
        conInMax = a
      }
    }

    def checkConOutMax(a:Int)={
      if (a>=conOutMax){
        conOutMax = a
      }
    }

    for (a<-0 to l.length()-1){
      if (l(a)=='+'){
        netIn = netIn + 1
        netOut = netOut -1
      }else{
        netOut = netOut + 1
        netIn = netIn -1
      }
      if (l(a)==last){
        if (l(a)=='+'){
          conIn = conIn + 1
          checkConInMax(conIn)
        }else{
          conOut = conOut + 1
          checkConOutMax(conOut)
        }
      }else{
        if (l(a)=='+'){
          checkConInMax(conIn)
          conIn = 1
        }else{
          checkConOutMax(conOut)
          conOut = 1
        }
      }
      last = l(a)
    }

    checkConOutMax(conOut)
    checkConInMax(conIn)

    Math.max(Math.max(netIn, netOut), Math.max(conInMax, conOutMax))
  }

  def main(args:Array[String]){
    val l = StdIn.readLine()
    println(minNum(l))
  }

}

import scala.io.StdIn

object MishapInClub {
  //+ in, - out
  def minNum(l:String):Int={
    //net in or net out or consecutive in or consecutive out
    var netIn = 0;
    var netOut = 0;
    var last = ' ';
    var conIn = 0;
    var conOut = 0;
    var conInMax = 0;
    var conOutMax = 0;
    for (a<-0 to l.length()-1){
      if (l(a)=='+'){
        netIn = netIn + 1
        netOut = netOut -1
      }else{
        netOut = netOut + 1
        netIn = netIn -1
      }
      if (l(a)==last){
        if (l(a)=='+'){
          conIn = conIn + 1
          if (conIn>conInMax)
            conInMax = conIn
        }else{
          conOut = conOut + 1
          if (conOut>conOutMax)
             conOutMax = conOut
        }
      }else{
        if (l(a)=='+'){
          if (conIn>conInMax)
            conInMax = conIn
          conIn = 1

        }else{
          if (conOut>conOutMax)
            conOutMax = conOut
          conOut = 1
        }
      }
      last = l(a)
    }
    Math.max(Math.max(netIn, netOut), Math.max(conInMax, conOutMax))
  }

  def main(args:Array[String]){
    val l = StdIn.readLine()
    println(minNum(l))
  }

}

import scala.io.StdIn

object MishapInClub {

  def minNum(l:String):Int={
    var plus=0
    var minus=0
    l.foreach { x => if (x=='+') plus=plus+1 else minus=minus+1 }
    Math.abs(plus-minus)
  }

  def main(args:Array[String]){
    val l = StdIn.readLine()
    println(minNum(l))
  }

}


Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of $$$n$$$ heroes, the strength of the $$$i$$$-th hero is equal to $$$a_i$$$.According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to $$$x$$$, then you have to send a hero with a strength of at least $$$x$$$ to kill it. If the dragon's attack power is $$$y$$$, then the total strength of the heroes defending the castle should be at least $$$y$$$.The player can increase the strength of any hero by $$$1$$$ for one gold coin. This operation can be done any number of times.There are $$$m$$$ dragons in the game, the $$$i$$$-th of them has defense equal to $$$x_i$$$ and attack power equal to $$$y_i$$$. Petya was wondering what is the minimum number of coins he needs to spend to defeat the $$$i$$$-th dragon.Note that the task is solved independently for each dragon (improvements are not saved).

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — number of heroes. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th hero. The third line contains a single integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of dragons. The next $$$m$$$ lines contain two integers each, $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le 10^{12}; 1 \le y_i \le 10^{18}$$$) — defense and attack power of the $$$i$$$-th dragon.

Print $$$m$$$ lines, $$$i$$$-th of which contains a single integer — the minimum number of coins that should be spent to defeat the $$$i$$$-th dragon.

NoteTo defeat the first dragon, you can increase the strength of the third hero by $$$1$$$, then the strength of the heroes will be equal to $$$[3, 6, 3, 3]$$$. To kill the dragon, you can choose the first hero.To defeat the second dragon, you can increase the forces of the second and third heroes by $$$1$$$, then the strength of the heroes will be equal to $$$[3, 7, 3, 3]$$$. To kill the dragon, you can choose a second hero.To defeat the third dragon, you can increase the strength of all the heroes by $$$1$$$, then the strength of the heroes will be equal to $$$[4, 7, 3, 4]$$$. To kill the dragon, you can choose a fourth hero.To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill the dragon.To defeat the fifth dragon, you can increase the strength of the second hero by $$$2$$$, then the strength of the heroes will be equal to $$$[3, 8, 2, 3]$$$. To kill the dragon, you can choose a second hero.

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object test {
    val writer =  new PrintWriter(System.out, false)
    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 bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val h = new Array[Long](n)
        for (i <- 0 to n-1)
            h(i) = readLong
        quickSort(h)
        val sum = h.sum
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

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

object test {
    val writer =  new PrintWriter(System.out, false)
    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 bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val h = new Array[Long](n)
        for (i <- 0 to n-1)
            h(i) = readLong
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

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

object test {
    val writer =  new PrintWriter(System.out, false)
    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 bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val ss = reader.readLine()
        var h = ss.split(' ').map(_.toLong)
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

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

object test {
    val writer =  new PrintWriter(System.out, false)
    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 bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val ss = reader.readLine()
        val h = ss.split(' ').map(_.toLong)
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

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

object test {
    val writer =  new PrintWriter(System.out, false)
    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 bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val ss = reader.readLine()
        val h = ss.split(' ').map(_.toLong)
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
            writer.flush()
        }
        writer.flush()
    }
}

object what extends App{
    def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

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

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

        val overall = heroes.sum
        val sorted  = heroes.sorted

        (defense: Long, attack: Long) => {
            val index = search(0, heroes.length - 1, sorted(_) >= defense)

            def coins(index: Int): Long = {
                val hero = sorted(index)
                0L.max(defense - hero) + 0L.max(attack - overall + hero)
            }

            coins(index) min coins(0 max (index - 1))
        }
    }

    import InOut._

    val n  = nextInt()
    val hn = nextLongs(n)

    private lazy val coins = slayTheDragon(hn)

    val m = nextInt()

    (0 until m).foreach { _ =>
        val Array(x, y) = nextLongs(2)

        out.println(coins(x, y))

    }
    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 what extends App{
    def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

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

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

        val overall = heroes.sum
        val sorted  = heroes.sorted

        (defense: Long, attack: Long) => {
            val index = search(0, heroes.length - 1, sorted(_) >= defense)

            def coins(index: Int): Long = {
                val hero = sorted(index)
                0L.max(defense - hero) + 0L.max(attack - overall + hero)
            }

            coins(index) min coins(0 max (index - 1))
        }
    }

    import InOut._

    val n  = nextInt()
    val hn = nextLongs(n)

    private lazy val coins = slayTheDragon(hn)

    val m = nextInt()

    (0 until m).foreach { _ =>
        val Array(x, y) = nextLongs(2)

        out.println(coins(x, y))
        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 C extends App {

  def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

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

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

    val heroesSorted  = heroes.sorted
    val heroesOverall = heroes.sum

    (dragonDefense: Long, dragonAttack: Long) => {
      val index = search(0, heroes.length - 1, heroesSorted(_) >= dragonDefense)

      def coins(index: Int): Long = {
        val hero = heroesSorted(index)
        0L.max(dragonDefense - hero) + 0L.max(dragonAttack - heroesOverall + hero)
      }

      coins(index) min coins(0 max (index - 1))
    }
  }

  import InOut._

  val n  = nextInt()
  val hn = nextLongs(n)

  lazy val coins = slayTheDragon(hn)

  val m = nextInt()

  (0 until m).foreach { _ =>
    val Array(x, y) = nextLongs(2)

    out.println(coins(x, y))
  }
  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 C extends App {

  def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

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

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

    val overall = heroes.sum
    val sorted  = heroes.sorted

    (defense: Long, attack: Long) => {
      val index = search(0, heroes.length - 1, sorted(_) >= defense)

      def coins(index: Int): Long = {
        val hero = sorted(index)
        0L.max(defense - hero) + 0L.max(attack - overall + hero)
      }

      coins(index) min coins(0 max (index - 1))
    }
  }

  import InOut._

  val n  = nextInt()
  val hn = nextLongs(n)

  private lazy val coins = slayTheDragon(hn)

  val m = nextInt()

  (0 until m).foreach { _ =>
    val Array(x, y) = nextLongs(2)

    out.println(coins(x, y))
    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.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    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() = next.toInt
    def readLong() = next.toLong
    def readString() = next()

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def main(args: Array[String]) {
        var t = 1 //readInt()
        while (t > 0) {
            t -= 1
            val n = readInt()
            val a = new Array[Long](n)
            for (i <- 0 until n) a(i) = readLong()

            quickSort(a)
            val sum = a.sum

            val m = readInt()
            for (i <- 0 until m) {
                val x = readLong()
                val y = readLong() - sum

                if (y >= x) {
                    writer.println(Math.max(0, x - a(0)) + Math.max(0, y + a(0)))
                } else {
                    val avg = (x - y) / 2
                    var l = 0
                    var r = n - 1
                    var min = -1L
                    while (l <= r) {
                        val mid = (l + r) / 2
                        if (a(mid) > avg) r = mid - 1
                        else {
                            min = a(mid)
                            l = mid + 1
                        }
                    }

                    l = 0
                    r = n - 1
                    var max = -1L
                    while (l <= r) {
                        val mid = (l + r) / 2
                        if (a(mid) >= avg) {
                            r = mid - 1
                            max = a(mid)
                        } else l = mid + 1
                    }

                    val rsmin = if (min != -1) Math.max(0, x - min) + Math.max(0, y + min) else Long.MaxValue
                    val rsmax = if (max != -1) Math.max(0, x - max) + Math.max(0, y + max) else Long.MaxValue

                    writer.println(Math.min(rsmin, rsmax))
                }

            }
        }
        writer.close()
    }
}


Ehab loves number theory, but for some reason he hates the number $$$x$$$. Given an array $$$a$$$, find the length of its longest subarray such that the sum of its elements isn't divisible by $$$x$$$, or determine that such subarray doesn't exist.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The first line contains an integer $$$t$$$ $$$(1 \le t \le 5)$$$ — the number of test cases you need to solve. The description of the test cases follows. The first line of each test case contains 2 integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^4$$$) — the number of elements in the array $$$a$$$ and the number that Ehab hates. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$.

For each testcase, print the length of the longest subarray whose sum isn't divisible by $$$x$$$. If there's no such subarray, print $$$-1$$$.

NoteIn the first test case, the subarray $$$[2,3]$$$ has sum of elements $$$5$$$, which isn't divisible by $$$3$$$.In the second test case, the sum of elements of the whole array is $$$6$$$, which isn't divisible by $$$4$$$.In the third test case, all subarrays have an even sum, so the answer is $$$-1$$$.

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 nx = readIntLine()
      val arr = readIntLine().toArray
      println(findLongest(arr, nx.last))
    }
  }

  def findLongest(arr: Array[Int], x: Int): Int = {
    if (arr.forall(_ % x == 0)) return -1

    if (arr.sum % x != 0) return arr.length

    for (i <- arr.indices) {
      if (arr(i) % x != 0 || arr(arr.length - 1 - i) % x != 0)
        return arr.length - i - 1
    }

    -1
  }

  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 A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextInts(n)
      var l = 0
      while (l < n && as(l) % x == 0) {
        l += 1
      }

      var r = n - 1
      while (r >= 0 && as(r) % x == 0) {
        r -= 1
      }

      var res = -1
      val sum = as.sum
      if (sum % x != 0) {
        res = n
      } else if (l <= r) {
        val rr = r
        val ll = n - l - 1
        res = ll max rr
        //println(l, r, ll, rr)
      }
      out.println(res)

      out.flush()
    }
  }

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

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 nx = readIntLine()
      val arr = readIntLine().toArray
      println(findLongest(arr, nx.last))
    }
  }

  def findLongest(arr: Array[Int], x: Int): Int = {
    if (arr.forall(_ % x == 0)) return -1

    if (arr.sum % x != 0) return arr.length

    for (i <- arr.indices) {
      if (arr(i) % x != 0 || arr(arr.length - 1 - i) != 0)
        return arr.length - i - 1
    }

    -1
  }

  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 A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextInts(n)
      var l = 0
      while (l < n && as(l) % x == 0) {
        l += 1
      }

      var r = n - 1
      while (r >= 0 && as(r) % x == 0) {
        r -= 1
      }

      var res = -1
      val sum = as.sum
      if (sum % x != 0) {
        res = n
      } else {
        val rr = r - 1
        val ll = n - l - 1
        res = ll max rr
        //println(l, r, ll, rr)
      }
      out.println(res)

      out.flush()
    }
  }

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

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

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextInts(n)
      var l = 0
      while (l < n && as(l) % x == 0) {
        l += 1
      }

      var r = n - 1
      while (r >= 0 && as(r) % x == 0) {
        r -= 1
      }

      var res = -1
      val sum = as.sum
      if (sum % x != 0) {
        res = n
      } else if (l < r) {
        val rr = r - 1
        val ll = n - l - 1
        res = ll max rr
        //println(l, r, ll, rr)
      }
      out.println(res)

      out.flush()
    }
  }

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


William has array of $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. He can perform the following sequence of operations any number of times:   Pick any two items from array $$$a_i$$$ and $$$a_j$$$, where $$$a_i$$$ must be a multiple of $$$2$$$  $$$a_i = \frac{a_i}{2}$$$  $$$a_j = a_j \cdot 2$$$ Help William find the maximal sum of array elements, which he can get by performing the sequence of operations described above.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 15)$$$, the number of elements in William's array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i < 16)$$$, the contents of William's array.

For each test case output the maximal sum of array elements after performing an optimal sequence of operations.

NoteIn the first example test case the optimal sequence would be:   Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \frac{4}{2} = 2$$$ and $$$a_1 = 6 \cdot 2 = 12$$$, making the array look as: [12, 2, 2].  Pick $$$i = 2$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_2 = \frac{2}{2} = 1$$$ and $$$a_1 = 12 \cdot 2 = 24$$$, making the array look as: [24, 1, 2].  Pick $$$i = 3$$$ and $$$j = 1$$$. After performing a sequence of operations $$$a_3 = \frac{2}{2} = 1$$$ and $$$a_1 = 24 \cdot 2 = 48$$$, making the array look as: [48, 1, 1]. The final answer $$$48 + 1 + 1 = 50$$$.In the third example test case there is no way to change the sum of elements, so the answer is $$$10$$$.

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    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()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Long](n+1)
        var cnt = 0
        var sum = 0L
        var mx = 1L
        for (i <- 1 to n) {
            arr(i) = readLong()
            while(arr(i) % 2 == 0) {
                cnt += 1
                arr(i) /= 2L
            }
            sum += arr(i)
            mx = max(mx, arr(i))
        }
        sum -= mx
        for (i <- 1 to cnt) {
            mx *= 2L
        }
        sum += mx
        writer.println(sum)

        def check(kk: Int): Boolean = {
            return true
        }
        def bs(st:Int, en:Int): Int = {
            if (en - st <= 1) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}

import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._
import scala.io.StdIn

object Main extends App {
  val t = StdIn.readInt()
  (0 until t).foreach { _ =>
    val n = StdIn.readInt()
    val arr = StdIn.readLine().split(" ").map(i => BigInt(i.toInt))
    var num:BigInt  = 1
    var mx:BigInt = 0
    var mxidx = 0
    (0 until n).foreach { i =>
      while (arr(i) % 2 == 0) {
        arr(i) /= 2
        num *= 2
      }
      if (arr(i) > mx) {
        mx = arr(i)
        mxidx = i
      }
    }
    arr(mxidx) *= num
    println(arr.sum)
  }
}


Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high.   A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.

The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.

Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.

object B extends App {

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

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

  val leftSmaller, rightSmaller = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    var j = i - 1
    while (j >= 0 && as(j) >= as(i)) {
      j = leftSmaller(j)
    }
    leftSmaller(i) = j
  }

  for (i <- n - 1 to 0 by -1) {
    var j = i + 1
    while (j < n && as(j) >= as(i)) {
      j = rightSmaller(j)
    }
    rightSmaller(i) = j
  }

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

  for (i <- 0 until n) {
    val span = rightSmaller(i) - leftSmaller(i) - 2
    if (res(span) < as(i)) res(span) = as(i)
  }

  for (i <- n - 2 to 0 by -1) {
    if (res(i) < res(i + 1)) res(i) = res(i + 1)
  }

  println(res.mkString(" "))
}

import scala.collection._

object B extends App {

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

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

  val leftSmaller, rightSmaller = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    var j = i - 1
    while (j >= 0 && as(j) >= as(i)) {
      j = leftSmaller(j)
    }
    leftSmaller(i) = j
  }

  for (i <- n - 1 to 0 by -1) {
    var j = i + 1
    while (j < n && as(j) >= as(i)) {
      j = rightSmaller(j)
    }
    rightSmaller(i) = j
  }

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

  for (i <- 0 until n) {
    val span = rightSmaller(i) - leftSmaller(i) - 2
    if (res(span) < as(i)) res(span) = as(i)
  }

  for (i <- n - 2 to 0 by -1) {
    if (res(i) == 0) res(i) = res(i + 1)
  }

  println(res.mkString(" "))
}

object B extends App {

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

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

  val leftSmaller, rightSmaller = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    var j = i - 1
    while (j >= 0 && as(j) >= as(i)) {
      j = leftSmaller(j)
    }
    leftSmaller(i) = j
  }

  for (i <- n - 1 to 0 by -1) {
    var j = i + 1
    while (j < n && as(j) >= as(i)) {
      j = rightSmaller(j)
    }
    rightSmaller(i) = j
  }

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

  for (i <- 0 until n) {
    val span = rightSmaller(i) - leftSmaller(i) - 2
    if (res(span) < as(i)) res(span) = as(i)
  }

  for (i <- n - 2 to 0 by -1) {
    if (res(i) == 0) res(i) = res(i + 1)
  }

  println(res.mkString(" "))
}