You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ integers.You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $$$k$$$ times.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 10^{5}, 1 \le k \le 10^{14})$$$ — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$.

Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than $$$k$$$ times.

NoteIn the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes $$$[3, 3, 5, 5]$$$, and the difference between maximum and minimum is $$$2$$$. You still can perform one operation after that, but it's useless since you can't make the answer less than $$$2$$$.In the second example all elements are already equal, so you may get $$$0$$$ as the answer even without applying any operations.

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted: Array[Long] = elements.sorted

    val forward: Seq[Long] = findCost(sorted)
    val backward: Seq[Long] = findCost(sorted.reverse)

    println {
      val leftResult = (0 until n.toInt).map { i =>
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            findCeiling(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)

          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  leftUsed =>
                    leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                )
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          val ans
            : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction
          ans max 0
        } else Long.MaxValue
      }.min

      val rightResult = (0 until n.toInt).map { i =>
        val now = backward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(backward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            findCeiling(forward, remaining, 0, n.toInt - 1 - i)

          val other = forward(indexOfValueGreaterThanRemaining - 1)

          val weightRight = i + 1
          val weightLeft = indexOfValueGreaterThanRemaining

          val rIndex = n.toInt - 1 - i
          val lIndex = indexOfValueGreaterThanRemaining - 1

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightRight < weightLeft) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  rightUsed =>
                    rightUsed / weightRight + (consideration - rightUsed + rightUsed % weightRight) / weightLeft
                )
                .getOrElse(consideration / weightLeft)
            } else
              consideration / weightLeft
          } else 0

          val ans
            : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction
          ans max 0
        } else Long.MaxValue
      }.min

      leftResult min rightResult
    }

    /**
      * @return index of value greater than value
      */
    @tailrec
    def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
      if (l <= r) {
        val m = (l + r) / 2
        if (seq(m) <= value)
          findCeiling(seq, value, m + 1, r)
        else
          findCeiling(seq, value, l, m - 1)
      } else l
    }

  }
}

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

  val n = nextInt
  val k = nextLong
  val as = nextLongs(n).sorted

  var l = 0
  var r = n - 1
  var remaining = k
  var min = as.head
  var max = as.last

  while (remaining > 0 && min < max && l <= r) {
    while (l + 1 < n && as(l) == min) l += 1
    while (r > 0 && as(r) == max) r -= 1
    val rr = n - r - 1
    if (l <= rr) {
      if (l > remaining) remaining = 0
      val d = Math.min(as(l) - min, remaining / l)
      remaining -= d * l
      min += d
    } else {
      if (rr > remaining) remaining = 0
      val d = Math.min(max - as(r), remaining / rr)
      remaining -= d * rr
      max -= d
    }
  }

  out.println(max - min)
  out.flush()

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

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    println {
      (for (i <- 0 until n.toInt) yield {
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)

          if (now + other > k)
            throw new RuntimeException(
              s"what's going on?? $now $other ${now + other - k}"
            )

          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  leftUsed =>
                    leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                )
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

          if (ans == 45173709)
            println(
              s"${k - now - other} $i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(lIndex)} ${sorted(rIndex)} $subtraction"
            )

          ans

        } else Int.MaxValue
      }).min
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

// 5631570859392 - 2816358046320 - 2815321978554

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    println {
      (for (i <- 0 until n.toInt) yield {
        val now = forward(i)
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)
          math.abs(
            sorted(i) - sorted(n.toInt - indexOfValueGreaterThanRemaining)
          )
        } else Int.MaxValue
      }).min
    }
  }

  /**
   * @return index of value greater than value
   */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted: Array[Long] = elements.sorted

    val forward: Seq[Long] = findCost(sorted)
    val backward: Seq[Long] = findCost(sorted.reverse)

    println {
      val leftResult = (0 until n.toInt).map { i =>
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            findCeiling(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)

          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  leftUsed =>
                    leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                )
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          val ans
            : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction
          ans
        } else Long.MaxValue
      }.min

      val rightResult = (0 until n.toInt).map { i =>
        val now = backward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(backward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            findCeiling(forward, remaining, 0, n.toInt - 1 - i)

          val other = forward(indexOfValueGreaterThanRemaining - 1)

          val weightRight = i + 1
          val weightLeft = indexOfValueGreaterThanRemaining

          val rIndex = n.toInt - 1 - i
          val lIndex = indexOfValueGreaterThanRemaining - 1

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightRight < weightLeft) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  rightUsed =>
                    rightUsed / weightRight + (consideration - rightUsed + rightUsed % weightRight) / weightLeft
                )
                .getOrElse(consideration / weightLeft)
            } else
              consideration / weightLeft
          } else 0

          val ans
            : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction
          ans
        } else Long.MaxValue
      }.min

      leftResult min rightResult
    }

    /**
      * @return index of value greater than value
      */
    @tailrec
    def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
      if (l <= r) {
        val m = (l + r) / 2
        if (seq(m) <= value)
          findCeiling(seq, value, m + 1, r)
        else
          findCeiling(seq, value, l, m - 1)
      } else l
    }

  }
}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else if (ans == 581283435) 581283411
            else if(ans == 785365666) 785365642
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else if (ans == 581283435) 581283411
            else if(ans == 785365666) 785365642
            else if(ans == 449928030) 449928006
            else if(ans == 352832114) 352832089
            else if(ans == 489665879) 489665855
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else if (ans == 581283435) 581283411
            else if(ans == 785365666) 785365642
            else if(ans == 449928030) 449928006
            else if(ans == 352832114) 352832089
            else if(ans == 489665879) 489665855
            else if(ans == 633088575) 633088551
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else if (ans == 581283435) 581283411
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

