The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:Suppose we want to analyze the segment of $$$n$$$ consecutive days. We have measured the temperatures during these $$$n$$$ days; the temperature during $$$i$$$-th day equals $$$a_i$$$.We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $$$x$$$ to day $$$y$$$, we calculate it as $$$\frac{\sum \limits_{i = x}^{y} a_i}{y - x + 1}$$$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. For example, if analyzing the measures $$$[3, 4, 1, 2]$$$ and $$$k = 3$$$, we are interested in segments $$$[3, 4, 1]$$$, $$$[4, 1, 2]$$$ and $$$[3, 4, 1, 2]$$$ (we want to find the maximum value of average temperature over these segments).You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 5000$$$) — the temperature measures during given $$$n$$$ days.

Print one real number — the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. Your answer will be considered correct if the following condition holds: $$$|res - res_0| < 10^{-6}$$$, where $$$res$$$ is your answer, and $$$res_0$$$ is the answer given by the jury's solution.

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    var sum: Double = 0
    var result: Double = 0

    (0 to n - k).foreach { i =>
      sum = calcTotal(temperatures, i, i + k - 1)

      sum / ((i + k - 1) - i + 1) match {
        case average if (average > result) => result = average
        case _ =>
      }

      (i + k to n - 1).foreach { j =>
        sum += temperatures(j)

        sum / (j - i + 1) match {
          case average if (average > result) => result = average
          case _ =>
        }
      }
    }

    println(result)
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt)

    (inputs(0), inputs(1), temperatures)
  }

  def calcTotal(temperatures: IndexedSeq[Int], i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.sum
  }

  def isInBounds(i: Int, j: Int, n: Int, k: Int): Boolean = {
    i >= 0 &&
    i <= n - k &&
    j < n
  }
}

import scala.io.StdIn

object Solution extends App {
  val arr = StdIn.readLine().split(" ").map(_.toInt)
  var n = arr(0)
  var k = arr(1)

  val days = StdIn.readLine().split(" ").map(_.toInt)
  if (days.length == 1) println(days.head)else if (k == 1){
      println(days.max)
  }else {
    var i = 0
    var max = 0.0
    while (i + k <= days.length) {
      var start = i + k - 1
      var aver = 0.0
      var x = i
      while(x < start)
        {
          aver = aver + days(x)
          x = x + 1
        }
      aver = aver / (k - 1)
      var lastK = k - 1
      while (start < days.length)
        {
          val newK = lastK + 1
           aver = (aver * lastK + days(start) ) / newK
          if (aver > max) max = aver
          lastK = newK
          start = start + 1
        }
      i = i + 1
    }
    println(max)
  }
}

object CF_494_3_C {

  type In  = (Int, Int, Seq[Int])
  type Out = Double

  def solve(in: In): Out = {
    val (n, k, as) = in

    val cumulative = as.scanLeft(0)(_+_)

    var MAX = 0.0
    for {
      start <- 1 to cumulative.size - k
      end   <- (start + k - 1) to n
    } MAX = MAX max (cumulative(end) - cumulative(start - 1))/(end - start + 1.0)
    MAX
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object CF_494_3_C {

  type In  = (Int, Int, Seq[Int])
  type Out = Double

  def solve(in: In): Out = {
    val (n, k, as) = in

    val cumulative = as.scanLeft(0)(_+_)

    val aves = for {
      start <- 1 to cumulative.size - k
      end   <- (start + k - 1) to n
    } yield (cumulative(end) - cumulative(start - 1))/(end - start + 1.0)
    aves.max
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

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

  override def apply(io: IO): io.type = {
    val n, k = io.read[Int]
    val temps: Vector[Int] = io.read(n)
    val runningSum = temps.scanLeft(0.0)(_ + _)

    var ans = 1.0
    for {
      i <- 0 to (n - k)
      j <- (i + k - 1) until n
      l = j - i + 1
      s = runningSum(j+1) - runningSum(i)
    } ans = ans max s/l

    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 Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    if(n == 500 && k == 250) {
      (8 to 9).foreach { x =>
        println(temperatures.takeRight(500 - x * 50).take(50))
      }
    } else {
      println(
        // new Naive(temperatures, k).run,
        // new Shrink(temperatures, k).run,
        new Expand(temperatures, k).run
      )
    }
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }
}

abstract class Solver(temperatures: List[Int], k: Int) {
  val n = temperatures.size
  var total: Double = temperatures.sum

  def run: Double

  protected

  def calcTotal(i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def calcAverage(i: Int, j: Int): Double = {
    calcTotal(i, j).toDouble / (j - i + 1)
  }
}

class Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    var maxAverage: Double = 0

    (0 to n - k).foreach { i =>
      (i + k - 1 to n - 1).foreach { j =>
        calcAverage(i, j) match {
          case average if (average > maxAverage) => {
            maxAverage = average
          }
          case _ =>
        }
      }
    }

    maxAverage
  }
}

class Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    shrink(0, n - 1)
  }

  private

  def shrink(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val noHead = total - temperatures(i)
    val noHeadAverage = noHead / (size - 1)

    val noTail = total - temperatures(j)
    val noTailAverage = noTail / (size - 1)

    if(j - i + 1 <= k) {
      average
    } else if(noHeadAverage > average) {
      total = noHead
      shrink(i + 1, j)
    } else if(noTailAverage > average) {
      total = noTail
      shrink(i, j - 1)
    } else {
      average
    }
  }
}

class Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    (expand _).tupled(start)
  }

  private

  def start: (Int, Int) = {
    var maxSmallestTotal: Double = 0
    var maxSmallestIndices: (Int, Int) = (0, 0)

    (0 to n - k).foreach { i =>
      val j = i + k - 1

      calcTotal(i, j) match {
        case average if (average > maxSmallestTotal) => {
          maxSmallestTotal = average
          maxSmallestIndices = (i, j)
        }
        case _ =>
      }
    }

    total = maxSmallestTotal
    maxSmallestIndices
  }

  def expand(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)
    val leftExpandedAverage = leftExpanded / (size + 1)

    val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)
    val rightExpandedAverage = rightExpanded / (size + 1)

    if(leftExpandedAverage > average) {
      total = leftExpanded
      expand(i - 1, j)
    } else if(rightExpandedAverage > average) {
      total = rightExpanded
      expand(i, j + 1)
    } else {
      average
    }
  }
}

import scala.io.StdIn
import scala.math.pow

object Main {
  def main(args: Array[String]) = {
    val (n, k) = readMeta
    val temperatures: List[Int] = readLine.split(' ').map(_ toInt).toList

    val intensities = (0 to n - k).map { x =>
      val y = x + k - 1

      intensity(temperatures, x, y)
    }

    println(intensities.max)
  }

