import scala.Predef._

object Main {
  def main(args: Array[String]) {
    val a = readLine().split(" ").map(_.toInt)
    val t = a(1)
    val raw = readLine()
    var s = raw.toCharArray
    for (_ <- 1 to t) {
      var bi = -1
      for (i <- 0 until s.size) {
        if (bi == -1) {
          if (s(i) == 'B') {
            bi = i
          }
        } else {
          if (s(i) == 'G') {
            s(i) = 'B'
            s(bi) = 'G'
            bi = -1
          } else {
            bi = i
          }
        }
      }
    }
    println(s.mkString(""))
  }
}


import scala.io.StdIn.readLine

object Puzzles {
  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val nums = readLine().split(" ").map(_.toInt).sorted
    val ans = nums.sliding(n).map(x => x.last - x.head).min
    println(ans)
  }
}


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

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

  val N = sc.nextInt
  val answer: String = {
    if (N <= 2) "-1"
    else List.range(1, N + 1).reverse.mkString(" ")
  }

  out.println(answer)
  out.close
}


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

import scala.annotation.tailrec

object A {
  def solve(in: Input, out: Output): Unit = {
    val n, m = in.nextInt()
    out.println(if (n < 31) m & ((1 << n) - 1) else m)
  }

  class Input(in: InputStream) extends Closeable {
    private[this] val br = new BufferedReader(new InputStreamReader(in))
    private[this] var st = new StringTokenizer(br.readLine())

    override def close(): Unit = br.close()

    @tailrec
    final def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    final def nextInt(): Int = next().toInt
    final def nextLong(): Long = next().toLong
    final def nextDouble(): Double = next().toDouble
  }

  final type Output = PrintWriter

  def main(args: Array[String]): Unit = {
    val in = new Input(System.in)
    val out = new Output(System.out)
    solve(in, out)
    out.close()
    in.close()
  }
}


object test5 extends App {
    val mod=1073741824
    var sum=0
    val map=collection.mutable.Map[Int,Int]()
    map(1)=1
    val Array(a,b,c)=readLine.split(" ").map(_.toInt)

    val list=for(i<-1 to a; j<-1 to b; k<-1 to c) yield
    {
        getNum(i*j*k)
    }:Long

    println(list.sum%mod)

    def getNum(num:Int)={
        def count()={
            var total=2
            for(i<-2 to math.sqrt(num).toInt)
            	 if(num%i==0)
            	     if(i*i==num) total+=1 else total+=2

            map(num)=total
            total
        }

        map.get(num) match{
            case None=>count()
            case _=>map(num)
        }
    }
}


import scala.io.StdIn

object Cookies {

  var result:Array[Int] = null

  def cookNum(n:Int):Int={
    if (n==0)
      return 1
    result = Array.fill(n)(1)
    for (a<-1 to n-1){
      result(a) = result(a-1)*3 % (1000003)
    }
    result(n-1)
  }

  def main(args:Array[String])={
    val n = StdIn.readLine().toInt
    println(cookNum(n))
  }

}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(a, b) = in.next().split(' ').map(_.toLong)
  if (a == b)
    println("infinity")
  else if (b > a)
    println(0)
  else {
    val ab = a - b
    println((1 to Math.sqrt(ab).toInt).foldLeft(0){
      case(acc, j) =>
        if (ab % j == 0 && a % (ab / j) == b) {
          if (ab / j != j && a % j == b)
            acc + 2
          else
            acc + 1
        }
        else acc
    })
  }
}


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, B = nl()
    val F = factorize(B)
    val C = mutable.HashMap[Long, Long]().withDefaultValue(0)
    F.keys.foreach { f =>
      var c = 0L
      var d = f
      while(d <= N) {
        c += N / d
        if (d <= (N - 1) / f + 1) d *= f
        else d = N + 1
      }
//      debug(s"$f $c")
      C(f) = c
    }

//    C.foreach { case (k, v) => debug(s"$k $v") }
    val ans = F.map { case (f, cnt) =>
//      debug(s"$f $cnt")
      C(f) / cnt
    }.min

    out.println(ans)
  }

  /**
    * *注意* 10^12以上ぐらいからは使わないこと
    */
  def factorize(n: Long): mutable.Map[Long, Long] = {
    import scala.collection.mutable
    val res = mutable.Map[Long, Long]() withDefaultValue 0

    def minFactor(n0: Long, rt: Int, i: Int): Long = {
      if (i > rt) n0 // √n まで見つからなかったら n0は素数か1
      else if (n0 % i == 0) i
      else minFactor(n0, rt, i + 1)
    }

    def step(n0: Long): Unit = {
      minFactor(n0, math.sqrt(n0).toInt, 2) match {
        case 1 =>
        case f =>
          res(f) = res(f) + 1
          step(n0 / f)
      }
    }

    step(n)
    res
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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


import java.util
import scala.collection.JavaConverters._

object CF518_2_B {
  def solve(b: Long): Long = {
    val pfs = Utility.primeFactors(b)
//    println("b = "+b)
//    println(pfs.asScala.toList)
    val ns = pfs.asScala.groupBy(identity).mapValues(_.size).values
    ns.map(_+1).product
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in)
//    val io = new IO("7169516929")
    val solution = solve(io.long())
    println(solution)
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
      // Euclid's algorithm
      def gcd(a: Long, b: Long): Long = b match {
        case 0 => a
        case _ => gcd(b, a % b)
      }
      // lcm(a,b) = abs(a*b)/gcd(a,b)
      def lcm(a: Long, b: Long) = math.abs(a)/gcd(a,b)*math.abs(b)

      // These were written in Java then auto-converted by IntelliJ to Scala... so ugly!
      def primesFromSieve(upto: Int): util.BitSet = { // true means it's a prime
        val bs: util.BitSet = new util.BitSet(upto + 1)
        // even numbers aren't prime, so we initialize intelligently. Takes ~ 15% of total method run time for 1e8
        // (future optimization if required: try initializing as longs with value 0x01010101010101...)
        bs.set(2)
        locally {var i: Int = 3
        while ( {
          i <= upto
        }) {
          bs.set(i)
          i += 2
        }}
        // end of initialization.
        val max: Int = Math.sqrt(upto).toInt
        // nextSetBit returns -1 if none exists so we have to check that i is still > 0
        locally { var i: Int = 3
        while ( {
          i <= max && i > 0
        }) {
          var j: Int = i * 2
          while ( {
            j < upto
          }) {
            bs.clear(j)

            j += i
          }

          i = bs.nextSetBit(i + 2)
        }}
        bs
      }

      def primeFactors(x: Long): util.ArrayList[Long] = {
        val factors = new util.ArrayList[Long]
        if (x < 2) return factors
        val maxPrimeFactor = Math.sqrt(x).toInt
        val allPrimes = primesFromSieve(maxPrimeFactor)
        var remaining = x
        var trial = 2L
        while ( {
          trial * trial <= remaining && trial > -1
        }) if (remaining % trial == 0) { // trial is prime factor of x
          factors.add(trial)
          remaining = remaining / trial
        }
        else trial = allPrimes.nextSetBit(trial.toInt + 1)
        factors.add(remaining)
        factors
      }

    }
}


