A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:  ai ≥ ai - 1 for all even i,  ai ≤ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.Can you make the array z-sorted?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

If it's possible to make the array a z-sorted print n space separated integers ai — the elements after z-sort. Otherwise print the only word "Impossible".

import java.util

import scala.collection.JavaConverters._

object ZSort {
  // https://codeforces.com/problemset/problem/652/B
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)

    if (n == 1) {
      println(arr.mkString)
    } else {
      val newArr = new util.ArrayList[Int](n)
      arr.zipWithIndex.foreach { case (curr, i) =>
        if (i == 0) {
          newArr.add(arr.head)
        } else {
          val prev = newArr.get(i - 1)
          if ((i + 1) % 2 == 0) {
            // even
            if (curr < prev) {
              newArr.add(prev)
              newArr.set(i - 1, curr)
            } else {
              newArr.add(curr)
            }
          } else {
            // odd
            if (curr > prev) {
              newArr.add(prev)
              newArr.set(i - 1, curr)
            } else {
              newArr.add(curr)
            }
          }
        }
      }

      println(newArr.asScala.mkString(" "))
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).sorted
  val first = data.take(n / 2 + n % 2)
  val second = data.drop(first.length)
  val result = Array.ofDim[Int](n)
  (0 until n by 2).foreach { i =>
    result(i) = first(i / 2)
  }
  (1 until n by 2).foreach { i =>
     result(i) = second(i / 2)
  }
  println(result.mkString(" "))
}


Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.

The first line contains two integers n and k (2 ≤ n ≤ 2·105, 0 < 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1, x2, ..., xn — the absurdity of each law (1 ≤ xi ≤ 109).

Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.

NoteIn the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toLong)
  val sliding = Array.ofDim[Long](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0l){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0l) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k) == max
  }.get

//  println(sliding.toList)
//  println(partSum.toList)
//  println(index)
//  println(partSum(index + k))

  val j = ((index + k) until sliding.length).find(i => sliding(i) == partSum(index + k)).get

  println(s"${index + 1} ${j + 1}")
}

import java.util._
import java.lang._
import java.io._

/**
 * @author kperikov
 */
object B_332 {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def partialSum(ints: Array[Int]): Array[Long] = {
    val sums = new Array[Long](ints.length)
    sums(0) = ints(0)
    for (i <- 1 until ints.length) {
      sums(i) = sums(i - 1) + ints(i)
    }
    sums
  }

  def sum(ints: Array[Long], x: Int, y: Int): Long = {
    x match {
      case 0 => ints(y)
      case _ => ints(y) - ints(x - 1)
    }
  }

  def solve = {
    val n = nextInt
    val k = nextInt
    val arr = new Array[Int](n)
    for (i <- 0 until n) {
      arr(i) = nextInt
    }
    val partialSums = partialSum(arr)
    var ans = (n - 2 * k, n - k)
    var max = sum(partialSums, n - 2 * k, n - k - 1) + sum(partialSums, n - k, n - 1)
    var suff = (n - k, sum(partialSums, n - k, n - 1))
    for (i <- n - 2 * k - 1 to 0 by -1) {
      var current = sum(partialSums, i + k, i + 2 * k - 1)
      if (current >= suff._2)
        suff = (i + k, current)
      current = sum(partialSums, i, i + k - 1) + suff._2
      if (current >= max) {
        max = current
        ans = (i, suff._1)
      }
    }
    println((ans._1 + 1) + " " + (ans._2 + 1))
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }

}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Long](n)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Long](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) = best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, father(k))
    var absurdity = sums(0) + best(k)

    for(i <- 1 to (n - 2 * k))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object Main332B {
  def readInts = readLine.split(" ")map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, k) = readInts
    val arr = readInts
    val sums = Array.ofDim[BigInt](n)
    var currentSum = BigInt(0)
    for (i <- (n-1) to 0 by -1) {
      currentSum += arr(i)
      if (i < n-k) currentSum -= arr(i+k)
      sums(i) = currentSum
    }
    var maxB = n-k
    var resA = n-k*2
    var resB = n-k
    for(a <- n-2*k to 0 by -1) {
      if(sums(a+k) >= sums(maxB)) maxB = a+k
      if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {
        resA = a
        resB = maxB
      }
    }
    println((resA+1) + " " + (resB+1))
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val sliding = Array.ofDim[Int](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k - 1))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k - 1) == max
  }.get

  val j = ((index + k - 1) until sliding.length).find(i => sliding(i) == partSum(index + k - 1)).get

  println(max)
  println(line.toList)
  println(sliding.toList)
  println(partSum.toList)
  println(s"$index $j")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val sliding = Array.ofDim[Int](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k - 1))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k - 1) == max
  }.get

  val j = ((index + k - 1) until sliding.length).find(i => sliding(i) == partSum(index + k - 1)).get

  println(s"$index $j")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val sliding = Array.ofDim[Int](n - k + 1)
  sliding(0) = line.take(k).sum

  (k until n).foreach { i => sliding(i - k + 1) = sliding(i - k) + line(i) - line(i - k) }
  val partSum = sliding.reverse.scanLeft(0){ case(a, b) => Math.max(a, b) }.tail.reverse
  val max = (0 until sliding.length - k).foldLeft(0) {
    case(max, i) =>
      Math.max(max, sliding(i) + partSum(i + k))
  }

  val index = (0 until sliding.length - k).find {
    i => sliding(i) + partSum(i + k) == max
  }.get