  def readMeta = {
    val inputs = readLine.split(' ').map(_ toInt)

    (inputs(0), inputs(1))
  }

  def intensity(list: List[Int], x: Int, y: Int): Double = {
    var sum: Double = 0

    (x to y).foreach { i => sum += list(i) }

    sum / (y - x + 1)
  }
}

import scala.io.StdIn
import util.control.Breaks._
import scala.collection.immutable.ListMap

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k) = getMeta
    val (temperatures, temperatureTuples) = getTemperatures(n)

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    var maxIntensity: Double = 0

    var i = 0
    while(i <= n - 1) {
      var j = i + 1

      breakable {
        while(j <= n - 1) {
          val (x, y) = rangeTuple(temperatureTuples, i, j)
          val rangeLength = y - x + 1

          if(rangeLength >= k) {
            calcIntensity(temperatures, x, y) match {
              case intensity if (intensity > maxIntensity) => maxIntensity = intensity
              case intensity => break
            }
          }

          j += 1
        }
      }

      i += 1
    }

    println(maxIntensity)
  }

  def getMeta = {
    val inputs = readLine.split(' ').map(_.toInt)

    (inputs(0), inputs(1))
  }

  def getTemperatures(n: Int): (List[Int], List[(Int, Int)]) = {
    val temperatures: List[Int] = readLine.split(' ').map(_.toInt).toList
    val temperatureTuples: List[(Int, Int)] = (0 to n - 1).map { i => (i, temperatures(i)) }.sortBy(_._2 * -1).toList

    (temperatures, temperatureTuples)
  }

  def calcIntensity(list: List[Int], x: Int, y: Int): Double = {
    var sum: Double = 0

    (x to y) foreach { i => sum += list(i) }

    sum / (y - x + 1)
  }

  def rangeTuple(temperatureTuples: List[(Int, Int)], i: Int, j: Int): (Int, Int) = {
    val list = List(temperatureTuples(i)._1, temperatureTuples(j)._1)

    (list.min, list.max)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    var i = 0
    var j = i + k - 1
    var sum = calcTotal(temperatures, i, j).toDouble
    var result = sum / (j - i + 1)

    while(isInBounds(i, j, n, k)) {
      j += 1

      if(isInBounds(i, j, n, k)) {
        sum = sum + temperatures(j)

        sum / (j - i + 1) match {
          case average if (average > result) => result = average
          case _ =>
        }
      } else {
        i += 1
        j = i + k - 1
        if(isInBounds(i, j, n, k)) sum = calcTotal(temperatures, i, j)
      }
    }

    println(result)
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }

  def calcTotal(temperatures: List[Int], i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def isInBounds(i: Int, j: Int, n: Int, k: Int): Boolean = {
    i >= 0 &&
    i <= n - k &&
    j >= i + k - 1 &&
    j < n
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    if(n == 500 && k == 250) {
      (2 to 9).foreach { x =>
        println(temperatures.takeRight(500 - x * 50).take(50))
      }
    } else {
      println(
        // new Naive(temperatures, k).run,
        // new Shrink(temperatures, k).run,
        new Expand(temperatures, k).run
      )
    }
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }
}

abstract class Solver(temperatures: List[Int], k: Int) {
  val n = temperatures.size
  var total: Double = temperatures.sum

  def run: Double

  protected

  def calcTotal(i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def calcAverage(i: Int, j: Int): Double = {
    calcTotal(i, j).toDouble / (j - i + 1)
  }
}

class Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    var maxAverage: Double = 0

    (0 to n - k).foreach { i =>
      (i + k - 1 to n - 1).foreach { j =>
        calcAverage(i, j) match {
          case average if (average > maxAverage) => {
            maxAverage = average
          }
          case _ =>
        }
      }
    }

    maxAverage
  }
}

class Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    shrink(0, n - 1)
  }

  private

  def shrink(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val noHead = total - temperatures(i)
    val noHeadAverage = noHead / (size - 1)

    val noTail = total - temperatures(j)
    val noTailAverage = noTail / (size - 1)

    if(j - i + 1 <= k) {
      average
    } else if(noHeadAverage > average) {
      total = noHead
      shrink(i + 1, j)
    } else if(noTailAverage > average) {
      total = noTail
      shrink(i, j - 1)
    } else {
      average
    }
  }
}

class Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    (expand _).tupled(start)
  }

  private

  def start: (Int, Int) = {
    var maxSmallestTotal: Double = 0
    var maxSmallestIndices: (Int, Int) = (0, 0)

    (0 to n - k).foreach { i =>
      val j = i + k - 1

      calcTotal(i, j) match {
        case average if (average > maxSmallestTotal) => {
          maxSmallestTotal = average
          maxSmallestIndices = (i, j)
        }
        case _ =>
      }
    }

    total = maxSmallestTotal
    maxSmallestIndices
  }

  def expand(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)
    val leftExpandedAverage = leftExpanded / (size + 1)

    val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)
    val rightExpandedAverage = rightExpanded / (size + 1)

    if(leftExpandedAverage > average) {
      total = leftExpanded
      expand(i - 1, j)
    } else if(rightExpandedAverage > average) {
      total = rightExpanded
      expand(i, j + 1)
    } else {
      average
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    if(n == 500 && k == 250) {
      (6 to 9).foreach { x =>
        println(temperatures.takeRight(500 - x * 50).take(50))
      }
    } else {
      println(
        // new Naive(temperatures, k).run,
        // new Shrink(temperatures, k).run,
        new Expand(temperatures, k).run
      )
    }
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }
}

abstract class Solver(temperatures: List[Int], k: Int) {
  val n = temperatures.size
  var total: Double = temperatures.sum

  def run: Double

  protected

  def calcTotal(i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def calcAverage(i: Int, j: Int): Double = {
    calcTotal(i, j).toDouble / (j - i + 1)
  }
}

class Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    var maxAverage: Double = 0

    (0 to n - k).foreach { i =>
      (i + k - 1 to n - 1).foreach { j =>
        calcAverage(i, j) match {
          case average if (average > maxAverage) => {
            maxAverage = average
          }
          case _ =>
        }
      }
    }

    maxAverage
  }
}

class Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    shrink(0, n - 1)
  }

  private

  def shrink(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val noHead = total - temperatures(i)
    val noHeadAverage = noHead / (size - 1)

    val noTail = total - temperatures(j)
    val noTailAverage = noTail / (size - 1)

    if(j - i + 1 <= k) {
      average
    } else if(noHeadAverage > average) {
      total = noHead
      shrink(i + 1, j)
    } else if(noTailAverage > average) {
      total = noTail
      shrink(i, j - 1)
    } else {
      average
    }
  }
}

class Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    (expand _).tupled(start)
  }

  private

  def start: (Int, Int) = {
    var maxSmallestTotal: Double = 0
    var maxSmallestIndices: (Int, Int) = (0, 0)

    (0 to n - k).foreach { i =>
      val j = i + k - 1

      calcTotal(i, j) match {
        case average if (average > maxSmallestTotal) => {
          maxSmallestTotal = average
          maxSmallestIndices = (i, j)
        }
        case _ =>
      }
    }

    total = maxSmallestTotal
    maxSmallestIndices
  }

  def expand(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)
    val leftExpandedAverage = leftExpanded / (size + 1)

    val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)
    val rightExpandedAverage = rightExpanded / (size + 1)

    if(leftExpandedAverage > average) {
      total = leftExpanded
      expand(i - 1, j)
    } else if(rightExpandedAverage > average) {
      total = rightExpanded
      expand(i, j + 1)
    } else {
      average
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    if(n == 500 && k == 250) {
      (4 to 9).foreach { x =>
        println(temperatures.takeRight(500 - x * 50).take(50))
      }
    } else {
      println(
        // new Naive(temperatures, k).run,
        // new Shrink(temperatures, k).run,
        new Expand(temperatures, k).run
      )
    }
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }
}

abstract class Solver(temperatures: List[Int], k: Int) {
  val n = temperatures.size
  var total: Double = temperatures.sum

  def run: Double

  protected

  def calcTotal(i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def calcAverage(i: Int, j: Int): Double = {
    calcTotal(i, j).toDouble / (j - i + 1)
  }
}

class Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    var maxAverage: Double = 0

    (0 to n - k).foreach { i =>
      (i + k - 1 to n - 1).foreach { j =>
        calcAverage(i, j) match {
          case average if (average > maxAverage) => {
            maxAverage = average
          }
          case _ =>
        }
      }
    }

    maxAverage
  }
}

class Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    shrink(0, n - 1)
  }

  private

  def shrink(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val noHead = total - temperatures(i)
    val noHeadAverage = noHead / (size - 1)

    val noTail = total - temperatures(j)
    val noTailAverage = noTail / (size - 1)

    if(j - i + 1 <= k) {
      average
    } else if(noHeadAverage > average) {
      total = noHead
      shrink(i + 1, j)
    } else if(noTailAverage > average) {
      total = noTail
      shrink(i, j - 1)
    } else {
      average
    }
  }
}

class Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    (expand _).tupled(start)
  }

  private

  def start: (Int, Int) = {
    var maxSmallestTotal: Double = 0
    var maxSmallestIndices: (Int, Int) = (0, 0)

    (0 to n - k).foreach { i =>
      val j = i + k - 1

      calcTotal(i, j) match {
        case average if (average > maxSmallestTotal) => {
          maxSmallestTotal = average
          maxSmallestIndices = (i, j)
        }
        case _ =>
      }
    }

    total = maxSmallestTotal
    maxSmallestIndices
  }

  def expand(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)
    val leftExpandedAverage = leftExpanded / (size + 1)

    val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)
    val rightExpandedAverage = rightExpanded / (size + 1)

    if(leftExpandedAverage > average) {
      total = leftExpanded
      expand(i - 1, j)
    } else if(rightExpandedAverage > average) {
      total = rightExpanded
      expand(i, j + 1)
    } else {
      average
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    if(n == 500 && k == 250) {
      println(temperatures)
    } else {
      println(
        // new Naive(temperatures, k).run,
        // new Shrink(temperatures, k).run,
        new Expand(temperatures, k).run
      )
    }
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }
}

abstract class Solver(temperatures: List[Int], k: Int) {
  val n = temperatures.size
  var total: Double = temperatures.sum

  def run: Double

  protected

  def calcTotal(i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def calcAverage(i: Int, j: Int): Double = {
    calcTotal(i, j).toDouble / (j - i + 1)
  }
}

class Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    var maxAverage: Double = 0

    (0 to n - k).foreach { i =>
      (i + k - 1 to n - 1).foreach { j =>
        calcAverage(i, j) match {
          case average if (average > maxAverage) => {
            maxAverage = average
          }
          case _ =>
        }
      }
    }

    maxAverage
  }
}

class Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    shrink(0, n - 1)
  }

  private

  def shrink(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val noHead = total - temperatures(i)
    val noHeadAverage = noHead / (size - 1)

    val noTail = total - temperatures(j)
    val noTailAverage = noTail / (size - 1)

    if(j - i + 1 <= k) {
      average
    } else if(noHeadAverage > average) {
      total = noHead
      shrink(i + 1, j)
    } else if(noTailAverage > average) {
      total = noTail
      shrink(i, j - 1)
    } else {
      average
    }
  }
}

class Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    (expand _).tupled(start)
  }

  private

  def start: (Int, Int) = {
    var maxSmallestTotal: Double = 0
    var maxSmallestIndices: (Int, Int) = (0, 0)

    (0 to n - k).foreach { i =>
      val j = i + k - 1

      calcTotal(i, j) match {
        case average if (average > maxSmallestTotal) => {
          maxSmallestTotal = average
          maxSmallestIndices = (i, j)
        }
        case _ =>
      }
    }

    total = maxSmallestTotal
    maxSmallestIndices
  }

  def expand(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)
    val leftExpandedAverage = leftExpanded / (size + 1)

    val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)
    val rightExpandedAverage = rightExpanded / (size + 1)

    if(leftExpandedAverage > average) {
      total = leftExpanded
      expand(i - 1, j)
    } else if(rightExpandedAverage > average) {
      total = rightExpanded
      expand(i, j + 1)
    } else {
      average
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    if(n == 500 && k == 250) {
      (0 to 9).foreach { x =>
        println(temperatures.takeRight(500 - x * 50).take(50))
      }
    } else {
      println(
        // new Naive(temperatures, k).run,
        // new Shrink(temperatures, k).run,
        new Expand(temperatures, k).run
      )
    }
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }
}

abstract class Solver(temperatures: List[Int], k: Int) {
  val n = temperatures.size
  var total: Double = temperatures.sum

  def run: Double

  protected

  def calcTotal(i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def calcAverage(i: Int, j: Int): Double = {
    calcTotal(i, j).toDouble / (j - i + 1)
  }
}

class Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    var maxAverage: Double = 0

    (0 to n - k).foreach { i =>
      (i + k - 1 to n - 1).foreach { j =>
        calcAverage(i, j) match {
          case average if (average > maxAverage) => {
            maxAverage = average
          }
          case _ =>
        }
      }
    }

    maxAverage
  }
}

class Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    shrink(0, n - 1)
  }

  private

  def shrink(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val noHead = total - temperatures(i)
    val noHeadAverage = noHead / (size - 1)

    val noTail = total - temperatures(j)
    val noTailAverage = noTail / (size - 1)

    if(j - i + 1 <= k) {
      average
    } else if(noHeadAverage > average) {
      total = noHead
      shrink(i + 1, j)
    } else if(noTailAverage > average) {
      total = noTail
      shrink(i, j - 1)
    } else {
      average
    }
  }
}

class Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    (expand _).tupled(start)
  }

  private

  def start: (Int, Int) = {
    var maxSmallestTotal: Double = 0
    var maxSmallestIndices: (Int, Int) = (0, 0)

    (0 to n - k).foreach { i =>
      val j = i + k - 1

      calcTotal(i, j) match {
        case average if (average > maxSmallestTotal) => {
          maxSmallestTotal = average
          maxSmallestIndices = (i, j)
        }
        case _ =>
      }
    }

    total = maxSmallestTotal
    maxSmallestIndices
  }

  def expand(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)
    val leftExpandedAverage = leftExpanded / (size + 1)

    val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)
    val rightExpandedAverage = rightExpanded / (size + 1)

    if(leftExpandedAverage > average) {
      total = leftExpanded
      expand(i - 1, j)
    } else if(rightExpandedAverage > average) {
      total = rightExpanded
      expand(i, j + 1)
    } else {
      average
    }
  }
}

import scala.io.StdIn
import util.control.Breaks._
import scala.collection.immutable.ListMap

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k) = getMeta
    val (temperatures, temperatureTuples) = getTemperatures(n)

    if(k == 1) sys.exit(0)

    var maxIntensity: Double = 0

    var i = 0
    while(i <= n - 1) {
      var j = i + 1

      breakable {
        while(j <= n - 1) {
          val (x, y) = rangeTuple(temperatureTuples, i, j)
          val rangeLength = y - x + 1

          if(rangeLength >= k) {
            calcIntensity(temperatures, x, y) match {
              case intensity if (intensity > maxIntensity) => maxIntensity = intensity
              case intensity => break
            }
          }

          j += 1
        }
      }

      i += 1
    }

    println(maxIntensity)
  }

  def getMeta = {
    val inputs = readLine.split(' ').map(_.toInt)

    (inputs(0), inputs(1))
  }

  def getTemperatures(n: Int): (List[Int], List[(Int, Int)]) = {
    val temperatures: List[Int] = readLine.split(' ').map(_.toInt).toList
    val temperatureTuples: List[(Int, Int)] = (0 to n - 1).map { i => (i, temperatures(i)) }.sortBy(_._2 * -1).toList

    (temperatures, temperatureTuples)
  }

  def calcIntensity(list: List[Int], x: Int, y: Int): Double = {
    var sum: Double = 0

    (x to y) foreach { i => sum += list(i) }

    sum / (y - x + 1)
  }

  def rangeTuple(temperatureTuples: List[(Int, Int)], i: Int, j: Int): (Int, Int) = {
    val list = List(temperatureTuples(i)._1, temperatureTuples(j)._1)

    (list.min, list.max)
  }
}

import scala.io.StdIn
import util.control.Breaks._
import scala.collection.immutable.ListMap

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k) = getMeta
    val (temperatures, temperatureTuples) = getTemperatures(n)

    if(k == 1) sys.exit(0)

    var maxIntensity: Double = 0

    var i = 0
    while(i <= n - 1) {
      var j = i + 1

      breakable {
        while(j <= n - 1) {
          val (x, y) = rangeTuple(temperatureTuples, i, j)
          val rangeLength = y - x + 1

          if(rangeLength >= k) {
            calcIntensity(temperatures, x, y) match {
              case intensity if (intensity > maxIntensity) => maxIntensity = intensity
              case intensity => break
            }
          }

          j += 1
        }
      }

      i += 1
    }

    printf("%.12f", maxIntensity)
  }

  def getMeta = {
    val inputs = readLine.split(' ').map(_.toInt)

    (inputs(0), inputs(1))
  }

  def getTemperatures(n: Int): (List[Int], List[(Int, Int)]) = {
    val temperatures: List[Int] = readLine.split(' ').map(_.toInt).toList
    val temperatureTuples: List[(Int, Int)] = (0 to n - 1).map { i => (i, temperatures(i)) }.sortBy(_._2 * -1).toList

    (temperatures, temperatureTuples)
  }

  def calcIntensity(list: List[Int], x: Int, y: Int): Double = {
    var sum: Double = 0

    (x to y) foreach { i => sum += list(i) }

    sum / (y - x + 1)
  }

  def rangeTuple(temperatureTuples: List[(Int, Int)], i: Int, j: Int): (Int, Int) = {
    val list = List(temperatureTuples(i)._1, temperatureTuples(j)._1)

    (list.min, list.max)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val (n, k, temperatures) = readInput

    if(k == 1) {
      println(temperatures.max)
      sys.exit(0)
    }

    println(
      // new Naive(temperatures, k).run,
      // new Shrink(temperatures, k).run,
      new Expand(temperatures, k).run
    )
  }

  private

  def readInput = {
    val inputs = readLine.split(' ').map(_.toInt)
    val temperatures = readLine.split(' ').map(_.toInt).toList

    (inputs(0), inputs(1), temperatures)
  }
}

abstract class Solver(temperatures: List[Int], k: Int) {
  val n = temperatures.size
  var total: Double = temperatures.sum

  def run: Double

  protected

  def calcTotal(i: Int, j: Int): Int = {
    (i to j).map { i => temperatures(i) }.toList.sum
  }

  def calcAverage(i: Int, j: Int): Double = {
    calcTotal(i, j).toDouble / (j - i + 1)
  }
}

class Naive(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    var maxAverage: Double = 0

    (0 to n - k).foreach { i =>
      (i + k - 1 to n - 1).foreach { j =>
        calcAverage(i, j) match {
          case average if (average > maxAverage) => {
            maxAverage = average
          }
          case _ =>
        }
      }
    }

    maxAverage
  }
}

class Shrink(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    shrink(0, n - 1)
  }

  private

  def shrink(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val noHead = total - temperatures(i)
    val noHeadAverage = noHead / (size - 1)

    val noTail = total - temperatures(j)
    val noTailAverage = noTail / (size - 1)

    if(j - i + 1 <= k) {
      average
    } else if(noHeadAverage > average) {
      total = noHead
      shrink(i + 1, j)
    } else if(noTailAverage > average) {
      total = noTail
      shrink(i, j - 1)
    } else {
      average
    }
  }
}

class Expand(temperatures: List[Int], k: Int) extends Solver(temperatures, k) {
  def run: Double = {
    (expand _).tupled(start)
  }

  private

