For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000.

The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109.

If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000.

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(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (pos == total0 + total1) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val _total0 = totalCount(a00)
  val _total1 = totalCount(a11)

  val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0
  val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else if (a00 + a01 + a10 + a11 == 0) println("0")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int, aXY: Int, aYX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    if (x == 0 && aXY + aYX > 0) 1 else x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, remain0: Int, remain1: Int, a01: Int, a10: Int): String = {

    if (remain0 + remain1 == 0) {
      res.take(pos).mkString
    } else if (a01 + a10 - remain0 == remain0 * (remain1 - 1) && remain0 <= a10) {
      res(pos) = '1'
      build(pos + 1, remain0, remain1 - 1, a01, a10 - remain0)
    } else {
      res(pos) = '0'
      build(pos + 1, remain0 - 1, remain1, a01 - remain1, a10)
    }

  }

  val total0 = totalCount(a00, a01, a10)
  val total1 = totalCount(a11, a10, a01)

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else if (a00 + a01 + a10 + a11 == 0) println("0")
  else println(build(0, total0, total1, a01, a10))
}

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(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val _total0 = totalCount(a00)
  val _total1 = totalCount(a11)

  val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0
  val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("Impossible")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val total0 = totalCount(a00)
  val total1 = totalCount(a11)

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  def totalCount(aXX: Int): Int = {
    var x = 0
    while (x * (x - 1) / 2 < aXX) x += 1
    x
  }

  val res = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {

    val x10for1 = total0 - cnt0
    val x01for0 = total1 - cnt1

    if (pos == total0 + total1) {
      res.take(pos).mkString
    } else if (a00 < 0 || a01 < 0 || a10 < 0 | a11 < 0) {
      ""
    } else if (a01 + a10 - x10for1 == (total0 - cnt0) * (total1 - cnt1 - 1) && x10for1 <= a10) {
      res(pos) = '1'
      build(pos + 1, cnt0, cnt1 + 1, a00, a01, a10 - x10for1, a11 - cnt1)
    } else {
      res(pos) = '0'
      build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01 - x01for0, a10, a11)
    }

  }

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

  val _total0 = totalCount(a00)
  val _total1 = totalCount(a11)

  val total0 = if (_total0 > 0) _total0 else if (a01 + a10 > 0) 1 else 0
  val total1 = if (_total1 > 0) _total1 else if (a01 + a10 > 0) 1 else 0

  if (total0 * (total0 - 1) / 2 != a00 || total1 * (total1 - 1) / 2 != a11 ||
    total0 * total1 != a01 + a10) println("Impossible")
  else {
    res(0) = '1'
    val r1 = build(1, 0, 1, a00, a01, a10 - total0, a11)
    res(0) = '0'
    val r2 = build(1, 1, 0, a00, a01 - total1, a10, a11)
    if (r1 != "") println(r1)
    else if (r2 != "") println(r2)
    else println("Impossible")
  }

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0 && (a00.toLong - cnt0) * cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0 && (a11.toLong - cnt1) * cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } /*else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } */else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}

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(a00, a01, a10, a11) = readInts(4)

  val res0 = Array.ofDim[Char](1000003)

  def build(pos: Int, cnt0: Int, cnt1: Int, a00: Int, a01: Int, a10: Int, a11: Int): String = {
    //println(res0.take(pos).mkString, pos, a00, a01, a10, a11)
    if (a00 == 0 && a01 == 0 && a10 == 0 && a11 == 0) {
      res0.take(pos).mkString
    } else if (a00 + a11 > a01 + a10 && a01 > 0 && a10 > 0) {
      ""
    } else if ((a00.toLong - cnt0) * cnt1 > a10 && cnt1 > 0) {
      ""
    } else if ((a11.toLong - cnt1) * cnt0 > a01 && cnt0 > 0) {
      ""
    } else if (pos > 32000 || a00 < 0 || a01 < 0 || a10 < 0 || a11 < 0) {
      ""
    } else {
      res0(pos) = '0'
      val res = build(pos + 1, cnt0 + 1, cnt1, a00 - cnt0, a01, a10 - cnt1, a11)

      if (res != "") res
      else {
        res0(pos) = '1'
        build(pos + 1, cnt0, cnt1 + 1, a00, a01 - cnt0, a10, a11 - cnt1)
      }
    }
  }

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

  res0(0) = '0'
  val r1 = build(1, 1, 0, a00, a01, a10, a11)

  res0(0) = '1'
  val r2 = if (r1 != "") r1
  else build(1, 0, 1, a00, a01, a10, a11)

  if (r1 == "0") println("")
  else if (r1 != "") println(r1)
  else if (r2 != "") println(r2)
  else println("Impossible")

  Console.flush
}


Two pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2·x + 1 ≤ n) and take a coin from each chest with numbers x, 2·x, 2·x + 1. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of chests with coins. The second line contains a sequence of space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai is the number of coins in the chest number i at the beginning of the game.

Print a single integer — the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.