import annotation.tailrec, collection.mutable, util.control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _560C extends CodeForcesApp[Int]({scanner => import scanner._
  val Seq(a1, a2, a3, a4, a5, a6) = Seq.fill(6)(nextInt)
  val t1 = a1 + a2 + a3
  val t2 = a3 + a4 + a5
  val t3 = a5 + a6 + a1
  require(t1 == t2 && t2 == t3)
  t1*t1 - a1*a1 - a3*a3 - a5*a5
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final def isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None
  final def counter[A] = collection.mutable.Map.empty[A, Int] withDefaultValue 0
  final def yesNo(result: Boolean) = if (result) "YES" else "NO"
}


object Codeforces158A extends App {

  import io.StdIn._

  val Array(n, k) = readLine().split(" ").map(_.toInt)
  val nn = readLine().split(" ").map(_.toInt)

  val limit = nn(k - 1)

  val count = nn.fold(0) { (count, i) => if (i >= limit && i > 0) count + 1 else count}
  println(count)

}


import java.util.Scanner

object Solution {
  def main(args: Array[String]) : Unit =  {
    solve()
  }
  def solve() = {
    val sc = new Scanner(System.in)
    val (x1 , y1 , x2 , y2 , a , b) = (sc.nextInt() , sc.nextInt() , sc.nextInt(), sc.nextInt() , sc.nextInt() , sc.nextInt())

    val result =
      if (Math.abs(x2 - x1) % a != 0 | Math.abs(y2 - y1) % b != 0) {
        false
      } else {
        (Math.abs(x2 - x1)/a)%2 == (Math.abs(y2 - y1)/b)%2
      }
    print(if(result)"YES" else "NO")
  }
}


import java.util.Scanner

object Main {
  case class Point(var x: Int, y: Int)

  val in = new Scanner(System.in)

  def main(args: Array[String]): Unit = {
    val n = in.nextInt()
    if (n <= 2) {
      print(0)
      return
    }
    print(n/2 + n%2 - 1)
  }
}


object B extends App {

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

  val Array(n, t) = readInts(2)
  val as = readInts(n)
  val cnts = Array.fill(as.max + 1) { 0L }
  for (a <- as) cnts(a) += 1

  val l = n * t min 2 * n * n

  val minByLen = Array.fill(l) { 0 }

  var i, len = 0

  while (i < l) {

    var lo = 0
    var hi = len - 1
    val a = as(i % n)

    while (lo <= hi) {
      val mid = (lo + hi) >> 1
      if (as(minByLen(mid) % n) <= a) lo = mid + 1
      else hi = mid - 1
    }

    minByLen(lo) = i
    if (lo == len) len += 1

    i += 1
  }

  val res = len + (if (2 * n < t) (t - 2 * n) * cnts.max else 0)

  println(res)
}


import scala.io.StdIn

object Task479A {
	def main(args: Array[String]) {
		println(max(Array(StdIn.readInt(), StdIn.readInt(), StdIn.readInt())))
	}

	def max(nums: Array[Int]) = nums.count(_ == 1) match {
		case 0 => var m = 1; nums.foreach(m *= _); m
		case (1 | 2) => nums indexOf 1 match {
			case 0 => if (nums(2) == 1) nums.sum else (1 + nums(1)) * nums(2)
			case 2 => nums(0) * (nums(1) + 1)
			case 1 => if (nums(0) <= nums(2)) (nums(0) + 1) * nums(2) else nums(0) * (1 + nums(2))
		}
		case _ => nums.sum
	}
}


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

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

  val S = sc.nextLine.toCharArray
  val T = sc.nextLine.toCharArray.toList

  val answer: Int = {
    @tailrec
    def loop(i: Int, ts: List[Char]): Int = ts match {
        case Nil => i
        case x :: xs => {
          if (x == S(i)) loop(i + 1, xs)
          else loop(i, xs)
        }
      }
    loop(0, T) + 1
  }

  out.println(answer)
  out.close
}


object scala{
    def main(args: Array[String]): Unit ={
        val a = readLine.toInt
        (0 until a).foreach{
            _ =>
            val N = readLine.toInt
            val res = Math.sqrt(N).toInt +
              Math.cbrt(N).toInt -
             (Math.sqrt(Math.cbrt(N))).toInt
             println(res)
        }
    }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(r, c) = in.next().split(" ").map(_.toInt)
  val rows = Array.ofDim[Boolean](r)
  val columns = Array.ofDim[Boolean](c)
  Range(0, r).foreach { i =>
    val str = in.next()
    Range(0, str.length).foreach { j =>
      if (str.charAt(j) == 'S') {
        rows(i) = true
        columns(j) = true
      }
    }
  }