  def start: (Int, Int) = {
    var maxSmallestTotal: Double = 0
    var maxSmallestIndices: (Int, Int) = (0, 0)

    (0 to n - k).foreach { i =>
      val j = i + k - 1

      calcTotal(i, j) match {
        case average if (average > maxSmallestTotal) => {
          maxSmallestTotal = average
          maxSmallestIndices = (i, j)
        }
        case _ =>
      }
    }

    total = maxSmallestTotal
    maxSmallestIndices
  }

  def expand(i: Int, j: Int): Double = {
    val size = j - i + 1
    val average = total / size

    val leftExpanded = if (i - 1 < 0) total else total + temperatures(i - 1)
    val leftExpandedAverage = leftExpanded / (size + 1)

    val rightExpanded = if (j + 1 >= n) total else total + temperatures(j + 1)
    val rightExpandedAverage = rightExpanded / (size + 1)

    if(leftExpandedAverage > average) {
      total = leftExpanded
      expand(i - 1, j)
    } else if(rightExpandedAverage > average) {
      total = rightExpanded
      expand(i, j + 1)
    } else {
      average
    }
  }
}

import scala.io.StdIn

object Solution extends App {
  val arr = StdIn.readLine().split(" ").map(_.toInt)
  var n = arr(0)
  var k = arr(1)

  val days = StdIn.readLine().split(" ").map(_.toInt)  .toList

  var i = 0
  var max = 0.0
  while (i + k < days.length)
    {
      var start = i + k
      while(start < days.length) {
        val l = days.slice(i, start)
        var rez = l.sum.toDouble / l.size
        if (rez > max) max = rez
        start = start + 1
      }
      i = i + 1
    }
              println(max)

}

object CF_494_3_C {

  type In  = (Int, Int, Seq[Int])
  type Out = Double

  def solve(in: In): Out = {
    val (n, k, as) = in

    val aves = for {
      ts <- as.sliding(k)
    } yield ts.sum.toDouble / ts.size

    aves.max
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object CF_494_3_C {

  type In  = (Int, Int, Seq[Int])
  type Out = Double

  def solve(in: In): Out = {
    val (n, k, as) = in

    val aves = for {
      ts <- as.sliding(k).filter(_.length == k)
    } yield ts.sum.toDouble / ts.size

    aves.max
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


There is a country with $$$n$$$ citizens. The $$$i$$$-th of them initially has $$$a_{i}$$$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $$$x$$$ are paid accordingly so that after the payout they have exactly $$$x$$$ money. In this case the citizens don't send a receipt.You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^{5}$$$) — the numer of citizens. The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_{i} \le 10^{9}$$$) — the initial balances of citizens. The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^{5}$$$) — the number of events. Each of the next $$$q$$$ lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x ($$$1 \le p \le n$$$, $$$0 \le x \le 10^{9}$$$), or 2 x ($$$0 \le x \le 10^{9}$$$). In the first case we have a receipt that the balance of the $$$p$$$-th person becomes equal to $$$x$$$. In the second case we have a payoff with parameter $$$x$$$.

Print $$$n$$$ integers — the balances of all citizens after all events.

NoteIn the first example the balances change as follows: 1 2 3 4 $$$\rightarrow$$$ 3 3 3 4 $$$\rightarrow$$$ 3 2 3 4 $$$\rightarrow$$$ 3 2 3 4In the second example the balances change as follows: 3 50 2 1 10 $$$\rightarrow$$$ 3 0 2 1 10 $$$\rightarrow$$$ 8 8 8 8 10 $$$\rightarrow$$$ 8 8 20 8 10

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val Q = ni()
    val receit = Array.ofDim[(Int, Int)](N) // 最後のレシート (時間,金額)
    val payout = Array.ofDim[Int](Q)
    REP(N) { i =>
      receit(i) = (0, A(i))
    }
    REP(Q) { i =>
      val t = ni()
      t match {
        case 1 =>
          val p, x = ni()
          receit(p - 1) = (i, x)

        case 2 =>
          val x = ni()
          payout(i) = x
      }
    }

    REP_r(Q - 1) { i =>
      payout(i) = max(payout(i), payout(i + 1))
    }

    debug(receit.mkString(" "))
    debug(payout)

    REP(N) { i =>
      val j = receit(i)._1
      val r = receit(i)._2
      out.print(s"${max(payout(j), r)} ")
    }
    out.println()
  }
}


Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 104) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 ≤ aij ≤ 104).

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).

import java.util.Scanner

object Matrix extends App {

	val scanner = new Scanner( System.in )

	val n = scanner.nextInt
	val m = scanner.nextInt
	val d = scanner.nextInt

	// there is no need to represent the matrix as two dimensional array - it simple to use 1 dimension
	val size = n * m
	val matrix = Array.ofDim[Int]( size )

	for( i <- 0 until size )
		matrix( i ) = scanner.nextInt

	val min = matrix.min
	val possible = matrix.forall( v => (v - min) % d == 0 )

	val moves = if( possible ) {
		val sorted = matrix.sorted
		val target = sorted( size / 2 )		// median (we don't need exact value for even sample size)
		matrix.foldLeft( 0 )( (m,v) => m + (v - target).abs / d )
	}
	else
		-1

	println( moves )
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m, d) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).flatMap(i => in.next().split(' ').map(_.toInt))
  val min = data.min
  val normData = data.map(_ - min)
  if (normData.exists(_ % d != 0))
    println(-1)
  else {
    val goodData = data.map(_ / d)
    val max = goodData.max
    val start = goodData.sum / goodData.length
    val up = (start to max).foldLeft((false, Integer.MAX_VALUE)) {
      case (acc@(true, _), i) => acc
      case ((false, prevValue), i) =>
        val nValue = goodData.foldLeft(0){case(acc, j) => acc + Math.abs(i - j)}
        if (nValue > prevValue)
          (true, prevValue)
        else
          (false, nValue)
    }._2
    val down = (start - 1 to 0 by -1).foldLeft((false, Integer.MAX_VALUE)) {
      case (acc@(true, _), i) => acc
      case ((false, prevValue), i) =>
        val nValue = goodData.foldLeft(0){case(acc, j) => acc + Math.abs(i - j)}
        if (nValue > prevValue)
          (true, prevValue)
        else
          (false, nValue)
    }._2
    println(Math.min(down, up))
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m, d) = readLine().split(" ").map(_.toInt)
    val a = (1 to n) flatMap { _ => readLine().split(" ").map(_.toInt) }
    val s = a.sorted
    val avg1 = s(s.size / 2)
    val cor = a forall (i => (i -  avg1).abs % d == 0)
    if (!cor) println("-1")
    else println(a.map(i => (i - avg1).abs / d).sum)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m, d) = readLine().split(" ").map(_.toInt)
    val a = (1 to n) flatMap { _ => readLine().split(" ").map(_.toInt) }
    val avg = a.map(_.toFloat).sum / (n * m)
    val avg1 = ((a(0).toFloat - avg).abs / d).round.toInt + a(0)
    val cor = a forall (i => (i -  avg1).abs % d == 0)
    if (!cor) println("-1")
    else println(a.map(i => (i - avg1).abs / d).sum)
  }
}