//  println(sliding.toList)
//  println(partSum.toList)
//  println(index)
//  println(partSum(index + k))

  val j = ((index + k) until sliding.length).find(i => sliding(i) == partSum(index + k)).get

  println(s"${index + 1} ${j + 1}")
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Long](n)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Long](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) =best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, 0)
    var absurdity = 0 : Long

    for(i <- 0 until (n - 2 * k + 1))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Int](n + 1)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Int](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) =best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, 0)
    var absurdity = 0

    for(i <- 0 until (n - 2 * k + 1))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Int](n + 1)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Int](n + 1)
    val father = new Array[Int](n + 1)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 to (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) =best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, 0)
    var absurdity = 0

    for(i <- 0 until (n - 2 * k))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object main {
  def main (args : Array[String]) {
    val line = readLine() split " " map (_.toInt)
    val n = line(0)
    val k = line(1)
    val a = readLine() split " " map (_.toInt)

    val sums = new Array[Long](n)

    sums(0) = a.take(k).sum
    for(i <- k until n)
      sums(i - k + 1) = sums(i - k) - a(i - k) + a(i)

    val best = new Array[Long](n)
    val father = new Array[Int](n)

    best(n - k) = sums(n - k)
    father(n - k) = n - k
    for(i <- (0 until (n - k)) reverse)
      if(best(i + 1) > sums(i)) {
        best(i) = best(i + 1)
        father(i) = father(i + 1)
      }
      else {
        best(i) = sums(i)
        father(i) = i
      }

    var answer = (0, k)
    var absurdity = sums(0) + best(k)

    for(i <- 1 to (n - 2 * k))
      if(absurdity < sums(i) + best(i + k)) {
        absurdity = sums(i) + best(i + k)
        answer = (i, father(i + k))
      }

    println((answer._1 + 1) + " " + (answer._2 + 1))
  }
}

object Main332B {
  def readInts = readLine.split(" ")map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, k) = readInts
    val arr = readInts
    val sums = Array.ofDim[Int](n)
    var currentSum = 0
    for (i <- (n-1) to 0 by -1) {
      currentSum += arr(i)
      if (i < n-k) currentSum -= arr(i+k)
      sums(i) = currentSum
    }
    var maxB = n-k
    var resA = n-k*2
    var resB = n-k
    for(a <- n-2*k to 0 by -1) {
      if(sums(a+k) >= sums(maxB)) maxB = a+k
      if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {
        resA = a
        resB = maxB
      }
    }
    println((resA+1) + " " + (resB+1))
  }

}

object Main332B {
  def readInts = readLine.split(" ")map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, k) = readInts
    val arr = readInts
    val sums = Array.ofDim[Long](n)
    var currentSum = 0
    for (i <- (n-1) to 0 by -1) {
      currentSum += arr(i)
      if (i < n-k) currentSum -= arr(i+k)
      sums(i) = currentSum
    }
    var maxB = n-k
    var resA = n-k*2
    var resB = n-k
    for(a <- n-2*k to 0 by -1) {
      if(sums(a+k) >= sums(maxB)) maxB = a+k
      if(sums(a) + sums(maxB) >= sums(resA) + sums(resB)) {
        resA = a
        resB = maxB
      }
    }
    println((resA+1) + " " + (resB+1))
  }

}


You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".Determine the minimum number of moves needed to make some table column consist only of numbers 1.

The first line contains two space-separated integers: n (1 ≤ n ≤ 100) — the number of rows in the table and m (1 ≤ m ≤ 104) — the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1".

Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.

NoteIn the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.In the second sample one can't shift the rows to get a column containing only 1s.

import scala.io.StdIn._
import scala.language.postfixOps
import scala.math.min

object TaskC extends App {
  val MaxValue = 1e9 toInt
  val MinValue = -MaxValue
  val n :: m :: Nil = readLine.split(" ").map(_.toInt).toList

  val table = 1 to n map (_ => readLine.split("").map(_.toInt)) toArray

  val ones = Array.fill(n)(Array.fill(m)(MaxValue))

  for(i <- 0 until n){
    val first = table(i).indexOf(1)
    val last = table(i).lastIndexOf(1)

    var lastTraversed = MinValue
    for(j <- 0 until m) {
      if (table(i)(j) == 0) {
        ones(i)(j) = min(j - lastTraversed, j + m - last)
      } else {
        ones(i)(j) = 0
        lastTraversed = j
      }
    }

    lastTraversed = MaxValue
    for (j <- 0 until m reverse) {
      if (table(i)(j) == 0) {
        ones(i)(j) = min(ones(i)(j), min(lastTraversed - j, m - j + first))
      } else {
        lastTraversed = j
      }
    }
  }

  println(if (table.forall(_.contains(1))) countMoves else -1)

  def countMoves = 0 until m map(j => 0 until n map(i => ones(i)(j)) sum) min
}


Two players play a game.Initially there are $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $$$n - 1$$$ turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after $$$n - 1$$$ turns if both players make optimal moves.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of numbers on the board. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$).

Print one number that will be left on the board.

NoteIn the first sample, the first player erases $$$3$$$ and the second erases $$$1$$$. $$$2$$$ is left on the board.In the second sample, $$$2$$$ is left on the board regardless of the actions of the players.

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine.toInt
    val a = StdIn.readLine.split(" ").map(_.toInt).sorted
    println(a((a.length - 1) / 2))
  }
}

import scala.io.StdIn

object A extends App {