NoteIn the first test case there isn't a single move that can be made. That's why the players won't be able to empty the chests.In the second sample there is only one possible move x = 1. This move should be repeated at least 3 times to empty the third chest.

object Main extends App{
  val n = readInt()
  val xs = Array(0) ++ readLine().split(" ").map(_.toInt)
  var ans = 0
  for (i <- (1 to n).reverse){
    if (xs(i) > 0){
      if (i > 1 && i % 2 == 1){
        xs(i-1) -= xs(i)
        xs((i-1)/2) -= xs(i)
        ans += xs(i)
      }
      else if (i > 1 && i % 2 == 0){
        xs(i/2) -= xs(i)
        ans += xs(i)
      }
      else {
        ans += xs(i)
      }
    }
  }
  if (n < 3 || n % 2 == 0)
    ans = -1
  println(ans)
}

// CodeForces 245 C

object IgraMonet extends App {
  val n = Console.readInt
  val s = Console.readLine
  val a:Array[Int] = (s split " ") map (_.toInt)
  // println("n=" + n +"s:" + s + "a:" + a)

  def countMoves(lst:Int, cnt:Int):Int =
    if (lst < 3) cnt + math.max(a(0), 0)
    else {
      val ad = math.max(0, math.max(a(lst-1), a(lst-2)))
      a(lst-1) -= ad
      a(lst - 2) -= ad
      a((lst-3)/2) -= ad
      countMoves(lst-2, cnt+ad)
    }

  if (n < 3 || (n % 2 == 0))    println(-1)
  else println(countMoves(n, 0))
}

object Main extends App{
  val n = readInt()
  val xs = Array(0) ++ readLine().split(" ").map(_.toInt)
  var ans = 0
  for (i <- (1 to n).reverse){
    if (xs(i) > 0){
      if (i > 1 && i % 2 == 1){
        xs(i-1) -= xs(i)
        xs((i-1)/2) -= xs(i)
        ans += xs(i)
      }
      else if (i > 1 && i % 2 == 0){
        xs(i/2) -= xs(i)
        ans += xs(i)
      }
      else {
        ans += xs(i)
      }
    }
  }
  if (n < 3)
    ans = -1
  println(ans)
}

// CodeForces 245 C

object IgraMonet extends App {
  val n = Console.readInt
  val s = Console.readLine
  val a:Array[Int] = (s split " ") map (_.toInt)
  // println("n=" + n +"s:" + s + "a:" + a)

  def countMoves(lst:Int, cnt:Int):Int =
    if (lst < 3) cnt + a(0)
    else {
      val ad = math.max(0, math.max(a(lst-1), a(lst-2)))
      a(lst-1) -= ad
      a(lst - 2) -= ad
      a((lst-3)/2) -= ad
      countMoves(lst-2, cnt+ad)
    }

  if (n < 3 || (n % 2 == 0))    println(-1)
  else println(countMoves(n, 0))
}

// CodeForces 245 C

object IgraMonet extends App {
  val n = Console.readInt
  val s = Console.readLine
  val a:Array[Int] = (s split " ") map (_.toInt)
  // println("n=" + n +"s:" + s + "a:" + a)

  def countMoves(lst:Int, cnt:Int):Int =
    if (lst < 3) cnt
    else {
      val ad = math.max(0, math.max(a(lst-1), a(lst-2)))
      a(lst-1) -= ad
      a(lst - 2) -= ad
      a((lst-3)/2) -= ad
      countMoves(lst-2, cnt+ad)
    }

  if (n < 3 || (n % 2 == 0))    println(-1)
  else println(countMoves(n, 0))
}


Monocarp has got an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote $$$k$$$ as the mathematic mean of these elements (note that it's possible that $$$k$$$ is not an integer). The mathematic mean of an array of $$$n$$$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $$$n$$$).Monocarp wants to delete exactly two elements from $$$a$$$ so that the mathematic mean of the remaining $$$(n - 2)$$$ elements is still equal to $$$k$$$.Your task is to calculate the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{9}$$$), where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print one integer — the number of pairs of positions $$$[i, j]$$$ ($$$i < j$$$) such that if the elements on these positions are deleted, the mathematic mean of $$$(n - 2)$$$ remaining elements is equal to $$$k$$$ (that is, it is equal to the mathematic mean of $$$n$$$ elements of the original array $$$a$$$).

NoteIn the first example, any pair of elements can be removed since all of them are equal.In the second example, there is no way to delete two elements so the mathematic mean doesn't change.In the third example, it is possible to delete the elements on positions $$$1$$$ and $$$3$$$, or the elements on positions $$$4$$$ and $$$5$$$.

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

object sample 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 myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n)
        var sum = 0L
        for (i <- 0  until n) {
            arr(i) = readInt()
            sum += arr(i).toLong
        }
        val mp = mutable.Map[Double, Int]()
        val mean = sum / n.toDouble
        var cnt = 0L
        var k = 0d
        for (i <- 0  until n) {
            k = arr(i) - mean
            if (mp.contains(-1*k)) {
                cnt += mp(-1*k).toLong
            }
            if (!mp.contains(k))
                mp(k) = 1
            else
                mp(k) += 1
        }
        writer.println(cnt)
    }
    writer.flush()
}

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

