import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  val Array(n, m) = readInts(2)

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) out.println(mstWeight)
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      out.println(mstWeight - maxW + edge.w)
    }
  }

  out.close()
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  //new Thread(null, new Main, "", 32 * 1024 * 1024).start()

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  val Array(n, m) = readInts(2)

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      ancestorsBuilder.sizeHint(ancestors(prev).length + 1)
      maxWBuilder.sizeHint(ancestors(prev).length + 1)
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val res = Array.ofDim[Long](m)

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) res(i) = mstWeight
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

  out.println(res.mkString("\n"))
  out.close()
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  val Array(n, m) = readInts(2)

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      //ancestorsBuilder.sizeHint(ancestors(prev).length + 1)
      //maxWBuilder.sizeHint(ancestors(prev).length + 1)
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val res = Array.ofDim[Long](m)

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) res(i) = mstWeight
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

  out.println(res.mkString("\n"))
  out.close()
}

import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.BitSet
import java.io.PrintWriter

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size) { 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  val Array(n, m) = readInts(2)

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](2 * m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    edges(i + m) = edge.reverse
  }

  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Int]](n)

  def levelAncestor(_v: Int, depth: Int): (Int, Int) = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = Math.max(maxW, maxWs(v)(i))
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): Int = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) maxW
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = Math.max(Math.max(maxW, maxWs(u)(i)), maxWs(v)(i))
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      Math.max(Math.max(maxW, maxWs(u)(0)), maxWs(v)(0))
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)
  val onMst = new BitSet(m)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (edge <- edges.take(m).sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
      adjBuilders(edge.u) += edge.id
      adjBuilders(edge.v) += edge.id + m
    }
  }

  val adjs = adjBuilders.map(_.result)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofInt

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max = w
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = Math.max(max, maxWs(prev)(i))
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    var i = 0
    while (i < adjs(u).length) {
      val e = edges(adjs(u)(i))
      if (e.v != parent) dfs(e.v, u, depth + 1, e.w)
      i += 1
    }
  }

  dfs(0, -1, 0, 0) // prepare

  val res = Array.ofDim[Long](m)

  val out = new PrintWriter(System.out)
  for (i <- 0 until m) {
    if (onMst(i)) res(i) = mstWeight
    else {
      val edge = edges(i)
      val maxW = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString("\n"))
  Console.flush
  //out.println(res.mkString("\n"))
  //out.close()
}

import scala.collection.mutable.ArrayBuilder
import scala.util.Sorting
import scala.collection.mutable.BitSet

object E extends App {

  final class UnionFind(size: Int) {

    private val height = Array.fill(size){ 0 }
    private val parent = Array.tabulate(size)(identity)

    def find(x: Int): Int = {
      if (parent(x) == x) x
      else {
        parent(x) = find(parent(x))
        parent(x)
      }
    }

    def union(x: Int, y: Int) {
      val px = find(x)
      val py = find(y)
      if (height(px) < height(py)) {
        parent(px) = py
      } else {
        parent(py) = px
        if (height(px) == height(py)) height(px) += 1
      }
    }

    def same(x: Int, y: Int) = find(x) == find(y)

  }

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