  val numbers = {
    StdIn.readLine()
    StdIn.readLine().split(" ").map(_.toInt)
  }.sorted

  val numbersCount = numbers.length

  val numberIndex = if (numbersCount % 2 == 0) {
    (numbersCount / 2) - 1
  } else {
    numbersCount / 2
  }
  println(numbers(numberIndex))
}

import scala.io.StdIn

object Game extends App {

  val n = StdIn.readInt()
  val arr = StdIn.readLine().split(" ").map(_.toInt)

  print(impl(n, arr))

  def impl(n: Int, arr: Array[Int]): Int = {
    val sorted: Array[Int] = arr.sorted.reverse
    sorted(n / 2)
  }
}

object A extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _)

  println(a(n / 2))
}

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

  override def apply(io: IO): io.type = {
    val as = io.read[Vector[Int]].sorted
    val ans = as((as.length - 1)/2)
    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 apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[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")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

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

import scala.io.StdIn

object A extends App {

  val numbers = {
    StdIn.readLine()
    StdIn.readLine().split(" ").map(_.toInt)
  }.sorted

  val numbersCount = numbers.length

  val numberIndex = numbersCount / 2

  println(numbers(numberIndex))
}

object A extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

  println(a(n / 2))
}


"You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it?

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For every test case print one non-negative integer — the answer to the problem.

NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs.

import scala.io.StdIn._

object Main {
  def getMS(b: Int): Int = {
    var k = 0;
    var a = b;
    while(a > 0) {
      a = (a >> 1);
      k = k + 1;
    }
    k
  }
  def main(args: Array[String]): Unit = {
    val t = readInt
    (0 until t).foreach { _ =>
      val n = readInt
      val a = readLine.split(" ").map(_.toInt)
      val result: Long = a.groupBy(getMS(_)).map { case (a, b) => (b.size.toLong * (b.size.toLong - 1)) / 2 }.sum
      println(result)
    }
  }
}

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

  def higher(a: Int): Int = {
    @annotation.tailrec
    def go(h: Int): Int = if (1 << h > a) h else go(h + 1)
    go(1)
  }

  val t = readInt()

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

    val bits = Array.fill(32)(0)

    val ans = an.foldLeft(0L) {
      case (count, h) =>
        bits(h) += 1
        count + bits(h) - 1
    }

    println(ans)
  }
}


Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1 / 4, and the problem's maximum point value is equal to 1500.If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses x / 250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000·(1 - 40 / 250) = 1680 points for this problem.There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.Unfortunately, Vasya is a cheater. He has registered 109 + 7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.

The first line contains a single integer n (2 ≤ n ≤ 120) — the number of round participants, including Vasya and Petya. Each of the next n lines contains five integers ai, 1, ai, 2..., ai, 5 ( - 1 ≤ ai, j ≤ 119) — the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j. It is guaranteed that each participant has made at least one successful submission. Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order.

Output a single integer — the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal.

NoteIn the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980 + 940 + 420 + 360 + 270 = 2970 points, while Petya will score just 800 + 820 + 420 + 440 + 470 = 2950 points.In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points.In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one.

object D 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 countSolved = Array.fill(5)(0)

  val as = Array.fill(n) {
    val aas = readInts(5)
    for (i <- 0 until 5) if (aas(i) >= 0) countSolved(i) += 1
    aas
  }

  var res = Long.MaxValue

  val levelScore = Array(3000, 2500, 2000, 1500, 1000, 500).reverse

  val problemLevel = Array.fill(5)(0)

  def vasyaWins(): Boolean = {
    var vasyaScore, petyaScore = 0L
    for (i <- 0 until 5) {
      val score = levelScore(problemLevel(i))
      if (as(0)(i) >= 0) vasyaScore += score - score * as(0)(i) / 250
      if (as(1)(i) >= 0) petyaScore += score - score * as(1)(i) / 250
    }
    vasyaScore > petyaScore
  }

  def can(budget: Long): Boolean = {
    var ok = true
    var minBudget = 0
    for (i <- 0 until 5) {
      val level = problemLevel(i)
      if (countSolved(i) > 0 && as(0)(i) != -1) {
        val l1 = 1 << level
        val bb = if (l1 == 1) 0 else l1 * countSolved(i) - n
        if (bb > minBudget) minBudget = bb
        if (!(countSolved(i) * (1 << level) <= n + budget &&
          (countSolved(i) + budget) * (2 << level) > n + budget)) ok = false
      }
    }
    for (i <- 0 until 5) {
      val level = problemLevel(i)
      if (countSolved(i) > 0 && as(0)(i) == -1) {
        if (!(countSolved(i) * (1 << level) <= n + budget &&
          countSolved(i) * (2 << level) > n + minBudget)) ok = false
      }
    }
    ok
  }

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def combinations(problem: Int): Unit = {
    if (problem == 5) {
      if (vasyaWins()) {
        val r = binSearch(0, 1000000007)
        if (r < res) res = r
      }
    } else {
      for (level <- 0 until 6) {
        problemLevel(problem) = level
        combinations(problem + 1)
      }
    }
  }

  combinations(0)

  if (res > 1000000007) res = -1

  println(res)
}