object sample 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 myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n)
        for (i <- 0  until n) {
            arr(i) = readInt()
        }
        val mp = mutable.Map[Int, Int]()
        val mean = arr.sum / n
        var cnt = 0
        var k = 0
        for (i <- 0  until n) {
            k = arr(i) - mean
            if (mp.contains(-1*k)) {
                cnt += mp(-1*k)
            }
            if (!mp.contains(k))
                mp(k) = 1
            else
                mp(k) += 1
        }
        writer.println(cnt)
    }
    writer.flush()
}


You are given $$$n$$$ rectangles on a plane with coordinates of their bottom left and upper right points. Some $$$(n-1)$$$ of the given $$$n$$$ rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.Find any point with integer coordinates that belongs to at least $$$(n-1)$$$ given rectangles.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 132\,674$$$) — the number of given rectangles. Each the next $$$n$$$ lines contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9 \le x_1 < x_2 \le 10^9$$$, $$$-10^9 \le y_1 < y_2 \le 10^9$$$) — the coordinates of the bottom left and upper right corners of a rectangle.

Print two integers $$$x$$$ and $$$y$$$ — the coordinates of any point that belongs to at least $$$(n-1)$$$ given rectangles.

NoteThe picture below shows the rectangles in the first and second samples. The possible answers are highlighted.  The picture below shows the rectangles in the third and fourth samples.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    case class Rect(l: Int, b: Int, r: Int, t: Int) {
      def add(that: Rect) = {
        Rect(max(l, that.l), max(b, that.b), min(r, that.r), min(t, that.t))
      }

      def isValid = l <= r && b <= t
    }
    val A = Array.ofDim[Rect](N)
    REP(N) { i =>
      val l, b, r, t = ni()
      A(i) = Rect(l, b, r, t)
    }

    val Zero = Rect(-1e9.toInt, -1e9.toInt, 1e9.toInt, 1e9.toInt)
    val L, R = Array.ofDim[Rect](N + 2)
    L(0) = Zero
    R(N + 1) = Zero
    REP(N) { i =>
      L(i + 1) = A(i).add(L(i))
    }

    REP_r(N) { i =>
      R(i + 1) = A(i).add(R(i + 2))
    }

    val rect = map(N) { i =>
      L(i).add(R(i + 2))
    }.find(_.isValid).get
    out.println(s"${rect.l} ${rect.b}")
  }

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

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

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

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

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

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


Let's call a list of positive integers $$$a_0, a_1, ..., a_{n-1}$$$ a power sequence if there is a positive integer $$$c$$$, so that for every $$$0 \le i \le n-1$$$ then $$$a_i = c^i$$$.Given a list of $$$n$$$ positive integers $$$a_0, a_1, ..., a_{n-1}$$$, you are allowed to:  Reorder the list (i.e. pick a permutation $$$p$$$ of $$$\{0,1,...,n - 1\}$$$ and change $$$a_i$$$ to $$$a_{p_i}$$$), then  Do the following operation any number of times: pick an index $$$i$$$ and change $$$a_i$$$ to $$$a_i - 1$$$ or $$$a_i + 1$$$ (i.e. increment or decrement $$$a_i$$$ by $$$1$$$) with a cost of $$$1$$$. Find the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