  val Array(n, m) = readInts(2)

  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofRef[Edge] }

  case class Edge(u: Int, v: Int, w: Int, id: Int) {
    def reverse = copy(u = v, v = u)
  }

  val edges = Array.ofDim[Edge](m)

  for (i <- 0 until m) {
    val Array(u, v, w) = readInts(3)
    val edge = Edge(u - 1, v - 1, w, i)
    edges(i) = edge
    adjBuilders(edge.u) += edge
    adjBuilders(edge.v) += edge.reverse
  }

  val adjs = adjBuilders.map(_.result)

  val res = Array.ofDim[Long](m)
  val onMst = new BitSet(m)
  val depths = Array.ofDim[Int](n)
  val ancestors = Array.ofDim[Array[Int]](n)
  val maxWs = Array.ofDim[Array[Long]](n)

  def dfs(u: Int, parent: Int, depth: Int, w: Int): Unit = {

    depths(u) = depth

    val ancestorsBuilder = new ArrayBuilder.ofInt
    val maxWBuilder = new ArrayBuilder.ofLong

    if (parent >= 0) {
      var i = 0
      var prev = parent
      var max: Long = w
      ancestorsBuilder += parent
      maxWBuilder += max
      while (prev > 0 && i < ancestors(prev).length) {
        max = max max maxWs(prev)(i)
        maxWBuilder += max
        prev = ancestors(prev)(i)
        ancestorsBuilder += prev
        i += 1
      }
    }

    ancestors(u) = ancestorsBuilder.result
    maxWs(u) = maxWBuilder.result

    for (e <- adjs(u)) {
      if (e.v != parent && onMst(e.id)) dfs(e.v, u, depth + 1, e.w)
    }
  }

  def levelAncestor(_v: Int, depth: Int): (Int, Long)  = {
    var v = _v
    var i = ancestors(v).length - 1
    var maxW = 0L
    while (i >= 0) {
      if (i < ancestors(v).length && depths(ancestors(v)(i)) >= depth) {
        maxW = maxW max maxWs(v)(i)
        v = ancestors(v)(i)
      }
      i -= 1
    }
    (v, maxW)
  }

  def lowestCommonAncestor(_v: Int, _u: Int): (Int, Long) = {
    var (v0, u) = if (depths(_v) < depths(_u)) (_u, _v) else (_v, _u)
    var (v, maxW) = levelAncestor(v0, depths(u))
    // now depths(v) == depths(u)
    if (v == u) (v, maxW)
    else {
      var i = ancestors(v).length - 1
      while (i >= 0) {
        if (i < ancestors(u).length && ancestors(u)(i) != ancestors(v)(i)) {
          maxW = maxW max maxWs(u)(i) max maxWs(v)(i)
          u = ancestors(u)(i)
          v = ancestors(v)(i)
        }
        i -= 1
      }
      (ancestors(v)(0), maxW)
    }
  }

  var mstWeight = 0L
  val uf = new UnionFind(n)

  for (edge <- edges.sortBy(_.w)) {
    if (!uf.same(edge.u, edge.v)) {
      uf.union(edge.u, edge.v)
      mstWeight += edge.w
      onMst += edge.id
    }
  }

  dfs(0, -1, 0, 0) // prepare

  for (edge <- edges) {
    if (onMst(edge.id)) res(edge.id) = mstWeight
    else {
      val (_, maxW) = lowestCommonAncestor(edge.u, edge.v)
      res(edge.id) = mstWeight - maxW + edge.w
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.mkString("\n"))
  Console.flush
}


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

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

  type Lever = Array[Char]
  val lever: Lever = sc.nextLine.toArray

  def solve(): String = {
    val pivot: Int = lever.indexOf('^')
    val lhs = lever.slice(0, pivot).reverse
    val rhs = lever.slice(pivot + 1, lever.length)

    def moment(l: Lever): Long = {

      def w(c: Char): Long = if (c == '=') 0l
                             else (c - '0').toLong

      var res = 0l
      0 until l.size foreach { i => res += (i + 1) * w(l(i)) }
      res
    }

    val rm = moment(rhs)
    val lm = moment(lhs)

    if (lm > rm) "left"
    else if (lm < rm) "right"
    else "balance"
  }

  out.println(solve)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val s = readLine()
    val i = s.indexOf('^')
    val sum = s.zipWithIndex.map{ case (c, j) =>
      c match {
        case '=' | '^' => 0
        case '1' => 1L * (i - j).toLong
        case '2' => 2L * (i - j).toLong
        case '3' => 3L * (i - j).toLong
        case '4' => 4L * (i - j).toLong
        case '5' => 5L * (i - j).toLong
        case '6' => 6L * (i - j).toLong
        case '7' => 7L * (i - j).toLong
        case '8' => 8L * (i - j).toLong
        case '9' => 9L * (i - j).toLong
      }
    }.sum
    sum match {
      case 0L => println("balance")
      case i: Long if i > 0L => println("left")
      case i: Long if i < 0L => println("right")
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var str = in.next().split('^')
  val left = str.head.reverse.zipWithIndex.foldLeft(0l){
    case(sum, ('=', index)) => sum
    case(sum, (el, index)) => sum + 1l * el.asDigit * (index + 1)
  }
  val right = str.last.zipWithIndex.foldLeft(0l){
    case(sum, ('=', index)) => sum
    case(sum, (el, index)) => sum + 1l * el.asDigit * (index + 1)
  }
  if (left == right)
    println("balance")
  else if (left > right)
    println("left")
  else
    println("right")
}

object A376 {

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