  val rc = rows.count(!_)
  val cc = columns.count(!_)
  println(rc * c + cc * (r - rc) )
}


/**
  * Created by octavian on 28/02/2016.
  */
object Orchestra {

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

    //System.setIn(new FileInputStream("./src/orchestra.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/orchestra.out")))

    val Array(r, c, n, k) = readLine().split(" ").map(_.toInt)
    var grid: Array[Array[Int]] = Array.ofDim[Int](r, c)

    for(i <- 0 until r) {
      for(j <- 0 until c) {
        grid(i)(j) = 0
      }
    }

    for(i <- 0 until n) {
      val Array(x, y): Array[Int] = readLine().split(" ").map(_.toInt)
      grid(x - 1)(y - 1) = 1
      //println("grid is: " + grid(x - 1)(y - 1))
    }

    var res = 0
    for(lb <- 0 until r) {
      for(le <- lb until r) {
        for(rb <- 0 until c) {
          for(re <- 0 until c) {
            if(matches(grid, lb, le, rb, re, k)) {
              res += 1
            }
          }
        }
      }
    }
    println(res)
  }

  def matches(grid: Array[Array[Int]], lb: Int, le: Int, rb: Int, re: Int, k: Int): Boolean = {
    //println("testing: " + lb + ", " + le + ", " + rb + ", " + re)
    var count = 0
    for(i <- lb to le) {
      for(j <- rb to re) {
        if(grid(i)(j) == 1) {
          count += 1
        }
      }
    }
    return count >= k
  }

}


object Main {
  def main(args: Array[String]) {
    val s = readLine()
    val danger = s.sliding(7).foldLeft(false) { (acc, s) =>
      if (s == "1111111" || s == "0000000") true
      else acc
    }
    if (danger) println("YES")
    else println("NO")
  }
}


object A761 {

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

  def main(args: Array[String]): Unit = {
    val Array(a,b) = readInts(2)
    if(a == 0 && b == 0)
      println("NO")
    else if(a == b || a+1 == b || b+1 == a)
      println("YES")
    else
      println("NO")
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val T = na(N)
    val ans = Array.ofDim[Int](N)

    REP(N - 1, 1) { i =>
      sort(T, 0, i)
      var m = 0
      var j = 0
      while(j < i && m + T(j) <= M - T(i)) {
        m += T(j)
        j += 1
      }
      ans(i) = i - j
    }

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


/**
  * Created by armanmac on 3/22/17.
  */

import util.control.Breaks._

object Code {

  //remove an element from array
  def remover(input: Array[Int], index: Int): Array[Int] = {
    var result: Array[Int] = new Array[Int](input.length - 1)
    var counter = 0

    for (i <- 0 to index - 1) {
      result(counter) = input(i)
      counter += 1
    }
    if (index != input.length - 1) {
      for (i <- index + 1 to input.length - 1) {
        result(counter) = input(i)
        counter += 1
      }
    }

    return result
  }

  def main(args: Array[String]): Unit = {
    val str = scala.io.StdIn.readLine().split(' ')

    val input = str(0).toInt
    var copyInput = str(0).toInt
    val size = str(0).length
    val k = str(1).toInt

    //converting to array
    var arr: Array[Int] = new Array[Int](size)
    for (i <- (0 to size - 1).reverse) {
      arr(i) = copyInput % 10
      copyInput /= 10
    }

    var iterSize = arr.length
    var counter = 0
    var removeCount = 0

    breakable {
      for (i <- (0 to arr.length - 1).reverse) {

        if (arr(i) == 0) {
          counter += 1
        }
        if (counter == k) {
          break()
        }
        if (arr(i) != 0) {
          arr = remover(arr, i)
          removeCount += 1
        }
      }
    }

    if(k>= size || k > counter)
      println(size-1)
    else
    println(removeCount)

  }
}


object H extends App {

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

  println(a + b)
}


import scala.collection.mutable._

object Main{
  def main(arr: Array[String]): Unit = {
    val x = readLine.split(" ").map(_.toInt);
    val A = x(0)
    val B = x(1)
    val C = x(2)
    val N = x(3)

    if(List(A, B, C).filter(_ > N).size > 0){
      println(-1)
      return
    }

    if(C > A || C > B){
      println(-1)
      return
    }

    val totalFailed = N - (A + B - C)

    if(totalFailed < 1){
      println(-1)
      return
    }

    println(totalFailed)
  }
}


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

  override def apply(io: IO): io.type = {
    val tests = io.read[Iterator[(Long, Long)]]
    val ans = tests.map({case (a, b) => (a - b) == 1 && BigInt(a + b).isProbablePrime(20)})
        .map(x => if (x) "YES" else "NO")
    io.writeAll(ans.toTraversable, separator = "\n")
  }
}
/****************************[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
      }
    }
  }
}


/**
 * Created by vinaysaini on 7/18/15.
 */

//    val Array(x,y,z) = io.StdIn.readLine().split(" ").map(_.toInt)

object Test {
  def main(args: Array[String]) {
  //  val x =
    val x = io.StdIn.readLine.split("").filter(_ != "").map(_.toInt)
    def forFirst(a: Int) = if(a == 9) 9 else revert(a)
    def revert(a: Int) = if(a < 5) a else 9-a
    println("%d%s".format(forFirst(x.head),x.tail.map(revert).mkString))
  }

}


object Main399A {