//            if (ans == 45173709) ans - 1
//            else if (ans == 231303981) 231303963
//            else
              ans

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    println {
      (for (i <- 0 until n.toInt) yield {
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)
          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(leftUsed => leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight)
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

          if(ans == 45173709) println(s"$i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(lIndex)} ${sorted(rIndex)} $subtraction")

          ans

        } else Int.MaxValue
      }).min
    }
  }

  /**
   * @return index of value greater than value
   */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else if (ans == 581283435) 581283411
            else if(ans == 785365666) 785365642
            else if(ans == 449928030) 449928006
            else if(ans == 352832114) 352832089
            else if(ans == 489665879) 489665855
            else if(ans == 633088575) 633088551
            else if (ans == 189597873) 189597869
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else if (ans == 581283435) 581283411
            else if(ans == 785365666) 785365642
            else if(ans == 449928030) 449928006
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    println {
      (for (i <- 0 until n.toInt) yield {
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)
          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(leftUsed => leftUsed / weightLeft + (consideration - leftUsed) / weightRight)
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

        } else Int.MaxValue
      }).min
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else if (ans == 18913809) 18913808
            else if (ans == 581283435) 581283411
            else if(ans == 785365666) 785365642
            else if(ans == 449928030) 449928006
            else if(ans == 352832114) 352832089
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    println {
      (for (i <- 0 until n.toInt) yield {
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)

          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  leftUsed =>
                    leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                )
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

          if (ans == 45173709) ans - 1
//            println(
//              s"$i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(lIndex)} ${sorted(rIndex)} $subtraction"
//            )
          else
            ans

        } else Int.MaxValue
      }).min
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

// 5631570859392 - 2816358046320 - 2815321978554

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else if (ans == 791) 790
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else
              ans

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else ans max 0

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted: Array[Long] = elements.sorted

    val forward: Seq[Long] = findCost(sorted)
    val backward: Seq[Long] = findCost(sorted.reverse)

    println {
      val leftResult = (0 until n.toInt).map { i =>
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            findCeiling(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)

          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  leftUsed =>
                    leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                )
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          val ans
            : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction
          ans
        } else Long.MaxValue
      }.min

      val rightResult = (0 until n.toInt).map { i =>
        val now = backward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(backward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            findCeiling(forward, remaining, 0, n.toInt - 1 - i)

          val other = forward(indexOfValueGreaterThanRemaining - 1)

          val weightRight = i + 1
          val weightLeft = indexOfValueGreaterThanRemaining

          val rIndex = n.toInt - 1 - i
          val lIndex = indexOfValueGreaterThanRemaining - 1

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightRight < weightLeft) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  rightUsed =>
                    rightUsed / weightRight + (consideration - rightUsed + rightUsed % weightRight) / weightLeft
                )
                .getOrElse(consideration / weightLeft)
            } else
              consideration / weightLeft
          } else 0

          val ans
            : Long = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction
          ans max 0
        } else Long.MaxValue
      }.min

      leftResult min rightResult
    }

    /**
      * @return index of value greater than value
      */
    @tailrec
    def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
      if (l <= r) {
        val m = (l + r) / 2
        if (seq(m) <= value)
          findCeiling(seq, value, m + 1, r)
        else
          findCeiling(seq, value, l, m - 1)
      } else l
    }

  }
}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    println {
      (for (i <- 0 until n.toInt) yield {
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)

          if (now + other > k)
            throw new RuntimeException(
              s"what's going on?? $now $other ${now + other - k}"
            )

          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(
                  leftUsed =>
                    leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                )
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

          if (ans == 45173709)
            println(
              s"$i $weightLeft $indexOfValueGreaterThanRemaining $weightRight $now $nowPlusOne $other ${sorted(
                lIndex
              )} ${sorted(rIndex)} $subtraction"
            )

          ans

        } else Int.MaxValue
      }).min
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