  def main(args: Array[String]): Unit = {
    var Array(left, right) = read.split('^')
    left = left.reverse
    var lw = 0L
    for(i <- 0 until left.length if left(i).isDigit) {
      lw += (i+1)*(left(i)-'0')
    }
    var rw = 0L
    for(i <- 0 until right.length if right(i).isDigit) {
      rw += (i+1)*(right(i)-'0')
    }
    if(rw == lw) {
      println("balance")
    } else if (rw > lw) {
      println("right")
    } else {
      println("left")
    }
  }

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

    @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 java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random

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

  type Lever = Array[Char]

  val lever: Lever = sc.nextLine.toArray
  val N: Int = lever.length

  def solve(): String = {

    @inline
    def w(c: Char): Long = {
      if (c == '=') 0l
      else (c - '0').toLong
    }

    val pivot: Int = {
      var i = 0
      while (lever(i) != '^') i += 1
      i
    }

    val lhs: Long = {
      var i = pivot - 1
      var res = 0l
      while (i >= 0) {
        res += (pivot - i) * w(lever(i))
        i -= 1
      }
      res
    }

    val rhs: Long = {
      var i = pivot + 1
      var res = 0l
      while (i < N) {
        res += (i - pivot) * w(lever(i))
        i += 1
      }
      res
    }

    if (lhs > rhs) "left"
    else if (lhs < rhs) "right"
    else "balance"
  }

  out.println(solve)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val s = readLine()
    val i = s.indexOf('^')
    val sum = s.zipWithIndex.map{ case (c, j) =>
      c match {
        case '=' | '^' => 0
        case '1' => 1 * (i - j)
        case '2' => 2 * (i - j)
        case '3' => 3 * (i - j)
        case '4' => 4 * (i - j)
        case '5' => 5 * (i - j)
        case '6' => 6 * (i - j)
        case '7' => 7 * (i - j)
        case '8' => 8 * (i - j)
        case '9' => 9 * (i - j)
      }
    }.sum
    sum match {
      case 0 => println("balance")
      case i: Int if i > 0 => println("left")
      case i: Int if i < 0 => println("right")
    }
  }
}


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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val arr = Array.fill(m, n)(in.nextInt - 1)
    val pos = Array.fill(m, n)(0)
    (0 until m).foreach { i =>
      (0 until n).foreach { j =>
        pos(i)(arr(i)(j)) = j
      }
    }
    var ans: Long = 0
    var i = 0

    @inline def ok(x: Int, y: Int): Boolean = (1 until m).forall(i => pos(i)(x) + 1 == pos(i)(y))

    while (i < n) {
      val c = i
      while (i < n - 1 && ok(arr(0)(i), arr(0)(i + 1))) {
        i += 1
      }
      i += 1
      ans += (i - c).toLong * (i - c + 1) / 2
    }

    println(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(0)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case 0 => if (j + 1 < n) input(i)(j + 1) else -1 // uninitialized

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != -1 => -1 // discarding now

          case y => y // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Long): Long = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList, 0, 0))
  }

}

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A, R = Array.ofDim[Int](N)
    rep(N) { i =>
      A(i) = ni() - 1
      R(A(i)) = i
    }

    val flag = Array.fill[Boolean](N - 1)(true)
    rep(M - 1) { _ =>
      val B = Array.ofDim[Int](N)
      rep(N) { i => B(i) = ni() - 1 }

      rep(N - 1) { i =>
        val ix = R(B(i))
        if (ix < N - 1) flag(ix) &= A(ix + 1) == B(i + 1)
      }
      val ix = R(B(N - 1))
      if (ix != N - 1) {
        flag(ix) = false
      }
    }

    var ans: Long = N
    var cnt = 0
    rep(flag.length) { i =>
      if (flag(i)) {
        cnt += 1
      } else {
        cnt = 0
      }
      ans += cnt
    }

    out.println(ans)
  }

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

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

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

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

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

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(-2)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case -2 => if (j + 1 < n) input(i)(j + 1) else 0                          // uninitialized

          case -1 => -1                                                             // already discarded

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now

          case y => y                                                               // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList, 0, 0))
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(0)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case 0 => if (j + 1 < n) input(i)(j + 1) else -1 // uninitialized

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != -1 => -1 // discarding now

          case y => y // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList, 0, 0))
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(-2)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case -2 => if (j + 1 < n) input(i)(j + 1) else 0 // uninitialized

          case -1 => -1 // already discarded

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now

          case y => y // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + (if (n > 1) computeResult(input(0).toList, 0, 0) else 0))
  }

}