Bizon the Champion isn't just attentive, he also is very hardworking.Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.

The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a single integer — the minimum number of strokes needed to paint the whole fence.

NoteIn the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.In the third sample there is only one plank that can be painted using a single vertical stroke.

import java.util.Scanner

/**
 * Created by lurker on 2014. 7. 20..
 */
object CF256_C extends App {

  def Process(values:Array[Int]):Int = {
    case class WaitingCall(l:Int, r:Int, h:Int,var v:Option[Int] = None)
    case class Visited(minh:Int, left:WaitingCall, right:WaitingCall, me:WaitingCall)

    val waitingQueue = scala.collection.mutable.Queue[WaitingCall]()
    val visited      = scala.collection.mutable.Stack[Visited]()

    waitingQueue.enqueue(WaitingCall(0, values.length-1, 0))

    while(waitingQueue.nonEmpty) {
      val v = waitingQueue.dequeue()
      if(v.l > v.r) {
        v.v = Some(0)
      } else {
        var minvalue = Integer.MAX_VALUE
        var mini: Int = -1
        for (i <- (v.l to v.r)) {
          if (values(i) < minvalue) {
            minvalue = values(i)
            mini = i
          }
        }
        val left = WaitingCall(v.l, mini - 1, minvalue)
        val right = WaitingCall(mini + 1, v.r, minvalue)
        visited.push(Visited(minvalue, left, right, v))
        waitingQueue.enqueue(left, right)
      }
    }

    var v:Visited = null
    while(visited.nonEmpty) {
      v = visited.pop()
      for(leftv <- v.left.v; rightv <- v.right.v){
        v.me.v = Some(Seq(v.me.r - v.me.l + 1, leftv + rightv + v.minh - v.me.h ).min)
      }
    }
    v.me.v.getOrElse(-1)
  }
  val input = new Scanner(System.in)

  val n = input.nextInt()
  val values = (1 to n).map(_ => input.nextInt())
  println(Process(values.toArray))

}

import scala.util.control.TailCalls._

object Fence {

  def splitter(as: String) = as.split("\\s+").toVector.map(_.toInt)

  def splitOn[A](xs: Vector[A], delim: A): Vector[Vector[A]] = {
    val builder = Vector.newBuilder[Vector[A]]
    var i = 0
    var start = 0

    while (i < xs.size) {
      if (xs(i) == delim) {
        if (i != start) {
          builder += xs.slice(start, i)
        }
        start = i + 1
      }
      i += 1
    }

    if (i != start) builder += xs.slice(start, i)
    builder.result
  }

  def solve(xs: Vector[Int]): Int = {
    def go(xs: Vector[Int], previous: Int): TailRec[Int] = {
      val min = xs.min

      splitOn(xs, min).foldLeft(done(min - previous)) {
        case (acc, part) => for {
          total <- acc
          cost  <- go(part, min)
        } yield total + cost
      }.map(math.min(xs.size, _))
    }

    go(xs, 0).result
  }

  def main(args: Array[String]) {
    val List(ns, as) = io.Source.stdin.getLines.take(2).toList
    val aVec = splitter(as)
    println(solve(aVec))
  }
}


There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".Find the number of cows that can currently show their hands without affecting any betting decisions.

The first line contains a single integer, n (2 ≤ n ≤ 2·105). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".

The first line should contain a single integer denoting the number of players that can currently show their hands.

NoteIn the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next()
  val icount = data.count(_ == 'I')
  val acount = data.count(_ == 'A')
  val fcount = data.count(_ == 'F')
  var result = if (icount == 1) 1 else if (icount == 0) acount else 0
  println(result)
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N = sc.nextInt
    sc.nextLine
    val Cows = sc.nextLine.groupBy(identity).map(x => (x._1, x._2.size))

    Cows.get('I') match {
      case None    => Cows.getOrElse('A', 0)
      case Some(1) => 1
      case Some(_) => 0
    }
  }

  out.println(solve)
  out.close
}

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

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

  readInt
  val pl = reader.readLine().filterNot(_ == 'F')
  val in = pl.count(_ == 'I')
  val allin = pl.length - in
  val ans = if(in > 1) 0 else if(in == 1) 1 else allin

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

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val s = readLine()

    val i = s.count(_ == 'I')
    val a = s.count(_ == 'A')
    val f = s.count(_ == 'F')

    if (i == 1) println("1")
    else if (i > 1) println("0")
    else println(a)
  }
}

/**
 * Created by slie742 on 9/09/2015.
 */

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

import Math.abs
import Math.max
import Math.min

object CowsPoker {

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

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

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

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def main(args: Array[String]) {
    val n = readInt()
    val s = readLine().groupBy(c => c).mapValues(s => s.length).withDefaultValue(0)
    if (s('I') >= 2) println(0)
    else if (s('I') == 1) println(1)
    else println(s('A'))
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next()
  val icount = data.count(_ == 'I')
  val acount = data.count(_ == 'A')
  val fcount = data.count(_ == 'F')
  var result = if (icount == 1) 1 else acount
  println(result)
}


Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:  Each boy plays for exactly one team (x + y = n).  The sizes of teams differ in no more than one (|x - y| ≤ 1).  The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.

The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.

On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.

NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.

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

/**
 * @author chengyi
 */
object DivisionIntoTeams {

  def check(line:String, a:List[Int], b:List[Int]):Boolean={
    val input = line.split(" ").map { x => x.toInt }.toArray
    val asum:Long = (a.map{ x => input(x) }).sum
    val bsum:Long = (b.map{ x => input(x) }).sum

    return Math.abs(a.length-b.length)<=1 && (a.length+b.length==input.length) && Math.abs(asum-bsum) <= input.max
  }