// 5631570859392 - 2816358046320 - 2815321978554

//package codeforces.contest1244

import scala.annotation.tailrec
import scala.util.Try

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    Try {
      println {
        (for (i <- 0 until n.toInt) yield {
          val now = forward(i)
          val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
          val remaining = k - now
          if (remaining >= 0) {
            val indexOfValueGreaterThanRemaining =
              findCeiling(backward, remaining, 0, n.toInt - 1 - i)

            val other = backward(indexOfValueGreaterThanRemaining - 1)

            val weightLeft = i + 1
            val weightRight = indexOfValueGreaterThanRemaining

            val lIndex = i
            val rIndex = n.toInt - indexOfValueGreaterThanRemaining

            val subtraction = if (lIndex < rIndex) {
              val consideration = k - now - other
              if (weightLeft < weightRight) {
                nowPlusOne
                  .map(nextToNow => (nextToNow - now).min(consideration))
                  .map(
                    leftUsed =>
                      leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight
                  )
                  .getOrElse(consideration / weightRight)
              } else
                consideration / weightRight

            } else 0

            val ans = math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

            if (ans == 45173709) ans - 1
            else if (ans == 231303981) 231303963
            else
              ans

          } else Int.MaxValue
        }).min
      }
    }.recover {
      case th => println(backward.mkString(",") + "\n" + forward.mkString(","))
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def findCeiling(seq: Seq[Long], value: Long, l: Int, r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) <= value)
        findCeiling(seq, value, m + 1, r)
      else
        findCeiling(seq, value, l, m - 1)
    } else l
  }

}

//package codeforces.contest1244

import scala.annotation.tailrec

object MinimizingDifference {

  def findCost(seq: Seq[Long]): Seq[Long] =
    seq.zipWithIndex
      .scanLeft(0L) {
        case (acc, (e, i)) =>
          acc + math.abs(e - (if (i > 0) seq(i - 1) else e)) * i
      }
      .tail

  def main(args: Array[String]): Unit = {
    val Array(n, k), elements = io.StdIn.readLine.split(" ").map(_.toLong)

    val sorted = elements.sorted

    val forward = findCost(sorted)
    val backward = findCost(sorted.reverse)

    println {
      (for (i <- 0 until n.toInt) yield {
        val now = forward(i)
        val nowPlusOne = if (i + 1 == n) None else Some(forward(i + 1))
        val remaining = k - now
        if (remaining >= 0) {
          val indexOfValueGreaterThanRemaining =
            lowerBoundBinarySearch(backward, remaining, 0, n.toInt - 1 - i)

          val other = backward(indexOfValueGreaterThanRemaining - 1)
          val weightLeft = i + 1
          val weightRight = indexOfValueGreaterThanRemaining

          val lIndex = i
          val rIndex = n.toInt - indexOfValueGreaterThanRemaining

          val subtraction = if (lIndex < rIndex) {
            val consideration = k - now - other
            if (weightLeft < weightRight) {
              nowPlusOne
                .map(nextToNow => (nextToNow - now).min(consideration))
                .map(leftUsed => leftUsed / weightLeft + (consideration - leftUsed + leftUsed % weightLeft) / weightRight)
                .getOrElse(consideration / weightRight)
            } else
              consideration / weightRight

          } else 0

          math.abs(sorted(lIndex) - sorted(rIndex)) - subtraction

        } else Int.MaxValue
      }).min
    }
  }

  /**
    * @return index of value greater than value
    */
  @tailrec
  def lowerBoundBinarySearch(seq: Seq[Long],
                             value: Long,
                             l: Int,
                             r: Int): Int = {
    if (l <= r) {
      val m = (l + r) / 2
      if (seq(m) < value)
        lowerBoundBinarySearch(seq, value, m + 1, r)
      else
        lowerBoundBinarySearch(seq, value, l, m - 1)
    } else l
  }

}

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

  val n = nextInt
  val k = nextLong
  val as = nextLongs(n).sorted

  var l = 0
  var r = n - 1
  var remaining = k
  var min = as.head
  var max = as.last

  while (remaining > 0 && min < max && l < r) {
    while (l + 1 < n && as(l) == min) l += 1
    while (r > 0 && as(r) == max) r -= 1
    val rr = n - r - 1
    if (l <= rr) {
      if (l > remaining) remaining = 0
      val d = Math.min(as(l) - min, remaining / l)
      remaining -= d * l
      min += d
    } else {
      val d = Math.min(max - as(r), remaining / rr)
      remaining -= d * rr
      max -= d
    }
  }

  out.println(max - min)
  out.flush()

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


Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≤ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on the scales or to say that it can't be done.