  def main(args: Array[String]): Unit = {
    val input = readLine.split(" ")
    val n = input(0).toInt
    val p = input(1).toInt
    val k = input(2).toInt
    println(
        (if(p-k > 1)"<< "else"") +
        ((if(p-k > 1)p-k else 1) to p-1).mkString(" ") +
        " (" + p + ") " +
        (p+1 to (if(p+k < n)p+k else n)).mkString(" ") +
        (if(p+k < n)" >>"else"")
        )
  }

}


import scala.io.StdIn

object Main extends App {
  io.Source.stdin.getLines()
  val Array(a, b) = StdIn.readLine().split(' ').map(_.toLong)
  val Array(x, y, z) = StdIn.readLine().split(' ').map(_.toLong)
  print((2 * x + y - a).max(0) + (y + 3 * z - b).max(0))
}


object A579 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readBigs(1)
    println(n.bitCount)
  }
}


object Main extends App {
  //  val INF = Integer.MAX_VALUE
  //  val source = Source.stdin
  //  val lines = source.getLines().toArray
  //  source.close()
  //  val Array(n, m) = lines(0).split(" ").map(_.toInt)

  //  val s = scala.io.StdIn.readLine()
  //  println(s + "!")

  val n = scala.io.StdIn.readLine().toInt
  val x = scala.io.StdIn.readLine().split(" ")
  val y = scala.io.StdIn.readLine().split(" ")

  if(x.map(x => x.toInt).sum >= y.map(y => y.toInt).sum) {
    println("Yes")
  } else {
    println("No")
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).foldLeft(0l, 1l) {
    case ((sum, prev), _) => (sum + prev * 2, prev * 2)
  }._1)
}


object Main {

  def main(args: Array[String]) {
    val Array(n,k)=io.StdIn.readLine().split(" ").map(_.toInt)
    val a=io.StdIn.readLine().split(" ").map(_.toInt).toList.zipWithIndex.sortWith(_._1<_._1)
    var s=0
    var i=0
    while(i<a.length && s+a(i)._1<=k){
      s+=a(i)._1
      i+=1
    }
    println(i)
    if (i!=0)
      println(a.take(i).map(_._2+1).mkString(" "))
  }

}


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

object A {

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

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

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

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

  def sqDist(x1: Int, y1: Int, x2: Int, y2: Int): Int = {
    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
  }

  def dist(x1: Int, y1: Int, x2: Int, y2: Int): Double = {
    return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
  }

  def isSquareTriangle(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int): Boolean = {
    val ab2 = sqDist(x1, y1, x2, y2)
    val bc2 = sqDist(x2, y2, x3, y3)
    val ac2 = sqDist(x1, y1, x3, y3)
    val ab = dist(x1, y1, x2, y2)
    val bc = dist(x3, y3, x2, y2)
    val ac = dist(x1, y1, x3, y3)
    if (ac < ab + bc && ab < ac + bc && bc < ac + ab) {
      if (ab2 + bc2 == ac2 || ab2 + ac2 == bc2 || bc2 + ac2 == ab2) {
        return true
      }
    }
    return false
  }

  def solve: Int = {
    val x1 = nextInt
    val y1 = nextInt
    val x2 = nextInt
    val y2 = nextInt
    val x3 = nextInt
    val y3 = nextInt
    if (isSquareTriangle(x1, y1, x2, y2, x3, y3)) {
      out.println("RIGHT")
      return 1
    }
    if (isSquareTriangle(x1 + 1, y1, x2, y2, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1 - 1, y1, x2, y2, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1 + 1, x2, y2, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1 - 1, x2, y2, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2 + 1, y2, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2 - 1, y2, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2, y2 + 1, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2, y2 - 1, x3, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2, y2, x3 + 1, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2, y2, x3 - 1, y3)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2, y2, x3, y3 + 1)) {
      out.println("ALMOST")
      return 1
    }
    if (isSquareTriangle(x1, y1, x2, y2, x3, y3 - 1)) {
      out.println("ALMOST")
      return 1
    }
    out.println("NEITHER")
    return 1
  }

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


object C extends App {

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

  val Array(n, m, k) = readInts(3)
  val MOD = 998244353L

  val pascal = Array.ofDim[Long](n + 1, n + 1)
  for (i <- pascal.indices) pascal(i)(0) = 1L
  for (i <- 1 until pascal.length) {
    for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD
  }

  val pow = pascal(n - 1)(k)
  val res = ((m * pow) % MOD) * BigInt(m - 1).modPow(k, MOD) % MOD

  println(res)
}


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

import scala.collection.mutable

object A extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val arr = Array.fill(n)(in.nextInt)
    val sum = arr.sum
    var ans = arr.max

    while (sum >= ans * n - sum)
      ans += 1

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

}


object Solve {
  import io.StdIn._
  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(s => s.toInt)
    val isBlackAndWhite = (1 to n).forall(_ => readLine.forall(c => !"CMY".contains(c)))
    println (if (isBlackAndWhite) "#Black&White" else "#Color")
  }
}


object A extends App {
  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  var r = k
  var a = n

  while (r > 0) {
    val t = a % 10 + 1

    if (t > r) a = a - r
    else a = a / 10

    r -= t
  }

  println(a)
}


object A141 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val input1 = scala.io.StdIn.readLine
    val input2 = scala.io.StdIn.readLine
    val input3 = scala.io.StdIn.readLine

    val map1 = (input1 + input2).sortBy(identity)
    val map2 = input3.toCharArray.sortBy(identity)

    if(map1.sameElements(map2)) {
      println("YES")
    } else {
      println("NO")
    }

  }
}


object CubicalPlanet39D  extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val f1 = List(scanner.nextInt(),scanner.nextInt(),scanner.nextInt())
    val f2 = List(scanner.nextInt(),scanner.nextInt(),scanner.nextInt())
    val r = f1.zip(f2).map{case (a,b) => (a-b)*(a-b)}.sum
    if(r<=2)
      out.println("YES")
    else
      out.println("NO")
  }
}


object MyClass {
      def add(x:Int, y:Int) = x + y;