object D 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 countSolved = Array.fill(5)(0)

  val as = Array.fill(n) {
    val aas = readInts(5)
    for (i <- 0 until 5) if (aas(i) >= 0) countSolved(i) += 1
    aas
  }

  var res = Long.MaxValue

  val levelScore = Array(3000, 2500, 2000, 1500, 1000, 500).reverse

  val problemLevel = Array.fill(5)(0)

  def vasyaWins(): Boolean = {
    var vasyaScore, petyaScore = 0L
    for (i <- 0 until 5) {
      val score = levelScore(problemLevel(i))
      if (as(0)(i) >= 0) vasyaScore += score - score * as(0)(i) / 250
      if (as(1)(i) >= 0) petyaScore += score - score * as(1)(i) / 250
    }
    vasyaScore > petyaScore
  }

  def can(budget: Long): Boolean = {
    var ok = true
    var minBudget = 0
    for (i <- 0 until 5) {
      val level = problemLevel(i)
      if (countSolved(i) > 0 && as(0)(i) != -1) {
        val l1 = 1 << level
        val bb = if (l1 == 1) 0 else l1 * countSolved(i) - n //(n - countSolved(i) * l1) / (l1 - 1)
        if (bb > minBudget) minBudget = bb
        if (!(countSolved(i) * (1 << level) <= n + budget &&
          (countSolved(i) + budget) * (2 << level) > n + budget)) ok = false
      }
    }
    for (i <- 0 until 5) {
      val level = problemLevel(i)
      if (countSolved(i) > 0 && as(0)(i) == -1) {
        if (!(countSolved(i) * (1 << level) <= n + budget &&
          countSolved(i) * (2 << level) > n + minBudget)) ok = false
      }
    }
    ok
  }

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def combinations(problem: Int): Unit = {
    if (problem == 5) {
      if (vasyaWins()) {
        val r = binSearch(0, 1000000007)
        if (r < res) res = r
      }
    } else {
      for (level <- 0 until 6) {
        problemLevel(problem) = level
        combinations(problem + 1)
      }
    }
  }

  combinations(0)

  if (res == Long.MaxValue) res = -1

  println(res)
}

object D 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 countSolved = Array.fill(5)(0)

  val as = Array.fill(n) {
    val aas = readInts(5)
    for (i <- 0 until 5) if (aas(i) >= 0) countSolved(i) += 1
    aas
  }

  var res = Long.MaxValue

  val levelScore = Array(3000, 2500, 2000, 1500, 1000, 500).reverse

  val problemLevel = Array.fill(5)(0)

  def vasyaWins(): Boolean = {
    var vasyaScore, petyaScore = 0L
    for (i <- 0 until 5) {
      val score = levelScore(problemLevel(i))
      if (as(0)(i) >= 0) vasyaScore += score - score * as(0)(i) / 250
      if (as(1)(i) >= 0) petyaScore += score - score * as(1)(i) / 250
    }
    vasyaScore > petyaScore
  }

  def can(budget: Long): Boolean = {
    var ok = true
    var minBudget = 0
    for (i <- 0 until 5) {
      val level = problemLevel(i)
      if (countSolved(i) > 0 && as(0)(i) != -1) {
        val l1 = 1 << level
        val bb = if (l1 == 1) 0 else l1 * countSolved(i) - n //(n - countSolved(i) * l1) / (l1 - 1)
        if (bb > minBudget) minBudget = bb
        if (!(countSolved(i) * (1 << level) <= n + budget &&
          (countSolved(i) + budget) * (2 << level) > n + budget)) ok = false
       // println(i, level, levelScore(level), countSolved(i), ok, bb)
      }
    }
    for (i <- 0 until 5) {
      val level = problemLevel(i)
      if (countSolved(i) > 0 && as(0)(i) == -1) {
        if (!(countSolved(i) * (1 << level) <= n + budget &&
          countSolved(i) * (2 << level) > n + minBudget)) ok = false
        //println(i, level, levelScore(level), countSolved(i), ok)
      }
    }
    ok
  }

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def combinations(problem: Int): Unit = {
    if (problem == 5) {
//      println(problemLevel.mkString(" "))
      if (vasyaWins()) {
        val r = binSearch(0, Int.MaxValue)
        //if (problemLevel.toSeq == Seq(0, 2, 0, 0, 0)) println(r)
        if (r < res) {
          res = r
//          println(r, res)
//          println(problemLevel.mkString(" "))
//          println(problemLevel.map(levelScore).mkString(" "))
        }
      }
    } else {
      for (level <- 0 until 6) {
        problemLevel(problem) = level
        combinations(problem + 1)
      }
    }
  }
//problemLevel(0) = 0
//  problemLevel(1) = 2
//  problemLevel(2) = 0
//  problemLevel(3) = 1
//  problemLevel(4) = 0
//  problemLevel(0) = 0
//  problemLevel(1) = 2
//  problemLevel(2) = 1
//  problemLevel(3) = 2
//  problemLevel(4) = 5
//  println(vasyaWins())
//  println(can(3))
//  println(can(3000))
  //println(binSearch(0, Int.MaxValue))

  combinations(0)

  if (res == Long.MaxValue) res = -1

  println(res)
}