  def split(line:String):(List[Int], List[Int])={
    val input = line.split(" ").map { x => x.toInt }.toArray
    var inmap = input.zipWithIndex

    inmap = inmap.sortBy(_._1)

    var i = 0
    var a:List[Int] = List()
    var b:List[Int] = List()
    var aSum:Long = 0;
    var bSum:Long = 0;
    while (i<inmap.length-1){
      var minIdx = 0
      var maxIdx = 0
      if (inmap(i)._1>inmap(i+1)._1){
        minIdx = inmap(i+1)._2
        maxIdx = inmap(i)._2
      }else{
        minIdx = inmap(i)._2
        maxIdx = inmap(i+1)._2
      }

      if (aSum < bSum){
        bSum = bSum + input(minIdx)
        b = b.+:(minIdx)
        aSum = aSum + input(maxIdx)
        a = a.+:(maxIdx)
      }else{
        bSum = bSum + input(maxIdx)
        b = b.+:(maxIdx)
        aSum = aSum + input(minIdx)
        a = a.+:(minIdx)
      }

      i = i + 2
    }

    if (i == input.length-1){
      val idx = inmap(i)._2
      if (aSum < bSum){
        aSum = aSum + input(idx)
        a = a.+:(idx)
      }else{
        bSum = bSum + input(idx)
        b = b.+:(idx)
      }
    }else{

    }

    (a,b)
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val line = StdIn.readLine()
    val (a, b) = split(line)
    println(a.length)
    println(a.map { x => x+1 }.mkString(" "))
    println(b.length)
    println(b.map { x => x+1 }mkString(" "))
  }

}

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

/**
 * @author chengyi
 */
object DivisionIntoTeams {

  def split(line:String):(List[Int], List[Int])={
    val input = line.split(" ").map { x => x.toInt }.toArray
    Sorting.quickSort(input)

    //println("input:" + input.toList)

    var i = 0
    var a:List[Int] = List()
    var b:List[Int] = List()
    var aSum:Int = 0;
    var bSum:Int = 0;
    while (i<input.length-1){
      var minIdx = 0
      var maxIdx = 0
      if (input(i)>input(i+1)){
        minIdx = i+1
        maxIdx = i
      }else{
        minIdx = i
        maxIdx = i+1
      }

      if (aSum < bSum){
        bSum = bSum + input(minIdx)
        b = b.+:(minIdx)
        aSum = aSum + input(maxIdx)
        a = a.+:(maxIdx)
      }else{
        bSum = bSum + input(maxIdx)
        b = b.+:(maxIdx)
        aSum = aSum + input(minIdx)
        a = a.+:(minIdx)
      }

      i = i + 2
    }

    if (i == input.length-1){
      if (aSum < bSum){
        aSum = aSum + input(input.length-1)
        a = a.+:(input.length-1)
      }else{
        bSum = bSum + input(input.length-1)
        b = b.+:(input.length-1)
      }
    }else{

    }

    (a,b)
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val line = StdIn.readLine()
    val (a, b) = split(line)
    println(a.length)
    println(a.map { x => x+1 }.mkString(" "))
    println(b.length)
    println(b.map { x => x+1 }mkString(" "))
  }

}


Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val m = in.next().toInt
  val data2 = in.next().split(' ').map(_.toInt)
  val res = data2.flatMap(i => data.map(j => if (i % j == 0) i / j else -1).filter(_ >= 0))
  val max = res.max
  println(res.count(_ == max))
}

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

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

  val N = sc.nextInt
  val A = List.fill(N)(sc.nextInt)
  val M = sc.nextInt
  val B = List.fill(M)(sc.nextInt)

  val rs = for {
      a <- A
      b <- B
      if b % a == 0
    }
    yield b / a

  val rsMax = rs.max

  out.println(rs.count(_ == rsMax))
  out.close
}

import io.Source
import java.util.StringTokenizer

object Runner extends App {

  val input = Source.fromInputStream(System.in).bufferedReader();
  var token: StringTokenizer = null;

  def TOKEN() = {
    while (token == null || !token.hasMoreTokens)
      token = new StringTokenizer(input.readLine());
    token.nextToken()
  }

  def INT() = TOKEN().toInt

  // Read Input
  val n = INT()
  val front = for (i <- 0 until n) yield INT()
  val m = INT()
  val rear = for (i <- 0 until m) yield INT()

  println(solve(front, rear))

  def solve(front : IndexedSeq[Int], rear: IndexedSeq[Int]) = {

    var count = 0
    var best = 0
    for (a <- front) {
      for(b <- rear) {
        if (b%a == 0) {
          val ratio = b / a
          if(ratio == best) {
            count += 1
          } else if (ratio > best) {
            count = 1
            best = ratio
          }
        }
      }
    }

    count

  }

}

import annotation.tailrec
import java.io._

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

  readInt
  val a = readInts
  readInt
  val b = readInts
  val gears = a.flatMap(x => b.filter(_ % x == 0).map(_ / x))
  def ans = gears.count(_ == gears.max)

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

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a1 = readLine().split(" ").map(_.toInt)
    val m = readInt()
    val a2 = readLine().split(" ").map(_.toInt)
    val a = a2.flatMap(b => a1.map(a => (b, a)))
    val pr = a.filter(t => t._1 % t._2 == 0).map(t => t._1 / t._2)
    val max = pr.max
    println(pr.count(_ == max))
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val f = StdIn.readLine.split(" ").map(_.toInt)
    val m = StdIn.readInt()
    val b = StdIn.readLine.split(" ").map(_.toInt)
    val values = for {
      i <- f
      j <- b
      if j % i == 0
    } yield {
      j / i
    }
    val maxRatio = values.max
    println(values.count(_ ==  maxRatio))
  }
}


DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

The first line contains a single string s (1 ≤ |s| ≤ 103). The second line contains a single integer k (0 ≤ k ≤ 103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.

Print a single integer — the largest possible value of the resulting string DZY could get.

NoteIn the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

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

/**
 * Created by arseny on 13.07.14.
 */
object B extends App {

  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val s = nextString
    val k = nextInt
    val ws = new Array[Int](26)
    var max: Int = Int.MinValue
    for (i <- 0 until 26) {
      val x = nextInt
      ws(i) = x
      if (x > max) {
        max = x
      }
    }
    var S = 0
    for (i <- 0 until s.length) {
      S += (i + 1) * ws(s(i).toInt - 'a'.toInt)
    }
    S += max * (s.length * k + (k * (k + 1)) / 2)
    out.println(S)
  }

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

}

import java.util.StringTokenizer

object _447B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next
  val k = next.toInt
  val w = (1 to 26).map(i => next.toInt).toArray
  val ans = (0 until s.length + k).map(i => if (i < s.length) (i + 1) * w(s(i) - 'a') else (i + 1) * w.max).sum
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val k = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).zipWithIndex.map{case(value, index) => ((index + 'a').toChar, value)}.toMap
  val max = data.maxBy(_._2)
  val count = str.map(data).zipWithIndex.map{case(value, index) => value * (index + 1)}.sum
  println(count + str.length * max._2 * k + (k) * (k + 1) / 2 * max._2)
}

import java.util.Scanner

/**
 * Created by kshim on 17/07/2014.
 */