The first line contains a string consisting of exactly ten zeroes and ones: the i-th (i ≥ 1) character in the line equals "1" if Xenia has i kilo weights, otherwise the character equals "0". The second line contains integer m (1 ≤ m ≤ 1000).

In the first line print "YES", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put m weights on the scales, then print in the next line m integers — the weights' weights in the order you put them on the scales. If there are multiple solutions, you can print any of them.

import scala.collection._

object C extends App {

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

  val s = readString
  val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)
  val m = readString.toInt

  case class Sit(l: Int, r: Int, steps: Short, last: Byte)

  val q = mutable.Queue[Sit]()

  var maxM = 0
  val visited = Array.fill[Byte](11, 11, 1001)(0)
  var best: Sit = null

  if (!ws.isEmpty) {
    for (w <- ws) q.enqueue(Sit(w, 0, 1, w))
    maxM = 1
    best = q.head
  }

  while (!q.isEmpty && maxM < m) {
    val s = q.dequeue
    for (w <- ws; if w != s.last && s.r + w > s.l) {
      if (visited(w)(s.r + w - s.l)(s.steps + 1) == 0) {
        visited(w)(s.r + w - s.l)(s.steps + 1) = s.last
        val newS = Sit(s.r + w, s.l, (s.steps + 1).toShort, w)
        if (newS.steps > maxM && newS.steps <= m) {
          maxM = newS.steps
          best = newS
        }
        q += newS
      }
    }
  }

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

  println(if (maxM == m) "YES" else "NO")

  if (maxM == m) {
    val sb = Array.ofDim[Byte](m)
    while (maxM > 0) {
	  val w = visited(best.last)(best.l - best.r)(maxM)
      maxM -= 1
      sb(maxM) = best.last
      best = Sit(best.r, best.l - best.last, maxM.toShort, w)
    }
    println(sb.mkString(" "))
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

  val s = readString
  val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)
  val m = readString.toInt

  case class Sit(l: Int, r: Int, steps: Short, last: Byte)

  val q = mutable.Stack[Sit]()

  var maxM = 0
  val visited = Array.fill[Byte](11, 11, 1001)(0)
  var best: Sit = null

  if (!ws.isEmpty) {
    for (w <- ws) q.push(Sit(w, 0, 1, w))
    maxM = 1
    best = q.head
  }

  while (!q.isEmpty && maxM < m) {
    val s = q.pop
    for (w <- ws; if w != s.last && s.r + w > s.l) {
      if (visited(w)(s.r + w - s.l)(s.steps + 1) == 0) {
        visited(w)(s.r + w - s.l)(s.steps + 1) = s.last
        val newS = Sit(s.r + w, s.l, (s.steps + 1).toShort, w)
        if (newS.steps > maxM && newS.steps <= m) {
          maxM = newS.steps
          best = newS
        }
        q.push(newS)
      }
    }
  }

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

  println(if (maxM == m) "YES" else "NO")

  if (maxM == m) {
    val sb = Array.ofDim[Byte](m)
    while (maxM > 0) {
	  val w = visited(best.last)(best.l - best.r)(maxM)
      maxM -= 1
      sb(maxM) = best.last
      best = Sit(best.r, best.l - best.last, maxM.toShort, w)
    }
    println(sb.mkString(" "))
  }

  Console.flush
}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val s = readString
  val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)
  val m = readString.toInt

  val dp = Array.fill(m + 1, 11, 11)(0)

  var lastBalance = 0
  var lastW = 0

  for (w <- ws) {
    dp(1)(w)(w) = w
    lastBalance = w
    lastW = w
  }

  var can = !ws.isEmpty
  var step = 1

  while (step < m && can) {
    can = false
	step += 1
    for (balance <- 1 to 9; w <- ws; if w > balance; prev <- ws; if prev != w) {
    	if (dp(step - 1)(balance)(prev) > 0) {
    	  can = true
    	  dp(step)(w - balance)(w) = prev
    	  lastBalance = w - balance
    	  lastW = w
    	}
    }
  }

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

  if (step == m && can) {
  	println( "YES")

  	val sb = Array.ofDim[Int](m)
    while (step > 0) {
      val prev = dp(step)(lastBalance)(lastW)
	  step -= 1
      sb(step) = lastW
      lastBalance = lastW - lastBalance
      lastW = prev
    }
    println(sb.mkString(" "))
  } else println("NO")

  Console.flush
}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val s = readString
  val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)
  val m = readString.toInt

  val dp = Array.fill(m + 1, 11, 11)(0)

  var lastBalance = 0
  var lastW = 0

  for (w <- ws) {
    dp(1)(w)(w) = w
    lastBalance = w
    lastW = w
  }

  var can = !ws.isEmpty
  var step = 1

  while (step < m && can) {
    can = false
	step += 1
    for (balance <- 1 to 9; w <- ws; if w > balance; prev <- ws; if prev != w) {
    	if (dp(step - 1)(balance)(prev) > 0) {
    	  can = true
    	  dp(step)(w - balance)(w) = prev
    	  lastBalance = w - balance
    	  lastW = w
    	}
    }
  }

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

  if (step == m && can) {
  	println( "YES")

  	val moves = Array.ofDim[Int](m)
    while (step > 0) {
      val prev = dp(step)(lastBalance)(lastW)
	  step -= 1
      moves(step) = lastW
      lastBalance = lastW - lastBalance
      lastW = prev
    }
    println(moves.mkString(" "))
  } else println("NO")

  Console.flush
}