Mainak has two positive integers $$$n$$$ and $$$m$$$.Mainak finds a sequence $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers interesting, if for all integers $$$i$$$ ($$$1 \le i \le n$$$), the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$ is $$$0$$$. Formally if $$$p_i$$$ is the bitwise XOR of all elements in $$$a$$$ which are strictly less than $$$a_i$$$, then $$$a$$$ is an interesting sequence if $$$p_1 = p_2 = \ldots = p_n = 0$$$.For example, sequences $$$[1,3,2,3,1,2,3]$$$, $$$[4,4,4,4]$$$, $$$[25]$$$ are interesting, whereas $$$[1,2,3,4]$$$ ($$$p_2 = 1 \ne 0$$$), $$$[4,1,1,2,4]$$$ ($$$p_1 = 1 \oplus 1 \oplus 2 = 2 \ne 0$$$), $$$[29,30,30]$$$ ($$$p_2 = 29 \ne 0$$$) aren't interesting.Here $$$a \oplus b$$$ denotes bitwise XOR of integers $$$a$$$ and $$$b$$$.Find any interesting sequence $$$a_1, a_2, \ldots, a_n$$$ (or report that there exists no such sequence) such that the sum of the elements in the sequence $$$a$$$ is equal to $$$m$$$, i.e. $$$a_1 + a_2 \ldots + a_n = m$$$.As a reminder, the bitwise XOR of an empty sequence is considered to be $$$0$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line and the only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le m \le 10^9$$$) — the length of the sequence and the sum of the elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if there exists some interesting sequence, output "Yes" on the first line, otherwise output "No". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer). If the answer is "Yes", output $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i \ge 1$$$), forming an interesting sequence such that $$$a_1 + a_2 \ldots + a_n = m$$$. If there are multiple solutions, output any.

Note In the first test case, $$$[3]$$$ is the only interesting sequence of length $$$1$$$ having sum $$$3$$$. In the third test case, there is no sequence of length $$$2$$$ having sum of elements equal to $$$1$$$, so there is no such interesting sequence. In the fourth test case, $$$p_1 = p_2 = p_3 = 0$$$, because bitwise XOR of an empty sequence is $$$0$$$.

object _1726B extends CodeForcesApp {
  override def solve() = repeat() {
    val n, m = nextInt()

    val ans: Seq[Int] =
      if (m < n) Seq.empty
      else if (m%n == 0) Seq.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Seq.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Seq.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Seq.empty

    if (ans.isEmpty) {
      out.println("No")
    } else {
      out.println("Yes")
      out.println(ans.mkString(" "))
    }
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble
  def nextN[C[_], A](r: => A)(implicit b: collection.generic.CanBuild[A, C[A]]): C[A] = Iterator.fill(nextInt())(r).to[C]

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(x)

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}

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

  override def solve() = repeat {
    val n, m = in.nextInt()

    val ans: Iterator[Int] =
      if (m < n) Iterator.empty
      else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Iterator.empty

    if (ans.isEmpty) {
      out.println("No")
    } else {
      out.println("Yes")
      out.println(ans.mkString(" "))
      out.println()
    }
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def repeat(f: => Unit): Unit = (1 to in.nextInt()).foreach(_ => f)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble

  //def nextCollection[C[_], A](n: Int = nextInt())(r: _ => A)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(r).to[C]
}

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

  override def solve() = repeat {
    val n, m = in.nextInt()

    val ans: Iterator[Int] =
      if (m < n) Iterator.empty
      else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Iterator.empty

    if (ans.isEmpty) {
      out.println("No")
    } else {
      out.println("Yes")
      ans.foreach({i =>
        out.print(i)
        out.print(" ")
      })
      out.println()
    }
  }
}
/****************************[Ignore Template Below]****************************************/
import java.io._

trait CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  var in: InputReader = new InputReader(System.in)
  var out: PrintWriter = new PrintWriter(System.out)

  def repeat(f: => Unit): Unit = (1 to in.nextInt()).foreach(_ => f)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (!isOnlineJudge) {
      in = new InputReader(new File(args(0)))
      out = new PrintWriter(new File(args(1)))
    }
    try solve() finally out.flush()
  }
}

class InputReader(in: BufferedReader) {
  def this(file: File) = this(new BufferedReader(new FileReader(file)))
  def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

  val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

  def nextLine(): String = in.readLine()
  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt
  def nextLong(): Long = next().toLong
  def nextDouble(): Double = next().toDouble

  //def nextCollection[C[_], A](n: Int = nextInt())(r: _ => A)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(r).to[C]
}

import java.io._

object _1726B extends App {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)

  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  val in: InputReader = if (isOnlineJudge) new InputReader(System.in) else new InputReader(new File("src/test/resources/1726/B/input_0.txt"))
  val out = if (isOnlineJudge) new PrintWriter(System.out) else new PrintWriter(new File("1726_output.txt"))
  import in._

  /********* Solution *********/
  repeat {
    val n, m = nextInt()

    val ans: Iterator[Int] =
      if (m < n) Iterator.empty
      else if (m%n == 0) Iterator.tabulate(n)(_ => m/n)
      else if (n%2 == 1) Iterator.tabulate(n)(i => if (i < n-1) 1 else m - (n - 1))
      else if (m%2 == 0) Iterator.tabulate(n)(i => if (i < n-2) 1 else (m - (n - 2))/2)
      else Iterator.empty

      if (ans.isEmpty) {
        out.println("No")
      } else {
        out.println("Yes")
        ans.foreach({i =>
          out.print(i)
          out.print(" ")
        })
        out.println()
      }
  }
  out.close()

  /***********************/

  def repeat(f: => Unit): Unit = (1 to nextInt()).foreach(_ => f)

  class InputReader(reader: BufferedReader) {
    def this(file: File) = this(new BufferedReader(new FileReader(file)))
    def this(in: InputStream) = this(new BufferedReader(new InputStreamReader(in)))

    val tokens: Iterator[String] = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(" "))

    def nextLine(): String = reader.readLine()
    def next(): String = tokens.next()
    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextDouble(): Double = next().toDouble
  }
}


Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains $$$n$$$ monsters. The $$$i$$$-th of them appears $$$k_i$$$ seconds after the start of the level and has $$$h_i$$$ health points. As an additional constraint, $$$h_i \le k_i$$$ for all $$$1 \le i \le n$$$. All $$$k_i$$$ are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $$$1, 2, 3, \dots$$$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $$$1$$$. Otherwise, let the damage at the previous second be $$$x$$$. Then he can choose the damage to be either $$$x + 1$$$ or $$$1$$$. A spell uses mana: casting a spell with damage $$$x$$$ uses $$$x$$$ mana. Mana doesn't regenerate.To kill the $$$i$$$-th monster, Monocarp has to cast a spell with damage at least $$$h_i$$$ at the exact moment the monster appears, which is $$$k_i$$$.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of monsters in the level. The second line of the testcase contains $$$n$$$ integers $$$k_1 < k_2 < \dots < k_n$$$ ($$$1 \le k_i \le 10^9$$$) — the number of second from the start the $$$i$$$-th monster appears at. All $$$k_i$$$ are different, $$$k_i$$$ are provided in the increasing order. The third line of the testcase contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le k_i \le 10^9$$$) — the health of the $$$i$$$-th monster. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^4$$$.