The first line contains an integer $$$n$$$ ($$$3 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum cost to transform $$$a_0, a_1, ..., a_{n-1}$$$ into a power sequence.

NoteIn the first example, we first reorder $$$\{1, 3, 2\}$$$ into $$$\{1, 2, 3\}$$$, then increment $$$a_2$$$ to $$$4$$$ with cost $$$1$$$ to get a power sequence $$$\{1, 2, 4\}$$$.

import scala.collection.mutable.ArrayBuffer

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

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

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

  def solve(): Unit = {
    val m     = in.nextInt()
    val data  = in.nextLineInt(m).sorted
    val lastIndex = m - 1
    val max   = data(lastIndex)

    val base1 = math.ceil(math.pow(max, 1d / lastIndex)).toInt
    val base2 = math.floor(math.pow(max, 1d / lastIndex)).toInt

    var sum1  = 0d
    var sum2  = 0d
    var i     = 0

    data.foreach(d => {
      val cur1 = Math.pow(base1, i)
      sum1 += Math.abs(d - cur1)

      val cur2 = Math.pow(base2, i)
      sum2 += Math.abs(d - cur2)
      i += 1
    })
    printf("%.0f\n", math.min(sum1, sum2))
//    println(math.min(sum1, sum2))
  }
  // 2000017493
  // 1999982505

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

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

import scala.collection.mutable.ArrayBuffer

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

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

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

  def solve(): Unit = {
    val m    = in.nextInt()
    val data = in.nextLineInt(m)
    val max  = data.max
//    val base = test3(20, 2)
    val base = test3(max, m - 1)
    var sum  = 0L
    var i    = 0
    // 1420172
    // 104639754
    // 83377718
//    println(base)
    data.sorted.foreach(d => {
      val cur = Math.pow(base, i)
      sum += Math.abs(cur - d).toLong
      i += 1
    })
    println(sum)
  }
  // 2000017493
  // 1999982505

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

  def test3(number: Int, e: Int) = {
    val sqrtNumber = Math.ceil(Math.sqrt(number)).toInt
    var minDiff    = Integer.MAX_VALUE.toDouble

    var targetExp  = 1
    var targetBase = 2
    1.to(sqrtNumber)
      .foreach(b => {
        val powerNumber = Math.pow(b, e)
        if (Math.abs(number.toDouble - powerNumber) < minDiff) {
          minDiff = number - powerNumber
          targetBase = b
          targetExp = e
        }
      })
//    println(targetBase, targetExp)
    targetBase
  }

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

import scala.collection.mutable.ArrayBuffer

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

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

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

  def solve(): Unit = {
    val m    = in.nextInt()
    val data = in.nextLineInt(m)
    val max  = data.max
    val base = test3(max, m - 1)
    var sum  = 0L
    var i    = 0
//    println(base)
    data.sorted.foreach(d => {
      val cur = Math.pow(base, i)
      sum += Math.abs(cur - d).toLong
      i += 1
    })
    println(sum)
  }
  // 2000017493
  // 1999982505

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

  def test3(number: Int, e: Int) = {
    val sqrtNumber = Math.sqrt(number).toInt
    var minDiff    = Integer.MAX_VALUE

    var targetExp  = 1
    var targetBase = 2
    2.until(sqrtNumber + 2)
      .foreach(b => {
        val powerNumber = Math.pow(b, e).toInt
        if (Math.abs(number - powerNumber) <= minDiff) {
          minDiff = number - powerNumber
          targetBase = b
          targetExp = e
        }
      })
//    println(targetBase, targetExp)
    targetBase
  }

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

import scala.collection.mutable.ArrayBuffer

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

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

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

  def solve(): Unit = {
    val m    = in.nextInt()
    val data = in.nextLineInt(m)
    val max  = data.max
    val base = test3(max, m - 1)
    var sum  = 0L
    var i    = 0
//    println(base)
    data.sorted.foreach(d => {
      val cur = Math.pow(base, i)
      sum += Math.abs(cur - d).toLong
      i += 1
    })
    println(sum)
  }
  // 2000017493
  // 1999982505

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

  def test3(number: Int, e: Int) = {
    val sqrtNumber = Math.ceil(Math.sqrt(number)).toInt
    var minDiff    = Integer.MAX_VALUE

    var targetExp  = 1
    var targetBase = 2
    1.to(sqrtNumber)
      .foreach(b => {
        val powerNumber = Math.pow(b, e).toInt
        if (Math.abs(number - powerNumber) <= minDiff) {
          minDiff = number - powerNumber
          targetBase = b
          targetExp = e
        }
      })
//    println(targetBase, targetExp)
    targetBase
  }

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

import scala.collection.mutable.ArrayBuffer

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

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

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

  def solve(): Unit = {
    val m     = in.nextInt()
    val data  = in.nextLineInt(m).sorted
    val lastIndex = m - 1
    val max   = data(lastIndex)

    val base1 = math.ceil(math.pow(max, 1d / lastIndex)).toInt
    val base2 = math.floor(math.pow(max, 1d / lastIndex)).toInt

    var sum1  = 0L
    var sum2  = 0L
    var i     = 0

    data.foreach(d => {
      val cur1 = Math.pow(base1, i)
      sum1 += Math.abs(d - cur1).toLong

      val cur2 = Math.pow(base2, i)
      sum2 += Math.abs(d - cur2).toLong
      i += 1
    })
    println(math.min(sum1, sum2))
  }
  // 2000017493
  // 1999982505

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

  /**
    * Util methods
    */

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

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

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

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

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

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

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

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

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

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

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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


An array of integers $$$p_{1},p_{2}, \ldots,p_{n}$$$ is called a permutation if it contains each number from $$$1$$$ to $$$n$$$ exactly once. For example, the following arrays are permutations: $$$[3,1,2], [1], [1,2,3,4,5]$$$ and $$$[4,3,1,2]$$$. The following arrays are not permutations: $$$[2], [1,1], [2,3,4]$$$.There is a hidden permutation of length $$$n$$$.For each index $$$i$$$, you are given $$$s_{i}$$$, which equals to the sum of all $$$p_{j}$$$ such that $$$j < i$$$ and $$$p_{j} < p_{i}$$$. In other words, $$$s_i$$$ is the sum of elements before the $$$i$$$-th element that are smaller than the $$$i$$$-th element.Your task is to restore the permutation.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^{5}$$$) — the size of the permutation. The second line contains $$$n$$$ integers $$$s_{1}, s_{2}, \ldots, s_{n}$$$ ($$$0 \le s_{i} \le \frac{n(n-1)}{2}$$$). It is guaranteed that the array $$$s$$$ corresponds to a valid permutation of length $$$n$$$.