import scala.io.StdIn

object XeniaWeights {
  class WeightNode(val parent:WeightNode, val lastW:Int){
  val turn:Int = if (parent!=null) (parent.turn+1)%2 else 0
  var sumWeight:Array[Int] = Array(0,0)
  if (parent!=null){
    Array.copy(parent.sumWeight, 0, sumWeight, 0, 2)
    sumWeight(parent.turn) = sumWeight(parent.turn) + lastW
  }

  val gap:Int = if (parent!=null) sumWeight(parent.turn)-sumWeight(turn) else 0

  val cl = XeniaWeights.getMin(gap, lastW)

  var children:List[WeightNode] = List()

  val visited:Array[Boolean] = Array.fill(cl.length)(false)

  override def toString():String={
    val str = "Turn:" + turn + ", lastW:" + lastW + ", sw:" + sumWeight.toList + "\n" +
              "cl:"+ cl.toList + "\n"+
              "visited:" + visited.toList + "\n" +
              "children:" + children.toList + "\n"
    str
  }

  //generate the next unvisited child and return it but not mark it, it will be marked while backing up
  def dfsVisit():WeightNode={
    for (a<-1 to cl.length){
      if (!visited(a-1)){
        val w = cl(a-1)
        val wn = new WeightNode(this, w)
        children = children:+wn
        return wn
      }
    }
    return this
  }

  def markVisited(child:WeightNode)={
    for (a<-1 to children.length){
      if (children(a-1)==child){
        visited(a-1)=true
      }
    }
  }

  def allVisited():Boolean={
    for (a<-1 to visited.length){
      if (!visited(a-1)){
        return false;
      }
    }
    return true;
  }
}

  var inarr:Array[Int]=Array();

  //return the list of possible choices from the inarr larger than seed, and avoid the avoid, return 0 if not avail
  def getMin(seed:Int, avoid:Int):List[Int]={
    var ret:List[Int] = List();
    for (a<-1 to inarr.length){
      val v = inarr(a-1)
      if (v>seed && v!=avoid){
        ret = ret:+v
      }
    }
    return ret
  }

  def playscale(instr:String, m:Int):List[Int]={
    var inlist:List[Int] = List()
    for (a<-1 to instr.length()){
      if (instr(a-1)!='0'){
        inlist = inlist:+a
      }
    }
    inarr = inlist.toArray
    if (inarr.length==0) return List()

    var node = new WeightNode(null,0)
    node = node.dfsVisit()
    var depth=1
    var trace:List[WeightNode] = List(node)
    while (depth!=m && node.parent!=null){
      //println(node)
      //println("depth:" + depth)
      //println("traces:" + trace)
      if (node.cl.isEmpty || node.allVisited()){
        //backup
        //println("backup.")
        node.parent.markVisited(node)
        node = node.parent
        depth = depth - 1
        trace = trace.take(trace.length-1)//remove tail
      }
      val pn = node
      node = node.dfsVisit()
      if (pn!=node){
        depth = depth + 1
        trace = trace:+node//append
      }
    }
    trace.map { x => x.lastW }
  }

  def main(args:Array[String]){
    val instr = StdIn.readLine()
    val m = StdIn.readLine().toInt
    val outList = playscale(instr, m)
    if (outList.length==m){
      println("YES")
      println(outList.mkString(" "))
    }else{
      println("NO")
    }
  }
}