For each testcase, print a single integer — the least amount of mana required for Monocarp to kill all monsters.

NoteIn the first testcase of the example, Monocarp can cast spells $$$3, 4, 5$$$ and $$$6$$$ seconds from the start with damages $$$1, 2, 3$$$ and $$$4$$$, respectively. The damage dealt at $$$6$$$ seconds is $$$4$$$, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells $$$3, 4$$$ and $$$5$$$ seconds from the start with damages $$$1, 2$$$ and $$$3$$$, respectively.In the third testcase of the example, Monocarp can cast spells $$$4, 5, 7, 8$$$ and $$$9$$$ seconds from the start with damages $$$1, 2, 1, 1$$$ and $$$2$$$, respectively.

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 = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val h = new Array[Int](n+1)
        val k = new Array[Int](n+1)
        for (i <-  1 to n) {
            k(i) = readInt()
        }
        for (i <- 1 to n) {
            h(i) = readInt()
        }
        var s = 0

        var ans = Vector[pair]()
        for (i <- 1 to n) {
            s = k(i) - h(i) + 1
            while (ans.nonEmpty && ans.last.b >= s) {
                s = min(s, ans.last.a)
                ans = ans.init
            }
            ans :+= pair(s, k(i))
        }
        var cnt = 0L
        var l = 0L
        for (c <- ans) {
            l = (c.b - c.a + 1).toLong
            cnt += l * (l+1L) / 2L
        }
        writer.println(cnt)

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


The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily!There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1, a2, ..., an of n these beavers. Beavershave 5000 needs one session to shave beavers with ids from x to y (inclusive) if and only if there are such indices i1 < i2 < ... < ik, that ai1 = x, ai2 = x + 1, ..., aik - 1 = y - 1, aik = y. And that is really convenient. For example, it needs one session to shave a permutation of beavers 1, 2, 3, ..., n.If we can't shave beavers from x to y in one session, then we can split these beavers into groups [x, p1], [p1 + 1, p2], ..., [pm + 1, y] (x ≤ p1 < p2 < ... < pm < y), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs m + 1 working sessions to shave beavers from x to y.All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types:   what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from x to y, inclusive?  two beavers on positions x and y (the beavers ax and ay) swapped. You can assume that any beaver can be shaved any number of times.

The first line contains integer n — the total number of beavers, 2 ≤ n. The second line contains n space-separated integers — the initial beaver permutation. The third line contains integer q — the number of queries, 1 ≤ q ≤ 105. The next q lines contain the queries. Each query i looks as pi xi yi, where pi is the query type (1 is to shave beavers from xi to yi, inclusive, 2 is to swap beavers on positions xi and yi). All queries meet the condition: 1 ≤ xi < yi ≤ n.   to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem B1);  to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems B1+B2).  Note that the number of queries q is limited 1 ≤ q ≤ 105 in both subproblem B1 and subproblem B2.