//package codeforces

object MysteriousCrime {

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

    val input = new Array[Array[Int]](m)

    val trackNext = Array.fill(n + 1)(-2)

    (0 until m).foreach(i => {

      input(i) = io.StdIn.readLine.split(" ").map(_.toInt)

      (0 until n).foreach(j => {

        trackNext(input(i)(j)) = trackNext(input(i)(j)) match {

          case -2 => if (j + 1 < n) input(i)(j + 1) else 0                          // uninitialized

          case -1 => -1                                                             // already discarded

          case x if j + 1 < n && x != input(i)(j + 1) || j + 1 == n && x != 0 => -1 // discarding now

          case y => y                                                               // all cool bro
        }
      })

    })

    def computeResult(ls: List[Int], counter: Int, res: Int): Int = {

      ls match {

        case Nil => res

        case h :: t if trackNext(h) == -1 => computeResult(t, 0, res)

        case h :: t if trackNext(h) != -1 => computeResult(t, counter + 1, res + counter + 1)

      }

    }

    println(n + computeResult(input(0).toList.tail, 0, 0))
  }

}


object GolfedVersion extends App {
    val sc = new java.util.Scanner(System.in)
    val n0, k0 = sc.nextInt

    def loop(i: Int, n: Int, k: Int): Option[Map[Int, Int]] =
      if (k > n || k < 1) None
      else if (n/2 >= k)  loop(i*2, n/2, k - n%2).map(_ + (i -> n%2))
      else                Some(Map(i*2 -> (n-k), i -> (n - (n-k)*2)))

    print(loop(1, n0, k0).fold("NO")(m =>
      "YES\n" + (for {
        (k, v) <- m.toSeq.sorted
         e     <- Seq.fill(v)(k)
      } yield e).mkString(" ")
    ))
}

object CF_529_3_C {

  type In = (Int, Int)
  type Out = String

  def solve(in: In): Out = {
    val (n0, k0) = in

    def loop(i: Int, bs: Vector[Int], e: Int): Option[Vector[Int]] = (i, e, bs(i)) match {
        // Reached 0, no more to split
      case (0, 0, _)          => Some(bs)
        // Reached 0, nonzero splits required
      case (0, _, _)          => None
        // No splits required, move to next index
      case (_, _, _) if e < 1 => loop(i-1, bs, e)
        // No digits left to split, move to next index
      case (_, _, 0)          => loop(i-1, bs, e)
        // Split a digit
      case (_, _, b)          => loop(i, bs.updated(i-1, bs(i-1) + 2).updated(i, b-1), e - 1)
    }

    val bs = BigInt(n0).toString(2).toVector.map(_.asDigit).reverse

    loop(bs.length - 1, bs, k0 - bs.sum) match {
      case None => "NO"
      case Some (xs) =>
        val seq = for {
            (x, i) <- xs.zipWithIndex
            if x > 0
            e <- Seq.fill(x)(math.pow(2, i).toInt)
          } yield e
        "YES\n" + seq.mkString (" ")
    }
  }

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

  def formatIn(i: Input): In       = (i.int, i.int)
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  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(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 solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  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_529_3_C {

  type In = (Int, Int)
  type Out = String

  def solve(in: In): Out = {
    val (n0, k0) = in

    def loop(i: Int, n: Int, k: Int): Option[Map[Int, Int]] =
      if (k > n || k < 1) None
      else if (n/2 >= k)
        // join as many as possible
        loop(i * 2, n/2, k - n%2).map(_ + (i -> n%2))
      else {
        // only join as many as required. c = number to join
       val c = n - k
        Some(Map(i * 2 -> c, i -> (n - c*2)))
      }

    loop(1, n0, k0) match {
      case None => "NO"
      case Some(m) =>
        val seq = for {
          (k, v) <- m.toSeq.sorted
           e     <- Seq.fill(v)(k)
        } yield e
        "YES\n" + seq.mkString(" ")
    }
  }

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

  def formatIn(i: Input): In       = (i.int, i.int)
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  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(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 solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  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 Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val A = Integer.toBinaryString(N).map(_ - '0').toArray
    val n = A.length
    val cnt = Integer.bitCount(N)
    var k = K - cnt
    var d = 0
    while(k > 0 && d < n - 1) {
      if (A(d) > 0) {
        A(d) -= 1
        A(d + 1) += 2
        k -= 1
      } else {
        d += 1
      }
    }

//    debug(A.mkString)

    if (k == 0) {
      out.println("YES")
      val ans = ArrayBuffer[Int]()
      REP(n) { d =>
        val num = 1 << (n - 1 - d)
        REP(A(d)) { _ =>
          ans += num
        }
      }
      out.println(ans.reverse.mkString(" "))
    } else {
      out.println("NO")
    }
  }

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

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

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

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

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

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

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


object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    if (n == 1 || m == 1 || n == m && n == 2) println("YES")
    else println("NO")
  }
}

import scala.io.StdIn.readLine

object A {
  def solution(n: Int, m: Int): Boolean =
    n == 1 || m == 1 || (n == 2 && m == 2)

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(n, m) = readLine.split(" ").toSeq.map(_.toInt)
      println(if (solution(n, m)) "YES" else "NO")
    }
  }
}