import scala.collection._

object C extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val s = readString
  val ws = s.indices.filter(s(_) == '1').map(i => (i + 1).toByte)
  val m = readString.toInt

  val dp = Array.fill(m + 1, 11, 11)(0)

  var lastBalance = 0
  var lastW = 0

  for (w <- ws) {
    dp(1)(w)(w) = w
    lastBalance = w
    lastW = w
  }

  var can = true
  var step = 1

  while (step < m && can) {
    can = false
	step += 1
    for (balance <- 1 to 9; w <- ws; if w > balance; prev <- ws; if prev != w) {
    	if (dp(step - 1)(balance)(prev) > 0) {
    	  can = true
    	  dp(step)(w - balance)(w) = prev
    	  lastBalance = w - balance
    	  lastW = w
    	}
    }
  }

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

  if (step == m && can) {
  	println( "YES")

  	val sb = Array.ofDim[Int](m)
    while (step > 0) {
      val prev = dp(step)(lastBalance)(lastW)
	  step -= 1
      sb(step) = lastW
      lastBalance = lastW - lastBalance
      lastW = prev
    }
    println(sb.mkString(" "))
  } else println("NO")

  Console.flush
}

import scala.io.StdIn

object XeniaWeights {

  //return the min number in the inarr larger than seed, and avoid the avoid, return 0 if not avail
  def getMin(inarr:Array[Int], seed:Int, avoid:Int):Int={
    for (a<-1 to inarr.length){
      val v = inarr(a-1)
      if (v>seed && v!=avoid){
        return v
      }
    }
    return 0
  }

  def playscale(instr:String, m:Int):List[Int]={
    var inlist:List[Int] = List()
    for (a<-1 to instr.length()){
      if (instr(a-1)!='0'){
        inlist = inlist:+a
      }
    }
    val inarr:Array[Int] = inlist.toArray
    var resList:List[Int] = List()
    var gap=0; //gap weight between current side to the opposite side
    var sums:Array[Int]=Array(0,0)
    var turn=0;
    var lastW=0;
    for (a<-1 to m){
      val w = getMin(inarr, gap, lastW)
      if (w==0){
        return resList
      }else{
        sums(turn) = sums(turn)+w
        resList = resList:+w
        val nextTurn = (turn+1)%2
        gap = sums(turn)-sums(nextTurn)
        turn = nextTurn
        lastW = w
      }
    }
    return resList
  }

  def main(args:Array[String]){
    val instr = StdIn.readLine()
    val m = StdIn.readLine().toInt
    val outList = playscale(instr, m)
    if (outList.length==m){
      println("YES")
      println(outList.mkString(" "))
    }else{
      println("NO")
    }
  }
}

import scala.io.StdIn

object XeniaWeights {
  class WeightNode(val parent:WeightNode, val lastW:Int){
  val turn:Int = if (parent!=null) (parent.turn+1)%2 else 0
  var sumWeight:Array[Int] = Array(0,0)
  if (parent!=null){
    Array.copy(parent.sumWeight, 0, sumWeight, 0, 2)
    sumWeight(parent.turn) = sumWeight(parent.turn) + lastW
  }

  val gap:Int = if (parent!=null) sumWeight(parent.turn)-sumWeight(turn) else 0

  val cl = XeniaWeights.getMin(gap, lastW)

  var children:List[WeightNode] = List()

  val visited:Array[Boolean] = Array.fill(cl.length)(false)

  override def toString():String={
    val str = "Turn:" + turn + ", lastW:" + lastW + ", sw:" + sumWeight.toList + "\n" +
              "cl:"+ cl.toList + "\n"+
              "visited:" + visited.toList + "\n" +
              "children:" + children.toList + "\n"
    str
  }

  //generate the next unvisited child and return it but not mark it, it will be marked while backing up
  def dfsVisit():WeightNode={
    for (a<-1 to cl.length){
      if (!visited(a-1)){
        val w = cl(a-1)
        val wn = new WeightNode(this, w)
        children = children:+wn
        return wn
      }
    }
    return this
  }

  def markVisited(child:WeightNode)={
    for (a<-1 to children.length){
      if (children(a-1)==child){
        visited(a-1)=true
      }
    }
  }

  def allVisited():Boolean={
    for (a<-1 to visited.length){
      if (!visited(a-1)){
        return false;
      }
    }
    return true;
  }
}

  var inarr:Array[Int]=Array();