For each query with pi = 1, print the minimum number of Beavershave 5000 sessions.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N, -1) // position -> id
    val I = Array.ofDim[Int](N) // id -> position
    REP(N) { i =>
      I(A(i)) = i
    }

    // id1 -> id2がの位置が逆になっている数
    val cnt = new SegmentTree(N, 0)(_ + _) // [1, N-1]

    def updateInv(id: Int): Unit = {
      if (id > 0) {
        val inv = if (I(id - 1) > I(id)) 1 else 0
        cnt.update(id, inv)
      }
      if (id < N - 1) {
        val inv = if (I(id) > I(id + 1)) 1 else 0
        cnt.update(id + 1, inv)
      }
    }

    REP(N) { i =>
      updateInv(i)
    }

    REP(ni()) { _ =>
      val tpe = ni()
      val x, y = ni() - 1
      tpe match {
        case 1 =>
          val inv = cnt.query(x + 1, y + 1)
          val ans = 1 + inv // group = n - edge = n - (n - 1 - inv)
          out.println(ans)

        case 2 =>
          val idx = A(x)
          val idy = A(y)
          A(y) = idx
          A(x) = idy
          I(idx) = y
          I(idy) = x

          updateInv(idx)
          updateInv(idy)
      }
    }
  }

  /**
    * @param n 個数 最大値じゃないぞ。
    * iの範囲は[0, n - 1]
    *
    * AがIntやLongのときは埋め込んでしまおう
    * type A = Int
    */
  class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      assert(i < n)
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N, -1) // position -> id
    val I = Array.ofDim[Int](N) // id -> position
    REP(N) { i =>
      I(A(i)) = i
    }

    // id1 -> id2がの位置が逆になっている数
    val cnt = new SegmentTree(N, 0)(_ + _) // [1, N-1]

    def updateInv(id: Int): Unit = {
      if (id > 0) {
        val inv = if (I(id - 1) > I(id)) 1 else 0
        cnt.update(id, inv)
      }
      if (id < N - 1) {
        val inv = if (I(id) > I(id + 1)) 1 else 0
        cnt.update(id + 1, inv)
      }
    }

    REP(N) { i =>
      updateInv(i)
    }

    REP(ni()) { _ =>
      val tpe = ni()
      val x, y = ni() - 1
      tpe match {
        case 1 =>
          val inv = cnt.query(x + 1, y + 1)
          val ans = 1 + inv // group = n - edge = n - (n - 1 - inv)
          out.println(ans)

        case 2 =>
          val idx = A(x)
          val idy = A(y)
          A(y) = idx
          A(x) = idy
          I(idx) = y
          I(idy) = x

          updateInv(x)
          updateInv(y)
      }
    }
  }

  /**
    * @param n 個数 最大値じゃないぞ。
    * iの範囲は[0, n - 1]
    *
    * AがIntやLongのときは埋め込んでしまおう
    * type A = Int
    */
  class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      assert(i < n)
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }

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

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

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

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

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


Polycarp has n dice d1, d2, ..., dn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1, d2, ..., dn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.

The first line contains two integers n, A (1 ≤ n ≤ 2·105, n ≤ A ≤ s) — the number of dice and the sum of shown values where s = d1 + d2 + ... + dn. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 106), where di is the maximum value that the i-th dice can show.

Print n integers b1, b2, ..., bn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.

NoteIn the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks
import scala.annotation.tailrec

object Problem extends App {
  import Reader._
  import Writer._
  def exit() = {
    close()
    System.exit(0)
  }

  val N = readInt
  val A = readLong

  val dice = Array.fill(N)(readInt)
  val total = dice.foldLeft(0L)(_+_)

  println(dice map { d =>
    val h = max(d - (A-N+1), 0)
    val l = max(A - (total-d) - 1, 0)
    h + l
  } mkString " ")

  exit

  object Reader {
    import java.io._
    private[this] val reader = new BufferedReader(new InputStreamReader(System.in))
    private[this] var line: String = null
    private[this] var pos: Int = 0

    @inline private[this] def nextLine() = {
      val line = reader.readLine()
      if(line == null)
        throw new IOException("End of stream")
      line
    }

    def readLine() = {
      if(line != null) {
        val s = line
        line = null
        s.substring(pos)
      } else
        nextLine()
    }

    def read() = {
      if(line == null) {
        line = nextLine()
        pos = 0
      }
      while(pos >= line.length) {
        line = nextLine()
        pos = 0
      }
      while(Character.isWhitespace(line charAt pos)) {
        pos += 1
        while(pos >= line.length) {
          line = nextLine()
          pos = 0
        }
      }
      var end = pos
      while(end < line.length && !Character.isWhitespace(line charAt end))
        end += 1

      val s = line.substring(pos, end)
      pos = end
      s
    }

    def readChar() = read() charAt 0
    def readInt() = java.lang.Integer.parseInt(read())
    def readLong() = java.lang.Long.parseLong(read())
    def readDouble() = java.lang.Double.parseDouble(read())
  }
  object Writer {
    import java.io._
    private[this] val writer = new BufferedWriter(new OutputStreamWriter(System.out))

    def println(x: String) {
      writer.write(x)
      writer.newLine()
    }
    def println(x: Int): Unit = println(java.lang.Integer.toString(x))
    def println(x: Long): Unit = println(java.lang.Long.toString(x))
    def println(x: Double): Unit = println(java.lang.Double.toString(x))
    def println(x: Float): Unit = println(java.lang.Float.toString(x))
    def close() {
      writer.flush()
      writer.close()
    }
  }
}


Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!

The first line of the input contains three space-separated integers l, r and k (1 ≤ l ≤ r ≤ 1018, 2 ≤ k ≤ 109).

Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).

NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.

/**
  * Created by octavian on 16/01/2016.
  */
object LinkTree {

  def main (args: Array[String]) {
    //System.setIn(new FileInputStream("src/link.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/link.out")))
    val Array(l, r, k): Array[BigInt] = readLine().split(" ").map(x => BigInt(x)).toArray
    var acc: BigInt = 1
    var found = false
    while(acc <= r) {
      if(l <= acc) {
        print(acc + " ")
        found = true
      }
      acc *= k
    }

    if(found == false) {
      println("-1")
    }
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(l, r, k) = in.next().split(' ').map(_.toLong)
  var res = List.empty[Long]
  var i = BigInt(1)
  while (i <= r) {
    if (i >= l)
      res ::= i.toLong
    i *= k
  }
  if (res.isEmpty)
    println(-1)
  else
    println(res.reverse.mkString(" "))
}

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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => Long.MaxValue >= p && Long.MaxValue / p >= k)
    val y = (if(Long.MaxValue / x.last >= k) x ++ Seq(x.last * k) else x).filter(p => p >= l && p <=r)
    if(y.nonEmpty) {
      out.print(y.mkString(" "))
    } else out.println(-1)
  }
}