import scala.io.StdIn._

object PuzzlePieces {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    loopWithIndex(n) { i =>
      val l = readLine.split(" ").map(_.toInt).toList
      val c = l(0)
      val r = l(1)
      if (c == 1 || r == 1) println("YES")
      else
        if (c > 2 || r > 2) println("NO")
        else println("YES")
    }
  }

  def loopWithIndex[T](n: Int)(block: Int => T) =
    (1 to n).foreach(e => block(e))
}

object ProblemA extends App {
  import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

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

  val n = in.nextInt()

  for (i <- 1 to n) {
    val m = in.nextInt()
    val n = in.nextInt()

    if ((n == 1 || m == 1) || (n == 2 && m == 2)) {
      println("YES")
    } else {
      println("NO")
    }
  }

}

import scala.io.StdIn._

object PuzzlePieces {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    loopWithIndex(n) { i =>
      val l = readLine.split(" ").map(_.toInt).toList
      val c = l(0)
      val r = l(1)
      if ((c == 1 && r == 3) || (c == 3 && r == 1)) println("YES")
      else
        if (c > 2 || r > 2) println("NO")
        else println("YES")
    }
  }

  def loopWithIndex[T](n: Int)(block: Int => T) =
    (1 to n).foreach(e => block(e))
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (f, s) = in.next().split(' ').map(_.toInt).foldLeft(101, 101) {
    case ((min, second), el) if el < min =>
      (el, min)
    case ((min, second), el) if el < second && el != min =>
      (min, el)
    case (acc, el) => acc
  }
  if (s == 101)
    println("NO")
  else
    println(s)
}

object Flask {
  def main(args: Array[String]): Unit = {
    readLine
    var data = readLine.split(" ").map(_.toInt)
    if (data.size < 2) { println("NO"); return; }

    var first: Option[Int] = None
    var second: Option[Int] = None
    data.foreach(x => x match {
      case x if first == None || x < first.get => { second = first; first = Some(x) }
      case x if first.get != x && (second == None || x < second.get) => { second = Some(x) }
      case _ => {}
    })
    println( if (second == None) "NO" else second.get)
  }
}

object A22 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n).distinct.sorted
    if(input.length == 1) {
      out.println("NO")
    } else {
      out.println(input(1))
    }
    out.close()
  }

  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")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var arr = readLine.split(" ").toList.map(_.toInt);
    var min = arr.min;
    var arrf = arr.filter(p => p != min);
    var result = "NO"
    if (!arrf.isEmpty)
      result = arrf.min.toString;
    println(result);
  }

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt).toSet.toSeq
    a.sorted.drop(1).headOption match {
      case None => println("NO")
      case Some(i) => println(i)
    }
  }
}

object Flask {
  def main(args: Array[String]): Unit = {
    readLine
    var data = readLine.split(" ").map(_.toInt)
    if (data.size < 3) { println("NO"); return; }

    var first: Option[Int] = None
    var second: Option[Int] = None
    data.foreach(x => x match {
      case x if first == None || x < first.get => { second = first; first = Some(x) }
      case x if first.get != x && (second == None || x < second.get) => { second = Some(x) }
      case _ => {}
    })
    println(second.get)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val (f, s) = in.next().split(' ').map(_.toInt).foldLeft(-101, -101) {
    case ((max, second), el) if el > max =>
      (el, max)
    case ((max, second), el) if el > second && el != max =>
      (max, el)
    case (acc, el) => acc
  }
  if (s == -101)
    println("NO")
  else
    println(s)

}


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

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

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


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