Print $$$n$$$ integers $$$p_{1}, p_{2}, \ldots, p_{n}$$$ — the elements of the restored permutation. We can show that the answer is always unique.

NoteIn the first example for each $$$i$$$ there is no index $$$j$$$ satisfying both conditions, hence $$$s_i$$$ are always $$$0$$$.In the second example for $$$i = 2$$$ it happens that $$$j = 1$$$ satisfies the conditions, so $$$s_2 = p_1$$$.In the third example for $$$i = 2, 3, 4$$$ only $$$j = 1$$$ satisfies the conditions, so $$$s_2 = s_3 = s_4 = 1$$$. For $$$i = 5$$$ all $$$j = 1, 2, 3, 4$$$ are possible, so $$$s_5 = p_1 + p_2 + p_3 + p_4 = 10$$$.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val S = nal(N)
    val ans = Array.ofDim[Int](N)
    val bit = new BIT(N + 1)
    REP(N, 1) { i =>
      bit.add(i, i)
    }

    REP_r(N) { i =>
      val a = bit.lowerBound(S(i) + 1)
      bit.add(a, -a)
      ans(i) = a
    }
    debug(ans)

    out.println(ans.mkString(" "))
  }

  class BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {
    def this(n: Int) = this(n, 0)(_ + _)

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)

    /**
      * 1 index
      * addとindex違うよ
      * cumsumなんかといっしょ
      */
    def sum(i: Int): Long = {
      assert(i <= n)
      var x = i
      var s: Long = zero
      while(x > 0) {
        s = f(s, bit(x))
        x -= x & -x
      }
      s
    }

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

    def sumAll: Long = sum(n)

    // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない
    private def sub(a: Long, b: Long) = a - b
    private def lt(a: Long, b: Long) = a < b

    /**
      * [l, r)
      */
    def query(l: Int, r: Int): Long = {
      assert(r > l)
      sub(sum(r), sum(l))
    }

    def lowerBound(W: Long): Int = {
      var k = N
      var x = 0
      var w = W
      while(k > 0) {
        if (x + k <= N && lt(bit(x + k), w)) {
          w = sub(w, bit(x + k))
          x += k
        }
        k /= 2
      }
      math.min(n, x)
    }
  }
}

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

  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- 1 until src.length) update(i, src(i))

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

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def binSearch(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) <= goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT((0L to n).toArray)

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {
    val a = bit.binSearch(ss(i))
    as(i) = a
    bit.update(a, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}

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

  class BIT(src: Array[Long]) {

    val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

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

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

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

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT((0L to n).toArray)

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {

    val s = ss(i)

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (bit.query(mid.toInt) > s) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }
    val a = binSearch(0, n)
    as(i) = a
    bit.update(a.toInt, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}

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

  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length + 1) { 0L }

    for (i <- src.indices) update(i + 1, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r <= 0) acc else query(r - (r & -r), acc + t(r))

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit = {
      if (i < t.length) {
        t(i) += delta
        update(i + (i & -i), delta)
      }
    }

    def binSearch(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx < t.length && sum + t(newIdx) <= goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx + 1
    }

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT(Array.tabulate(n)(_ + 1))

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {
    val a = bit.binSearch(ss(i))
    as(i) = a
    bit.update(a, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}

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

  final class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

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

    def rangeQuery(l: Int, r: Int): Long = query(r) - query(l - 1)

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

    def binSearch(goal: Long): Int = {
      var sum = 0L
      var idx = 0
      var bitMask = Integer.highestOneBit(t.length - 1)
      while (bitMask > 0) {
        val newIdx = idx + bitMask
        if (newIdx <= t.length && sum + t(newIdx - 1) <= goal) {
          idx = newIdx
          sum += t(idx)
        }
        bitMask >>>= 1
      }
      idx
    }

  }

  val Array(n) = readInts(1)
  val ss = readLongs(n)

  val bit = new BIT((0L to n).toArray)

  val as = Array.ofDim[Long](n)

  for (i <- ss.indices.reverse) {
    val a = bit.binSearch(ss(i))
    as(i) = a
    bit.update(a, -a)
  }

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

  println(as.mkString(" "))

  Console.flush
}


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations:  Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$).  Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9$$$) — the length of $$$a$$$ and the required divisior. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$.

NoteConsider the first test case of the example:  $$$x=0$$$, $$$a = [1, 2, 1, 3]$$$. Just increase $$$x$$$;  $$$x=1$$$, $$$a = [1, 2, 1, 3]$$$. Add $$$x$$$ to the second element and increase $$$x$$$;  $$$x=2$$$, $$$a = [1, 3, 1, 3]$$$. Add $$$x$$$ to the third element and increase $$$x$$$;  $$$x=3$$$, $$$a = [1, 3, 3, 3]$$$. Add $$$x$$$ to the fourth element and increase $$$x$$$;  $$$x=4$$$, $$$a = [1, 3, 3, 6]$$$. Just increase $$$x$$$;  $$$x=5$$$, $$$a = [1, 3, 3, 6]$$$. Add $$$x$$$ to the first element and increase $$$x$$$;  $$$x=6$$$, $$$a = [6, 3, 3, 6]$$$. We obtained the required array. Note that you can't add $$$x$$$ to the same element more than once.

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/D
 */