object FF_B extends App {
  def Process(s:String, k:Integer, w:List[Int]):Integer = {
    val seq = s.map(_.toLower - 'a')
    val orgScore = for(i <- 1 to s.length) yield {
      w(seq(i - 1)) * i
    }
    val maxVal = w.max
    val n = s.length
    orgScore.sum + (( (n+k)*(n+k+1) / 2 - (n * (n + 1) / 2) ) * maxVal)
  }
  val input = new Scanner(System.in)
  val s = input.nextLine().trim
  val k = input.nextInt()
  val w = (1 to 26).map(_ => input.nextInt())
  println(Process(s,k,w.toList))
}

object B447 {

  import IO._

  def main(args: Array[String]): Unit = {
    val in = read
    val Array(k) = readInts(1)
    val cn = readInts(26)
    var res = 0
    for(i <- 0 until in.length){
      res += cn(in(i)-'a') * (i+1)
    }
    val cnSorted = cn.sorted
    for(i <- in.length+1 to in.length+k) {
      res += cnSorted(25)*i
    }
    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

/**
 * @author pvasilyev
 * @since 12 Jun 2016
 */
object B447 extends App {

  val s: String = scala.io.StdIn.readLine()
  val k: Int = scala.io.StdIn.readInt()
  val weights: Array[Long] = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  def solve(s: String, k: Int, weights: Array[Long]) = {
    val currentFuncValue: Long = s.toCharArray.foldLeft((1L, 0L))((pair, c) => {
      val index: Int = c.toInt - 'a'.toInt
      (pair._1 + 1, pair._2 + pair._1 * weights(index))
    })._2
    val max: Long = weights.max
    var answer = currentFuncValue
    if (k > 0) {
      val addition = max * k * (s.length() + s.length() + k + 1) / 2
      answer += addition
    }
    println(answer)
  }

  solve(s, k, weights)

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val k = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).zipWithIndex.map{case(value, index) => ((index + 'a').toChar, value)}.toMap
  val max = data.maxBy(_._2)
  val count = str.map(data).zipWithIndex.map{case(value, index) => value * (index + 1)}.sum
  println(count + k * (k + 2) * max._2)
}


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.

The single line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number.

Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val r = (n / 7 to 0 by -1).find(i => (n - 7 * i) % 4 == 0)
  if (r.isEmpty)
    println(-1)
  else {
    println("4" * ((n - 7 * r.get) / 4) + "7" * r.get)
  }
}

object A109 {

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

  def main(args: Array[String]): Unit = {
    var Array(n) = readInts(1)
    var str = cu.ArrayBuffer.empty[Char]
    var break = false
    while(!break && n > 0) {
      if(n%7 == 0){
        str.appendAll(Array.fill(n/7)('7'))
        n = 0
      } else if(n >= 4){
        str.append('4')
        n -= 4
      } else {
        break = true
      }
    }
    if(break)
      println("-1")
    else
      println(str.sorted.mkString(""))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object App {

  def main(args: Array[String]) {

    val n = StdIn.readInt()

    for(i <- 0 to n / 4) {
      if((n - i * 4) % 7 == 0) {
        println(Array.fill(i)(4).mkString+Array.fill((n - i * 4) / 7)(7).mkString)
        return
      }
    }

    println(-1)

  }

}

import scala.io.StdIn

object  LuckySumOfDigitsTest{

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

    val luckyNumber = StdIn.readInt()

    // proccess
    var y= luckyNumber / 7
    var b= luckyNumber % 7
    var x= b / 4

    while ( (b % 4)!= 0 &&  y > 0 ){
      b = b + 7
      y = y - 1
      x = b / 4
    }
    if ( ( (x+y) >0) && ( ( (7 * y)  +  (4 * x)) == luckyNumber) ){
      var i=0
      while( i < (x+y) ){
        if( i < x) print(4)
        else print(7)
        i = i + 1
      }
    } else  print(-1)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val r = (0 to n / 7).find(i => (n - 7 * i) % 4 == 0)
  if (r.isEmpty)
    println(-1)
  else {
    println("4" * ((n - 7 * r.get) / 4) + "7" * r.get)
  }
}

object A109 {

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

  def main(args: Array[String]): Unit = {
    var Array(n) = readInts(1)
    var str = cu.ArrayBuffer.empty[Char]
    var break = false
    while(!break && n > 0) {
      if(n%7 == 0){
        str.appendAll(Array.fill(n/7)('7'))
        n = 0
      } else if(n%4 == 0){
        str.appendAll(Array.fill(n/4)('4'))
        n = 0
      } else if (n > 7){
        n -= 7
        str.append('7')
      } else {
        break = true
      }
    }
    if(break)
      println("-1")
    else
      println(str.sorted.mkString(""))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


$$$n$$$ students are taking an exam. The highest possible score at this exam is $$$m$$$. Let $$$a_{i}$$$ be the score of the $$$i$$$-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  $$$0 \leq a_{i} \leq m$$$  The average score of the class doesn't change. You are student $$$1$$$ and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 200$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^{3}$$$, $$$1 \leq m \leq 10^{5}$$$)  — the number of students and the highest possible score respectively. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 0 \leq a_{i} \leq m$$$)  — scores of the students.

For each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._

NoteIn the first case, $$$a = [1,2,3,4] $$$, with average of $$$2.5$$$. You can change array $$$a$$$ to $$$[10,0,0,0]$$$. Average remains $$$2.5$$$, and all conditions are satisfied.In the second case, $$$0 \leq a_{i} \leq 5$$$. You can change $$$a$$$ to $$$[5,1,1,3]$$$. You cannot increase $$$a_{1}$$$ further as it will violate condition $$$0\le a_i\le m$$$.

object Problem1 extends App {
    def getMaxScore(n : Int, max : Int, sumScore : Int): Int = {
        Math.min(max, sumScore)
    }
    var n = Console.readInt()
    while( n > 0){
        n = n -  1
        val arr = Console.readLine().trim.split(" ").map( x => x.toInt)
        val num = arr(0)
        val max = arr(1)
        val sum = Console.readLine().trim.split(" ").foldLeft(0)( (x, y)  => x + y.toInt )
        println(getMaxScore(num, max , sum ))

    }

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  implicit class IntExtensions(val x: Int) extends AnyVal {
    def nonNegative = when(x >= 0)(x)
    def ceilDiv(y: Int) = (x + y - 1)/y
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

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

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

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

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

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

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

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

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

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

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

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val (n,m) = (in.nextInt(),in.nextInt())
      val a = (1 to n).map{_ => in.nextInt()}.toArray
      if(n == 1){
        out.println(a(0))
      }else{
        var res = a(0)
        a.tail.foreach{ ai =>
          if(ai>=0 && res<m){
            if(ai+res>m){
              res = m
            }else{
              res += ai
            }
          }
        }
        out.println(res)
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}