      def main(args: Array[String]) {

         var lines = io.Source.stdin.getLines;
         /*var n = 0;
         var k = 0;
         var x = 0;*/
         var Array(n,k,x) = lines.next.split(' ').map(_.toInt);
         //var n = ln1.next.toInt;
         //var k = ln1.next.toInt;
         //var x = ln1.next.toInt;

         var total = 0;
         var A = lines.next.split(' ').map(_.toInt);
         var i = 1;
         for ( i <- 0 to n - k - 1) {
             var temp = A(i);
             total = total + temp;
         }

         if (k > n) total = total + x * n;
         else total = total + x * k;

         print(total)
         //for (ln <- io.Source.stdin.getLines) {

         //}
      }
   }


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

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

  val N = sc.nextLine.toInt
  val stones = sc.nextLine

  def solve(s0: String): Int = {
    @tailrec
    def loop(acc: Int, c: Char, s: String): Int =
      if (s.isEmpty) acc
      else if (c == s.head) loop(acc + 1, c, s.tail)
      else loop(acc, s.head, s.tail)
    loop(0, s0.head, s0.tail)
  }

  out.println(solve(stones))
  out.close
}


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

object A {

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

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

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

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

  def solve: Int = {
    val path = next
    var i = 1
    var ans = ""
    while (i < path.length) {
      if (path(i) == '/' && path(i - 1) == '/') {
      } else {
        ans += path(i)
      }
      i += 1
    }
    i = ans.length - 1
    while (i >= 0 && ans(i) == '/') {
      i -= 1
    }
    out.println("/" + ans.substring(0, i + 1))
    return 1
  }

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


import java.util.StringTokenizer

object _554A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next
  var set = Set[String]()
  for (i <- 0 to s.length) {
    val cb = s.splitAt(i)
    for (j <- 'a' to 'z') set = set + (cb._1 + j + cb._2)
  }
  println(set.size)
}


object CF411A {
    def main(args: Array[String]) {
        val pass = readLine()
        println (
            if (pass.length >= 5 && pass.exists(_.isUpper) &&
                pass.exists(_.isLower) && pass.exists(_.isDigit)) {
                "Correct"
            } else {
                "Too weak"
            }
        )
    }
}


//package template

object Template {
	def main(args: Array[String]) {
		var Array(n, d) = readLine.split(" ").map(_.toInt)
		var input = readLine.split(' ').map(_.toLong).reduceLeft(_ + _)
		if((n - 1) * 10 + input > d) print(-1)
		else print((d - ((n - 1) * 10 + input)) / 5 + (n - 1) * 2)
	}
}


object P143A extends App {
  val reqs = (readLine + " " + readLine + " " + readLine).split(" ").map(_.toInt).toList
  def f {
    val r = 1 to 9
    for (a <- r; b <- r; c <- r; d <- r)
      if (Set(a, b, c, d).size == 4 && List(a + b, c + d, a + c, b + d, a + d, b + c) == reqs) {
        print("%d %d\n%d %d".format(a, b, c, d))
        return
      }
    print("-1")
  }
  f
}


object probA extends App{
   def turns(n1 : Int,m1 : Int) = {
      var ret : Int = n1
      var n : Int= m1
      var m : Int= ret
      /*
      * (-n,-n) (-n,n+1)
      * (-n,n+1) (n+1,n+1)
      * (n+1,n+1)    (n+1,-n-1)
      * (n+1,-n-1)   (-n-1,-n-1)
      */
      if( n<=0 && m>(n) && m<=(-n+1) ) ret = -4*n
      else if (m>0 && n<=m && n>(-m+1)) ret=4*(m-1)+1
      else if(n>0 && (m+n)>=0 && m<=n ) ret = 4*(n-1)+2
      else ret = -4*(m+1)+3

      math.max(0,ret)
   }
   var line : String = readLine()
   var Array(v1,v2)  = line.split(" ")
   println(turns(v1.toInt,v2.toInt))
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(a, b) = in.next().split(' ').map(_.toInt)
  var x = a
  var xValue = (0, 0, 0)
  while (x % 2 == 0 || x % 5 == 0 || x % 3 == 0) {
    xValue = if (x % 2 == 0) {
      x /= 2
      (xValue._1 + 1, xValue._2, xValue._3)
    } else if (x % 3 == 0) {
      x /= 3
      (xValue._1, xValue._2 + 1, xValue._3)
    } else {
      x /= 5
      (xValue._1, xValue._2, xValue._3 + 1)
    }
  }
  var y = b
  var yValue = (0, 0, 0)
  while (y % 2 == 0 || y % 5 == 0 || y % 3 == 0) {
    yValue = if (y % 2 == 0) {
      y /= 2
      (yValue._1 + 1, yValue._2, yValue._3)
    } else if (y % 3 == 0) {
      y /= 3
      (yValue._1, yValue._2 + 1, yValue._3)
    } else {
      y /= 5
      (yValue._1, yValue._2, yValue._3 + 1)
    }
  }
  if (x != y)
    println(-1)
  else
    println(Math.abs(xValue._1 - yValue._1) + Math.abs(xValue._2 - yValue._2) + Math.abs(xValue._3 - yValue._3))
}


object A527 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    var Array(a, b) = readLongs(2)
    var res = 0L
    while(a != b) {
      if((a-b) % b == 0) {
        res += (a-b)/b + 1L
        a = 0
        b = 0
      } else {
        res += (a/b)
        val x = Array(a%b, b)
        a = x.max
        b = x.min
      }
    }
    if(a == b && a != 0) {
      res += 1
    }
    println(res)
  }
}


object Try1 {
  def main(args: Array[String]) {
    var m,x,c, n, i: Int = 0
    var a = new Array[Int](101)
    n = readInt()
    m=0;
    for (i <- 1 to n) {
      x = readInt()
      a(x) = a(x)+1
    }
    for (i<- 0 to 100)
      if (a(i)>0){
        m=m+1
        c=i
      }
    if (m==2 && a(c)+a(c)==n) {
      println("YES")
      i=0;
      while (a(i)==0) i+=1
      print(i+" ")
      i+=1
      while (a(i)==0) i+=1
      println(i)
    }
    else println("NO")
  }
}


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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val ans = (1 until n).count(l => (n-l) % l == 0)
    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()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(p._2))
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of 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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