object ZeroRemainderArray {
  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to io.StdIn.readInt()) yield {
          val Array(_, k) = io.StdIn.readLine.split(" ").map(_.toLong)

          val arr = io.StdIn.readLine.split(" ").map { ai =>
            val r = ai.toLong % k
            if (r == 0) 0 else k - r
          }.groupBy(identity) // minimum amount need to make divisible by k

          arr.foldLeft(0L) { case (acc, (i, is)) =>
            val c = is.length
            if (i == 0) acc else acc max (i + (c - 1) * k + 1)
          }
        }
      }.mkString("\n")
    }
  }
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CF653A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val k = ni()

      val a = na(n).filter(p => p % k != 0)
      if(a.length == 0) {
        out.println("0")
      } else {
        val r = a.map(f => k - f % k).groupBy(f => f).map(f => f._1 -> f._2.length)
        val v = r.values.max
        val u = r.filter(p => p._2 == v).keys.max

        out.println((v-1)*k.toLong + u + 1)
      }
    }
  }

}

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/D
 */
object ZeroRemainderArray {
  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to io.StdIn.readInt()) yield {
          val Array(_, k) = io.StdIn.readLine.split(" ").map(_.toInt)
          val queue = collection.mutable.PriorityQueue.empty[Int](Ordering.Int.reverse)

          io.StdIn.readLine.split(" ").foreach { ai =>
            val r = ai.toInt % k
            queue.enqueue(if (r == 0) 0 else k - r)
          } // minimum amount need to make divisible by k

          @scala.annotation.tailrec
          def loop(x: Long = 0): Long = {
            if (queue.isEmpty) x
            else {
              val ai = queue.dequeue()

              if (ai == 0) loop(x)
              else if (x > ai) {
                queue.enqueue(ai + k)
                loop(x)
              } else // (x < ai)
                loop(ai + 1)
            }
          }

          loop()
        }
      }
    }
  }
}


The Central Company has an office with a sophisticated security system. There are $$$10^6$$$ employees, numbered from $$$1$$$ to $$$10^6$$$.The security system logs entrances and departures. The entrance of the $$$i$$$-th employee is denoted by the integer $$$i$$$, while the departure of the $$$i$$$-th employee is denoted by the integer $$$-i$$$.The company has some strict rules about access to its office:  An employee can enter the office at most once per day.  He obviously can't leave the office if he didn't enter it earlier that day.  In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day. Any array of events satisfying these conditions is called a valid day.Some examples of valid or invalid days:  $$$[1, 7, -7, 3, -1, -3]$$$ is a valid day ($$$1$$$ enters, $$$7$$$ enters, $$$7$$$ leaves, $$$3$$$ enters, $$$1$$$ leaves, $$$3$$$ leaves).  $$$[2, -2, 3, -3]$$$ is also a valid day.  $$$[2, 5, -5, 5, -5, -2]$$$ is not a valid day, because $$$5$$$ entered the office twice during the same day.  $$$[-4, 4]$$$ is not a valid day, because $$$4$$$ left the office without being in it.  $$$[4]$$$ is not a valid day, because $$$4$$$ entered the office and didn't leave it before the end of the day. There are $$$n$$$ events $$$a_1, a_2, \ldots, a_n$$$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.You must partition (to cut) the array $$$a$$$ of events into contiguous subarrays, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.For example, if $$$n=8$$$ and $$$a=[1, -1, 1, 2, -1, -2, 3, -3]$$$ then he can partition it into two contiguous subarrays which are valid days: $$$a = [1, -1~ \boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$$$.Help the administrator to partition the given array $$$a$$$ in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$ and $$$a_i \neq 0$$$).

If there is no valid partition, print $$$-1$$$. Otherwise, print any valid partition in the following format:   On the first line print the number $$$d$$$ of days ($$$1 \le d \le n$$$).  On the second line, print $$$d$$$ integers $$$c_1, c_2, \ldots, c_d$$$ ($$$1 \le c_i \le n$$$ and $$$c_1 + c_2 + \ldots + c_d = n$$$), where $$$c_i$$$ is the number of events in the $$$i$$$-th day.  If there are many valid solutions, you can print any of them. You don't have to minimize nor maximize the number of days.

NoteIn the first example, the whole array is a valid day.In the second example, one possible valid solution is to split the array into $$$[1, -1]$$$ and $$$[1, 2, -1, -2, 3, -3]$$$ ($$$d = 2$$$ and $$$c = [2, 6]$$$). The only other valid solution would be to split the array into $$$[1, -1]$$$, $$$[1, 2, -1, -2]$$$ and $$$[3, -3]$$$ ($$$d = 3$$$ and $$$c = [2, 4, 2]$$$). Both solutions are accepted.In the third and fourth examples, we can prove that there exists no valid solution. Please note that the array given in input is not guaranteed to represent a coherent set of events.