  //return the list of possible choices from the inarr larger than seed, and avoid the avoid, return 0 if not avail
  def getMin(seed:Int, avoid:Int):List[Int]={
    var ret:List[Int] = List();
    for (a<-1 to inarr.length){
      val v = inarr(a-1)
      if (v>seed && v!=avoid){
        ret = ret:+v
      }
    }
    return ret
  }

  def playscale(instr:String, m:Int):List[Int]={
    var inlist:List[Int] = List()
    for (a<-1 to instr.length()){
      if (instr(a-1)!='0'){
        inlist = inlist:+a
      }
    }
    inarr = inlist.toArray

    var node = new WeightNode(null,0)
    node = node.dfsVisit()
    var depth=1
    var trace:List[WeightNode] = List(node)
    while (depth!=m && node.parent!=null){
      //println(node)
      //println("depth:" + depth)
      //println("traces:" + trace)
      if (node.cl.isEmpty || node.allVisited()){
        //backup
        //println("backup.")
        node.parent.markVisited(node)
        node = node.parent
        depth = depth - 1
        trace = trace.take(trace.length-1)//remove tail
      }
      val pn = node
      node = node.dfsVisit()
      if (pn!=node){
        depth = depth + 1
        trace = trace:+node//append
      }
    }
    trace.map { x => x.lastW }
  }

  def main(args:Array[String]){
    val instr = StdIn.readLine()
    val m = StdIn.readLine().toInt
    val outList = playscale(instr, m)
    if (outList.length==m){
      println("YES")
      println(outList.mkString(" "))
    }else{
      println("NO")
    }
  }
}

import scala.io.StdIn

object Watermelon {

  def canDivide(w:Int):String = {
    if (w>=4 && w%2==0) "YES" else "NO"
  }

  def main(args: Array[String]) {
    val ln:String = StdIn.readLine()
    val weight:Int = ln.toInt
    println(canDivide(weight))
  }
}

import scala.io.StdIn

object XeniaWeights {

  //return the min number in the inarr larger than seed, return 0 if not avail
  def getMin(inarr:Array[Int], seed:Int):Int={
    for (a<-1 to inarr.length){
      if (inarr(a-1)>seed){
        return inarr(a-1)
      }
    }
    return 0
  }

  def playscale(instr:String, m:Int):List[Int]={
    var inlist:List[Int] = List()
    for (a<-1 to instr.length()){
      if (instr(a-1)!='0'){
        inlist = inlist:+a
      }
    }
    val inarr:Array[Int] = inlist.toArray
    var resList:List[Int] = List()
    var gap=0; //gap weight between current side to the opposite side
    var sums:Array[Int]=Array(0,0)
    var turn=0;
    for (a<-1 to m){
      val w = getMin(inarr, gap)
      if (w==0){
        return resList
      }else{
        sums(turn) = sums(turn)+w
        resList = resList:+w
        val nextTurn = (turn+1)%2
        gap = sums(turn)-sums(nextTurn)
        turn = nextTurn
      }
    }
    return resList
  }

  def main(args:Array[String]){
    val instr = StdIn.readLine()
    val m = StdIn.readLine().toInt
    val outList = playscale(instr, m)
    if (outList.length==m){
      println("YES")
      println(outList.mkString(" "))
    }else{
      println("NO")
    }
  }
}


One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

import java.util

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val max = 1000000007;
    val (n, m) = readTuple()
    val A = new Array[Set[Char]](m)
    for(i <- 0 to m - 1)
      A(i) = Set()

    for(i <- 0 to n - 1)
      StdIn.readLine().zipWithIndex.foreach(e=> A(e._2) += e._1)

    println(A.foldLeft(1L)((s,a)=> (s * a.size) % max ))

  }

  def readInt(): Int = StdIn.readInt()

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

  def readTuple(): (Int, Int) = {
    val line = readInts
    (line(0), line(1))
  }

}

import java.util.Scanner
import scala.collection.mutable.Set
object PocketBook {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt
    val m = sc.nextInt
    val sets = new Array[Set[String]](m)
    for (j <- 0 until m) {
      sets(j) = Set()
    }
    for (i <- 0 until n) {
      val cs = sc.next.toCharArray
      for (j <- 0 until m) {
        sets(j) += cs(j).toString
      }
    }
    var l = 1: BigInt;
    for (j <- 0 until m) {
      l *= sets(j).size
    }
    l %= 1000000007
    println(l)
  }
}