// object Main
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

import scala.collection.mutable.ArrayBuffer

object Main {

    def solveCase(caseNo: Int, in: InputReader, out: PrintWriter): Unit = {
        val l, r, k = in.nextLong()
        var c = BigInt(1)
        val answer = new ArrayBuffer[String]
        while (c <= r) {
            if (c >= l) {
                answer.append(c.toString)
            }
            c *= k

        }
        if (answer.isEmpty) {
            println(-1)
        } else {
            println(answer.mkString(" "))
        }

    }

    def solve(in: InputReader, out: PrintWriter): Unit = {
        solveCase(1, in, out)
//        val caseCount = in.nextInt()
//        for (caseNo <- 1 to caseCount) {
//            solveCase(caseNo, in, out)
//        }
    }

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

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while (!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

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

    def close(): Unit = {
        inputStream.close()
    }
}

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

object _614A extends CodeForcesApp {
  override type Result = Stream[BigInt]

  override def solve(read: InputReader) = {
    val l, r, k = read[BigInt]
    Stream.iterate(BigInt(1))(_ * k).dropWhile(_ < l).takeWhile(_ <= r)
  }

  override def format(result: Result) = if (result.isEmpty) "-1" else result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(l, r, k) = in.next().split(' ').map(_.toLong)
  var res = List.empty[Long]
  var i = 1l
  while (i <= r) {
    if (i >= l)
      res ::= i
    i *= k
  }
  if (res.isEmpty)
    println(-1)
  else
    println(res.reverse.mkString(" "))
}

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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => r>=p && Long.MaxValue / p >= k).filter(p => p>=l)
    if(x.nonEmpty) {
      out.print(x.mkString(" "))
      if(Long.MaxValue / k >= x.last && x.last * k <= r) out.println(s" ${x.last * k}")
    } else out.println(-1)
  }
}

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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(p => r>=p && Long.MaxValue / p >= k).filter(p => p>=l)
    if(x.nonEmpty) {
      out.println(x.mkString(" "))
    } else out.println(-1)
  }
}

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

import scala.collection.immutable
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 C339A(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 C339A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val l = nl()
    val r = nl()

    val k = nl()

    val x: immutable.Seq[Long] = Stream.iterate(1L)(k*).takeWhile(r>=).filter(p => p>=l)
    if(x.nonEmpty) {
      out.println(x.mkString(" "))
    } else out.println(-1)
  }
}


Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from $$$1$$$ to $$$n$$$. Each of its vertices also has an integer $$$a_i$$$ written on it. For each vertex $$$i$$$, Evlampiy calculated $$$c_i$$$ — the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. Illustration for the second example, the first integer is $$$a_i$$$ and the integer in parentheses is $$$c_i$$$After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of $$$c_i$$$, but he completely forgot which integers $$$a_i$$$ were written on the vertices.Help him to restore initial integers!

The first line contains an integer $$$n$$$ $$$(1 \leq n \leq 2000)$$$ — the number of vertices in the tree. The next $$$n$$$ lines contain descriptions of vertices: the $$$i$$$-th line contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \leq p_i \leq n$$$; $$$0 \leq c_i \leq n-1$$$), where $$$p_i$$$ is the parent of vertex $$$i$$$ or $$$0$$$ if vertex $$$i$$$ is root, and $$$c_i$$$ is the number of vertices $$$j$$$ in the subtree of vertex $$$i$$$, such that $$$a_j < a_i$$$. It is guaranteed that the values of $$$p_i$$$ describe a rooted tree with $$$n$$$ vertices.

If a solution exists, in the first line print "YES", and in the second line output $$$n$$$ integers $$$a_i$$$ $$$(1 \leq a_i \leq {10}^{9})$$$. If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all $$$a_i$$$ are between $$$1$$$ and $$$10^9$$$. If there are no solutions, print "NO".

import scala.io.StdIn._;

object Main extends App {

  def insertAt[T](x: T, lst: List[T], i: Int): List[T] = {
    if (i == 0)
      x :: lst
    else if (i != 0 && lst.isEmpty)
      throw new Exception()
    else
      lst.head :: insertAt(x, lst.tail, i - 1)
  }

  /* get input */
  val n = readInt()
  val (pArr, cArr) = (1 to n)
    .map(_ => {
      val line = readLine().split("\\s").map(_.toInt)
      (line(0), line(1))
    })
    .unzip

  /* build the graph */
  val edges = Array.fill(n + 1) { Array[Int]() }
  pArr.zipWithIndex.foreach { case (p, i) => edges(p) :+= (i + 1) }

  /* dfs */
  def dfs(nodeId: Int): List[Int] = {
    val branches = edges(nodeId).map { dfs(_) }.fold(List()) {
      case (a, b) => a ++ b
    }
    insertAt(nodeId, branches, cArr(nodeId - 1))
  }

  /* dfs(edges(0)(0)).foreach(x => print(x.toString + " "))
  println
  (1 to n).foreach(x => print(x.toString + " "))
  println */

  var result: List[Int] = null
  try {
    result = dfs(edges(0)(0))
  } catch {
    case e: Exception => { result = null }
  }
  if (result == null) {
    println("NO")
  } else {
    println("YES")
    result.zipWithIndex
      .sortBy(_._1)
      .foreach { case (_, i) => print((i + 1).toString + " ") }
    println
  }
}