import sun.invoke.empty.Empty

object B1253 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer

  def main(args: Array[String]): Unit = {
    var tests = 1 // readInt
    while (tests > 0) {
      val Array(n) = readInts(1)
      val a = readInts(n)
      val set = cu.HashSet.empty[Int]
      var map = cu.Map.empty[Int, Boolean] //count for day
      var res = 0
      var resPos = ArrayBuffer.empty[Int]
      var break = false
      var i = 0
      var last = 0
      while (i < n && !break) {
        if (a(i) < 0) {
          if (!set.contains(-a(i)))
            break = true
          else {
            set.remove(-a(i))
            map.put(-a(i), true)
            if (set.isEmpty) {
              resPos.append(i - last + 1)
              last = i + 1
              map = cu.Map.empty[Int, Boolean]
              res += 1
            }
          }
        } else {
          if (set.contains(a(i)) || map.contains(a(i))) {
            break = true
          } else {
            set.add(a(i))
          }
        }
        i += 1
      }
      if (break || set.nonEmpty) {
        out.println(-1)
      } else {
        out.println(res)
        out.println(resPos.mkString(" "))
      }
      tests -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.collection.mutable

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

  val n = nextInt
  val as = nextInts(n)
  val resBuilder = new mutable.ArrayBuilder.ofInt

  var count = 0
  val inside, entered = mutable.HashSet.empty[Int]
  var bad = false
  for (a <- as) {
    count += 1
    if (a < 0) {
      if (!inside.remove(-a)) bad = true
    } else {
      if (!inside.add(a) || entered(a)) bad = true
      entered.add(a)
    }
    if (inside.isEmpty) {
      resBuilder += count
      entered.clear()
      count = 0
    }
  }

  if (inside.nonEmpty || bad) println(-1)
  else {
    val res = resBuilder.result()
    out.println(res.length)
    out.println(res.mkString(" "))
  }
  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
  }
}


Bob has a string $$$s$$$ consisting of lowercase English letters. He defines $$$s'$$$ to be the string after removing all "a" characters from $$$s$$$ (keeping all other characters in the same order). He then generates a new string $$$t$$$ by concatenating $$$s$$$ and $$$s'$$$. In other words, $$$t=s+s'$$$ (look at notes for an example).You are given a string $$$t$$$. Your task is to find some $$$s$$$ that Bob could have used to generate $$$t$$$. It can be shown that if an answer exists, it will be unique.

The first line of input contains a string $$$t$$$ ($$$1 \leq |t| \leq 10^5$$$) consisting of lowercase English letters.

Print a string $$$s$$$ that could have generated $$$t$$$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).

NoteIn the first example, we have $$$s = $$$ "aaaaa", and $$$s' = $$$ "".In the second example, no such $$$s$$$ can work that will generate the given $$$t$$$.In the third example, we have $$$s = $$$ "ababacac", and $$$s' = $$$ "bbcc", and $$$t = s + s' = $$$ "ababacacbbcc".

object B extends App {

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

  val t = readLine

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

  val pref = new StringBuilder
  var ok = false

  for (i <- 0 until t.length) {
    if (t(i) != 'a') pref += t(i)
    if (i + pref.length + 1 == t.length) {
      val s = pref.result()
      if (s == t.drop(i + 1)) {
        ok = true
        println(t.take(i + 1))
      }
    }
  }

  if (!ok) println(":(")

  Console.flush
}

import scala.io.StdIn

object Codeforces1146B {

  val noAnswer = ":("

  def removeA(string: String): String = {
    val stringBuilder = new StringBuilder()
    for (char <- string)
      if (char != 'a') stringBuilder.append(char)

    stringBuilder.toString()
  }

  def isTwoEqual(string: String): Boolean = {
    if (string.length % 2 != 0) return false
    val nextStart = string.length / 2
    for (i <- 0 until nextStart) {
      if (string(i) != string(nextStart + i)) return false
    }
    true
  }

  def getOriginalString(t: String): String = {
    val aRemoved = removeA(t)
    if (isTwoEqual(aRemoved)) {
      val secondPart = aRemoved.substring(aRemoved.length / 2)
      if (t.endsWith(secondPart))
        return t.substring(0, t.length - secondPart.length)
    }
    noAnswer
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().trim
    val s = getOriginalString(t)
    println(s)
  }
}