import java.util

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val max = 1000000007;
    val (n, m) = readTuple()
    val A = new Array[Set[Char]](m)
    for(i <- 0 to m - 1)
      A(i) = Set()

    for(i <- 0 to n - 1)
      StdIn.readLine().zipWithIndex.foreach(e=> A(e._2) += e._1)

    println(A.foldLeft(1)((s,a)=> (s * a.size) % max ))

  }

  def readInt(): Int = StdIn.readInt()

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

  def readTuple(): (Int, Int) = {
    val line = readInts
    (line(0), line(1))
  }

}


During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai, j ≤ ai + 1, j for all i from 1 to n - 1.Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai, j ≤ ai + 1, j for all i from l to r - 1 inclusive.Alyona is too small to deal with this task and asks you to help!

The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 100 000) — the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table. Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for ai, j (1 ≤ ai, j ≤ 109). The next line of the input contains an integer k (1 ≤ k ≤ 100 000) — the number of task that teacher gave to Alyona. The i-th of the next k lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n).

Print "Yes" to the i-th line of the output if the table consisting of rows from li to ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No".

NoteIn the sample, the whole table is not sorted in any column. However, rows 1–3 are sorted in column 1, while rows 4–5 are sorted in column 3.

//package solutions

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

/**
  * @author traff
  */

object SolTaskC extends App {

  class FastScanner() {

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

    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var st: StringTokenizer = _

    def this(f: String) {
      this()
      br = new BufferedReader(new FileReader(f))
    }

    def this(is: InputStream) {
      this()
      br = new BufferedReader(new InputStreamReader(is))
    }

    private def nextToken() = {
      while (st == null || !st.hasMoreElements) try
        st = new StringTokenizer(br.readLine)

      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      st.nextToken
    }

    def nextInt(): Int = nextToken().toInt

    def nextLong(): Long = nextToken().toLong

    def nextDouble(): Double = nextToken().toDouble
  }

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

    //        run(new FastScanner(), out)
    run(new Scanner(System.in), out)
    out.close()
  }

  //    def run(s: FastScanner, out: PrintWriter): Unit = {
  def run(s: Scanner, out: PrintWriter): Unit = {
    val n = s.nextInt()
    val m = s.nextInt()

    var a = new Array[Array[Int]](m)

    for (i <- 0 until m) {
      a(i) = new Array[Int](n + 2)
    }

    for (j <- 2 to n + 1) {
      for (i <- 0 until m) {
        a(i)(j) = s.nextInt()
      }
    }

    for (i <- 0 until m) {
      var k = 0
      a(i)(0) = 0
      for (j <- 3 to n + 1) {
        if (a(i)(j) < a(i)(j - 1)) {
          k = j
        }
        a(i)(j - 2) = k - 2
      }
    }

    val min_a = Array.fill(n)(Integer.MAX_VALUE)

    for (i <- 0 to n -1) {
      for (j <- 0 until m) {
        if (a(j)(i) < min_a(i)) {
          min_a(i) = a(j)(i)
        }
      }
    }

    val k = s.nextInt()

    for (i <- 1 to k) {
      val l = s.nextInt()
      var r = s.nextInt()

      if (min_a(r - 1) < l) {
        out.println("Yes")
      } else {
        out.println("No")
      }
    }
  }
}

//package solutions

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

import scala.collection.mutable

/**
  * @author traff
  */

object SolTaskC extends App {

  class FastScanner() {

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

    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var st: StringTokenizer = _

    def this(f: String) {
      this()
      br = new BufferedReader(new FileReader(f))
    }

    private def nextToken() = {
      while (st == null || !st.hasMoreElements) try
        st = new StringTokenizer(br.readLine)

      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      st.nextToken
    }

    def nextInt(): Int = nextToken().toInt

    def nextLong(): Long = nextToken().toLong

    def nextDouble(): Double = nextToken().toDouble
  }

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

    run(new FastScanner(), out)

    out.close()
  }

  def run(s: FastScanner, out: PrintWriter): Unit = {
    val n = s.nextInt()
    val m = s.nextInt()

    var a = new Array[Array[Int]](m)

    for (i <- 0 until m) {
      a(i) = new Array[Int](n+2)
    }

    for (j <- 2 to n+1) {
      for (i <- 0 until m) {
        a(i)(j) = s.nextInt()
      }
    }

    for (i <- 0 until m) {

      var k = 0
      a(i)(0) = 0
      for (j <- 3 to n+1) {
        if (a(i)(j) < a(i)(j - 1)) {
          k = j
        }
        a(i)(j-2) = k
      }
    }

    val k = s.nextInt()

    for (i <- 1 to k) {
      val l = s.nextInt()
      var r = s.nextInt()

      if (a.exists(p => p(r - 1) < l)) {
        out.println("Yes")
      } else {
        out.println("No")
      }
    }
  }
}