object Main {
  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 w, h, k = ni()
    val ans = (map(k) { i =>
      (h - 4 * i) * 2 + (w - 4 * i) * 2 - 4
    }).sum
    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
  }
}


import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

/**
 * Educational round 16
 */
object A_ED16 {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa2)
//    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val cd = readLine.string
    val col = cd.charAt(0)
    val row = cd.charAt(1)

    var res = 8
    if (col == 'a' || col == 'h') res = 5
    if (row == '1' || row == '8') if (res == 8) res = 5 else res = 3

    //---------------------------- parameters reading :end

    outLn(res)
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
"""

val sa2 = """
"""

val sa3 = """
"""
}

}


import java.io.FileReader
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val Array(n, m, k) = readBigIntLine()
    //println(allBlocks(n, m).count(goodBlock(_, k)))
    //println(goodBlock(allBlocks(3, 3).head, -1))
    /*    allBlocks(n, m).foreach{
          a =>
            println("-")
            a.foreach(aa => println(aa.mkString(" ")))
        }*/

    if (((n % 2 == 1) ^ (m % 2 == 1)) && k == -1) {
      println(0)
    } else {
      println(BigInt(2).modPow((n - 1) * (m - 1), magicMod))
    }
  }

  /*def goodBlock(block : Array[Array[Int]], k : Int): Boolean = {
    val goodRow = (0 until block.length).map(r => block(r).product  == k).reduce(_ && _)
    val goodCol = (0 until block(0).length).map(c => block.indices.map(block(_)(c)).product == k).reduce(_ && _)
    goodRow && goodCol
  }

  def allBlocks(w : Int, h : Int) : Iterable[Array[Array[Int]]] = {
    (0L until 1L << (w * h)).map {
      i =>
        (0 until h).map {
          r =>
            (0 until w).map(c => if (((i >> (w * r + c)) & 1) == 1) 1 else -1).toArray
        }.toArray
    }.view
  }*/

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

  def readIntLine(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}


object bearAndGame extends App{
  val n = readInt()
  val mins = readLine().split(" ").map(_.toInt)
  var temp : Int = 0

  for(i <- 0 until(mins.length)){
    if (mins(i)-temp > 15) temp+15
    else temp = mins(i)
  }

  if(temp<=75) println(temp+15)
  else println(90)
}


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

import scala.collection.mutable

object B {

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

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

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

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

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def naiveCalc(x: Int, m: Int, b: Int): Long = {
    var sum = 0L
    val y = (-x / m + b).toLong
    val k = y + 1.toLong
    sum += (x * (x + 1.toLong)) / 2
    sum *= k
    sum += ((y * k) / 2.toLong) * (x + 1)
    sum
  }

  def solve: Int = {
    val m = nextInt
    val b = nextInt
    var maxSum = Long.MinValue
    for (i <- 0 to b) {
      val z = i * m
      maxSum = Math.max(maxSum, naiveCalc(z, m, b))
    }
//    for (i <- 0 to m * b) {
//      if (i % m == 0) {
//        val y = -i / m + b
//        if (i.toLong * y.toLong > maxSum) {
//          maxSum = i.toLong * y.toLong
//          maxX = i
//        } else if (i.toLong * y.toLong == maxSum) {
//          if (naiveCalc(i, m, b) > naiveCalc(maxX, m, b)) {
//            maxX = i
//          }
//        }
//      }
//    }
    out.println(maxSum)
    return 0
  }
}


//package com.codility.challenge._codeforces_cyclic_shift

/**
  * Created by obarros on 17/12/2016.
  */
object Main {
  def main(args: Array[String]): Unit = {
    val word = scala.io.StdIn.readLine()
    print(solution(word))

  }

  def solution(s: String): Int = {
    mapListOfShiftStrinf(s).length
  }

  def shifString(s: String): String = {
    s.substring(1, s.length) + s.charAt(0)
  }

  def mapListOfShiftStrinf(s: String): List[String] = {
    var result = List[String]()
    var value = s
    var resultI = s
    result =   s :: result
    for (i <- 0 until s.length) {
      result = shifString(resultI) :: result
      value = shifString(value)
      resultI =  value
  //    println(value)
    }
    result.distinct
  }

}


object C extends App {
  val Array(a, b, c, d) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val pref = (a to b)
    .foldLeft(Array.fill[Int](b + c + 2)(0)) { (pref, x) =>
      pref(x + b) += 1
      pref(x + c + 1) -= 1
      pref
    }
    .scanLeft(0L)(_ + _)
    .tail
    .scanRight(0L)(_ + _)

  val ans = (c to d.min(b + c)).foldLeft(0L)((s, z) => s + pref(z + 1))

  println(ans)
}


object A00131 extends Application {
  def isAllCaps(str: String) = str forall (_.isUpper)
  def switchCase(ch: Char) = if (ch.isLower) ch.toUpper else ch.toLower
  def changeString(str: String) = str map switchCase
  val str = Console.readLine();
  val changed = if (isAllCaps(str.tail)) changeString(str) else str
  println(changed)
}


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

object _633B extends CodeForcesApp {
  override type Result = Stream[Int]

  override def solve(read: InputReader) = {
    val n = read[Int]
    val fives = Stream.iterate(5)(_ * 5)
    def zeroes(i: Int) = fives.map(i / _).takeWhile(_ > 0).sum
    Stream.range(1, 500000).filter(i => zeroes(i) == n)
  }

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

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

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

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

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

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

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

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

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


object C extends App {

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

  val s = readLine
  val double = ('A' to 'Z').find(c => s.count(_ == c) > 1).get
  val _p1 = s.indexOf(double)
  val _p2 = s.indexOf(double, _p1 + 1)

  def solve(s: String, i: Int): Boolean = {

    val p1 = s.indexOf(double)
    val p2 = s.indexOf(double, p1 + 1)
      //println(i, s, double, p1, p2)

    if (p1 != p2 - 1 && (p1 == 25 - p2 || p1 == 26 - p2) /*|| (p1 == 27 - p2 && p1 == 1)*/ ) {
      println(s.take(13))
      println(s.drop(13).filter(_ != double).reverse)
      true
    } else if (p1 != p2 - 1 && (p1 == 27 - p2 /*&& p1 == 1*/)) {
      println(s.take(14).filter(_ != double))
      println(s.drop(14).reverse)
      true
    } else false
  }

  var ok = false

  var i = 0
  while (i < 27 && !ok && _p2 != _p1 + 1) {
    val ss = s.drop(i) ++ s.take(i)
    ok = solve(ss, i)
    i += 1
  }

  if (!ok) println("Impossible")
}


object B444 {
  def main(args: Array[String]){
    val n = Console.in.readLine().toInt

    val cubesOrder = 0 to n-1

    val matrix = for(_ <- 0 until n)
        yield Console.in.readLine.split(" ").map(_.toInt)

    var continue = true;

    for(i <- 1 to ('9'*n).toInt if(continue == true)) {
      val digits = i.toString.map(_.asDigit).toList
      var possible = false

      cubesOrder.permutations.takeWhile(_ => possible == false).foreach(perm => {
        var result = true;
        for(j <- 0 until digits.size) {
          result &= matrix(perm(j)).contains(digits(j))
        }
        possible |= result
      })

      if(!possible) {
        continue = false;
        print(i-1)
      }

    }

  }
}


import scala.math._
import scala.util.Sorting._
import scala.collection.mutable.Map

object Main extends App{

 var result = (1 to 8)
.map(x => readLine)
.flatMap(x => x.toList)
.map(x =>
  (
  x.toLower
  match
  {
  case 'q' => 9
  case 'r' => 5
  case 'b' => 3
  case 'n' => 3
  case 'p' => 1
  case _ => 0
  },
  if(x == x.toUpper) 1 else 0
  )
).groupBy(x => x._2).map(x => (x._1, x._2.map(x => x._1).sum))

if(result.getOrElse(0,0) < result.getOrElse(1,0))
  println("White")
else if (result.getOrElse(0,0) > result.getOrElse(1,0))
  println("Black")
else
  println("Draw")
}


import java.util.StringTokenizer

object _507B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val r = next.toLong
  val x = next.toLong
  val y = next.toLong
  val xx = next.toLong
  val yy = next.toLong

  def sqr(x: Long) = x * x

  val dist2 = sqr(x - xx) + sqr(y - yy)
  val hehe = sqr(2 * r)

  println((Math.sqrt(dist2) / Math.sqrt(hehe)).ceil.round)
}


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

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

  val s = reader.readLine()
  def ans = s.take(1).toUpperCase + s.drop(1)

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


object B extends App {

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

  val ss = readLine
  val n = BigInt(ss.dropRight(1).toLong - 1)
  val s = ss.last

  val pos = "fedabc"

  val r1 = (n / 4) * 16
  val r2 = (n % 2) * 7
  val r3 = pos.indexOf(s) + 1

  println(r1 + r2 + r3)
}


object CF_525_2_A {
  def solve(x: Int):Option[(Int, Int)] = {
    for {
      a <- 1 to x
      b <- 1 to a
      if a % b == 0 && a * b > x && a / b < x
    } return Some(a, b)
  return None
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in)
    val solution = solve(io.int).fold("-1"){case(a,b) => s"$a $b"}
    println(solution)
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}


import java.util.Scanner

/**
 * Created by hama_du on 2014/05/22.
 */
object ProblemC extends App {
  val MOD = 1000000007

  val in = new Scanner(System.in)
  val n,k,d = in.nextInt()

  val dp = Array.ofDim[Long](n+1,2)
  dp(0)(0) = 1
  for (i <- 0 until n) {
    for (flag <- 0 to 1) {
      for (j <- 1 to k) {
        val ti = i + j
        val tflag = if ((flag == 1) || (j >= d)) { 1 } else { 0 }
        if (ti <= n) {
          dp(ti)(tflag) += dp(i)(flag)
          dp(ti)(tflag) %= MOD
        }
      }
    }
  }
  println(dp(n)(1))
}


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

object _680B extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, a = io[Int]
    val isCriminal = io[Vector, Int](n).map(_ == 1)

    var ans = 0
    var l = a - 1
    var r = a - 1

    while(l >= 0 && r < n) {
      if (isCriminal(l) && isCriminal(r)) {
        ans += (if (l == r) 1 else 2)
      }
      //debug(l, r, isCriminal(l), isCriminal(r), ans)
      l -= 1
      r += 1
    }
    ans = ans + isCriminal.slice(0, l+1).count(identity)
    ans = ans + isCriminal.slice(r, n).count(identity)
    io += 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()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out) with Iterator[String] {
  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

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

  def apply[A](implicit read: IO.Read[A]): A = read.apply(this)
  def apply[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(apply).to[C]

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

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val a = 1234567
  val b = 123456
  val c = 1234
  val res = (0 to n / a).exists{ ac =>
      val left = n - (ac * a)
      (0 to left / b).exists(bc => (left - (bc * b)) % c == 0)
  }
  if (res)
    println("YES")
  else
    println("NO")
}


object AAryaAndBran extends App {
  def days(k: Int, a: Array[Int]): (Int, Int, Int) =
    a.foldLeft((k, 0, 0)) { case ((k, r, i), a) =>
      if (k > 0) {
        val t = r + a
        val p = t min 8
        (k - p, t - p, i + 1)
      }
      else (k, r, i)
    }

  val Array(n, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val a: Array[Int] = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  val (nk, r, d) = this.days(k, a)
  if (nk > 0) println("-1")
  else println(d)
}


import scala.io.StdIn
import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
    val Array(k, n, w) = readLine.split(" ").map(_.toLong)
    val s = (w * (w + 1) / 2) * k - n
    if(s > 0 ) println(s) else println(0)
  }
}


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

/**
  * @author Aydar Gizatullin a.k.a. lightning95 on 30.05.17.
  */

object Main {

  def main(args: Array[String]) {
    val rw = new RW("input.txt", "output.txt")
    val n = rw nextInt
    var beg = false
    var mid = false
    var end = false
    var last = 0
    var ok = true
    for (_ <- 1 to n) {
      val x = rw.nextInt
      if (last < x) {
        if (!mid && !end)
          beg = true
        else
          ok = false
      }
      if (x == last) {
        if (end)
          ok = false
        else
          mid = true
      }
      if (last > x)
        end = true

      last = x
    }

    rw println (if (ok) "YES" else "NO")
    rw.close()
  }

  class RW(val inputFile: String, val outputFile: String) {
    private var br = new BufferedReader(new InputStreamReader(System.in))
    private var out = new PrintWriter(new OutputStreamWriter(System.out))

    private val f = new File(inputFile)
    if (f.exists && f.canRead)
      try {
        br = new BufferedReader(new FileReader(inputFile))
        out = new PrintWriter(new FileWriter(outputFile))
      } catch {
        case e: IOException =>
          e.printStackTrace()
      }

    private var st = null: StringTokenizer
    var eof = false

    def nextLine: String = {
      var s = ""
      try
        s = br.readLine()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      s
    }

    def next: String = {
      while (st == null || !st.hasMoreTokens)
        try
          st = new StringTokenizer(br.readLine)
        catch {
          case _: IOException =>
            eof = true
            ""
        }
      st.nextToken
    }

    def nextLong: Long = next.toLong

    def nextInt: Int = next.toInt

    def println(): Unit = out.println()

    def println(o: Any): Unit = out.println(o)

    def print(o: Any): Unit = out.print(o)

    def close(): Unit = {
      try
        br.close()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }

      out.close()
    }
  }

}


object EvenOdds {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextLong();
		val k = scanner.nextLong();
		val midway = (n >> 1) + n%2
		if (k > midway) {
		  val offset = k - midway
		  println(offset << 1)
		}
		else {
		  println( ((k-1) << 1) + 1)
		}
	}
}


//package round328.c

import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {
  val sc = new Scanner(System.in)

  @tailrec
  def gcd(a: BigInt, b: BigInt): BigInt = {
    if (b == BigInt(0)) a else gcd(b, a % b)
  }

  val t = BigInt(sc.nextBigInteger())
  val l1 = BigInt(sc.nextBigInteger())
  val l2 = BigInt(sc.nextBigInteger())
  val (w, b) = (l1 max l2, l1 min l2)

  val nww = w * b / gcd(w, b)
  val c = t / nww
  val l = t % nww

  val licznik = (c + 1) * b - 1 + (if (l < b) l + 1 - b else 0)

  val d = gcd(licznik, t)

  val (li, mi) = (licznik / d, t / d)

  println(s"$li/$mi")

}


import scala.io.StdIn

/**
 * Created by dmitry on 04.02.17.
 */
object Main {
  def main(args: Array[String]) {
    val line: String = StdIn.readLine()
    val digits: Array[String] = line.split(' ')
    val n = digits(0).toInt
    val m = digits(1).toInt
    val z = digits(2).toInt
    println((1 to z).toStream.count(i => i % n == 0 & i % m == 0))

    /*val str = (1 to 100).toStream
    val lst = str.filter(_ < 50).map(_ * 10).foreach(println(_))*/
  }
}


object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(a, b, c) = in.next().split(" ").map(_.toLong)
  val r = (1 to 81).flatMap{i =>
    val f = b * Math.pow(i, a).toLong + c
    if (f > 0 && f < 1000000000 && f.toString.map(_ - '0').sum == i) Some(f) else None
  }
  println(r.length)
  println(r.mkString(" "))
}


//package com.omar
import scala.io.StdIn._

object Bla{
  def main(args: Array[String]): Unit = {
    readInt()
    val line = readLine()
    val res = line.foldLeft(0)((re,x)=>(re,x) match {
      case (y,'+') => y+1
      case (0,'-') => 0
      case (y,'-') => y-1
      case _ => 0
    })
    println(res)

  }
}


import java.io.FileReader
import java.util
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val intervals = readIntLine().sorted
    if ((intervals(0) == 2 && intervals(1) == 2) || (intervals.toSet.size == 1 && intervals(0) == 3) || (intervals.toSet contains 1) || (intervals(0) == 2 && intervals(1) == 4) && intervals(2) == 4) {
      println("YES")
    } else {
      println("NO")
    }
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

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

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(r1, c1, r2, c2) = in.next().split(' ').map(_.toInt)
  val dr = Math.abs(r1 - r2)
  val dc = Math.abs(c1 - c2)
  val rook = if (dr + dc == 0) 0 else if (r1 == r2 || c1 == c2) 1 else 2
  val bishop = if ((dr + dc) % 2 == 1 || dr + dc == 0) 0 else if (dr == dc) 1 else 2
  val king = Math.max(dr, dc)
  println(s"$rook $bishop $king")
}


object A13 {

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

  def sumOfDigitsInBase(n1: Int, x: Int): Int = {
    var res = 0
    var n = n1
    while(n > 0) {
      res += (n%x)
      n /= x
    }
    res
  }

  def gcd(a: Int, b: Int): Int = {
    if(b == 0) a else gcd(b, a%b)
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val res = (2 until n).foldLeft(0)((sum, b) => sum+sumOfDigitsInBase(n, b))
    val tot = n-2
    println(s"${res/gcd(res, tot)}/${tot/gcd(res, tot)}")
  }

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

}