Two players decided to play one interesting card game.There is a deck of $$$n$$$ cards, with values from $$$1$$$ to $$$n$$$. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card. The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.For example, suppose that $$$n = 5$$$, the first player has cards with values $$$2$$$ and $$$3$$$, and the second player has cards with values $$$1$$$, $$$4$$$, $$$5$$$. Then one possible flow of the game is:The first player chooses the card $$$3$$$. The second player chooses the card $$$1$$$. As $$$3>1$$$, the first player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$, $$$3$$$, the second player has cards $$$4$$$, $$$5$$$.The first player chooses the card $$$3$$$. The second player chooses the card $$$4$$$. As $$$3<4$$$, the second player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$. The second player has cards $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$1$$$. The second player chooses the card $$$3$$$. As $$$1<3$$$, the second player gets both cards. Now the first player has only the card $$$2$$$. The second player has cards $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$2$$$. The second player chooses the card $$$4$$$. As $$$2<4$$$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$, $$$k_2$$$ ($$$2 \le n \le 100, 1 \le k_1 \le n - 1, 1 \le k_2 \le n - 1, k_1 + k_2 = n$$$) — the number of cards, number of cards owned by the first player and second player correspondingly. The second line of each test case contains $$$k_1$$$ integers $$$a_1, \dots, a_{k_1}$$$ ($$$1 \le a_i \le n$$$) — the values of cards of the first player. The third line of each test case contains $$$k_2$$$ integers $$$b_1, \dots, b_{k_2}$$$ ($$$1 \le b_i \le n$$$) — the values of cards of the second player. It is guaranteed that the values of all cards are different.

For each test case, output "YES" in a separate line, if the first player wins. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).

NoteIn the first test case of the example, there is only one possible move for every player: the first player will put $$$2$$$, the second player will put $$$1$$$. $$$2>1$$$, so the first player will get both cards and will win.In the second test case of the example, it can be shown that it is the second player who has a winning strategy. One possible flow of the game is illustrated in the statement.

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

  for (_ <- 1 to nextInt) {
    val n, k1, k2 = nextInt
    val as = nextInts(k1)
    val bs = nextInts(k2)
    val res = if (as.max > bs.max) "YES" else "NO"

    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 Main {

    def main(args: Array[String]): Unit = {
        import scala.io.StdIn.readLine
        import scala.io.StdIn.readInt

        var T: Int = readInt
        for(t <- 0 until T) {
            var Array(n, m, k) = readLine.split(" ").map(_.toInt)
            var A = readLine.split(" ").map(_.toInt)
            var B = readLine.split(" ").map(_.toInt)

            if(A.contains(n))   println("YES")
            else    println("NO")
        }
    }

}


One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?

The first line contains two integers n and b (1 ≤ n, b ≤ 2000) — the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≤ ai ≤ 2000) — the prices of Martian dollars.

Print the single number — which maximal sum of money in bourles can Vasya get by the end of day n.

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, b) = readLine.split(" ").map(_.toInt);
    var a = readLine.split(" ").map(_.toInt);
    var best = b;
    for (i <- 0 until a.length; j <- i + 1 until a.length) {
      var countM = b / a(i);
      var mod = b % a(i);
      best = math.max(best, countM * a(j) + mod);
    }
    println(best);
  }
}


Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot.The robot has instructions — the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number 0. If the robot should go into the cell with an obstacle according the instructions, it will skip this move.Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once — at its last move. Moreover, the latter move cannot be skipped.Let's assume that k is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose k obstacles and the finishing cell so that the robot is able to complete the instructions successfully.

The first line contains a sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), consisting only of letters "L" and "R". If character si equals "L", then the robot on the i-th move must try to move one cell to the left. If the si-th character equals "R", then the robot on the i-th move must try to move one cell to the right.

Print a single integer — the required number of ways. It's guaranteed that this number fits into 64-bit signed integer type.

NoteIn the first sample Valera mustn't add any obstacles and his finishing cell must be cell 2.In the second sample, Valera must add an obstacle in cell number 1, and his finishing cell must be cell number  - 1. In this case robot skips the first two moves and on the third move he goes straight from the starting cell to the finishing one. But if Valera doesn't add any obstacles, or adds an obstacle to another cell, then the robot visits the finishing cell more than once.

object Main {
  def inverse(ch: Char) = {
      ch match {
        case 'R' => 'L'
        case 'L' => 'R'
      }
  }

  def check(s: String, tape: Array[Int]) = {
    var pointer = s.length
    for (ch <- s) {
      if (ch == 'L') {
        if (tape(pointer - 1) != -1) {
          tape(pointer - 1) += 1
          pointer -= 1
        }
      }
      else if (ch == 'R') {
        if (tape(pointer + 1) != -1) {
          tape(pointer + 1) += 1
          pointer += 1
        }
      }
    }
    if (pointer != s.length && tape(pointer) == 1) true else false
  }

  def main(args: Array[String]) {
    val in = readLine()

    val s = if (in.last == 'L') in.map(inverse) else in

    var tape = new Array[Int](2 * s.length + 1)
    if (check(s, tape)) {
      println("1")
      return
    }

    var l = 0
    var r = s.length
    var ans = 0
    while (l < r) {
      tape = new Array[Int](2 * s.length + 1)
      var m = (l + r) / 2
      tape(m) = -1
      if (check(s, tape)) {
        r = m
        ans = s.length - m
      }
      else {
        l = m + 1
      }
    }
    println(ans)
  }
}