ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.

The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20). The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order. The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make. The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.

For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print  - 1, if it is impossible to get the corresponding sum.

object VK2015C extends App {
  def readInts = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val Array(n, k) = readInts
  val a = readInts

  val map = scala.collection.mutable.HashMap.empty[Int, Int]

  for {
    x <- a
    c <- 0 to k
    xc = x * c
    curc = map.getOrElse(xc, k + 1)
    if c < curc
  } map += xc -> c

  val Array(q) = readInts
  for (i <- 1 to q) {
    val ans2 = for {
      z <- readInts
      (xc, c) <- map
      ctot <- map.get(z - xc)
    } yield ctot + c
    val ans = if (ans2.isEmpty) k+1 else ans2.min
    if (ans <= k) println(ans) else println(-1)
  }
}

object C extends App {
  def readInts = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val Array(n, k) = readInts
  val a = readInts
  val Array(q) = readInts

  val map = scala.collection.mutable.Map.empty[Int, Int]

  for {
    z <- 0 to n-1
    x <- 0 to n-1
    zc <- 0 to k
    xc <- 0 to k
    newc = zc + xc
    if newc <= k
    money = z*zc+x*xc
    curc = map.getOrElse(money, k+1)
    if newc < curc
  } yield map += money -> newc
  for (i <- 1 to q) {
    val Array(money) = readInts
    println(map.getOrElse(money, -1))
  }
}

object C extends App {
  def readInts = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val Array(n, k) = readInts
  val a = readInts
  val Array(q) = readInts

  val map = scala.collection.mutable.Map.empty[Int, Int]

  for {
    z <- 0 to n-1
    x <- 0 to n-1
    zc <- 0 to k
    xc <- 0 to k
    newc = zc + xc
    if newc <= k
    money = z * zc + x * xc
    curc = map.getOrElse(money, k+1)
    if newc < curc
  } map += money -> newc
  for (i <- 1 to q) {
    val Array(money) = readInts
    println(map.getOrElse(money, -1))
  }
}


There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $$$n$$$ packets with inflatable balloons, where $$$i$$$-th of them has exactly $$$a_i$$$ balloons inside.They want to divide the balloons among themselves. In addition, there are several conditions to hold:  Do not rip the packets (both Grigory and Andrew should get unbroken packets);  Distribute all packets (every packet should be given to someone);  Give both Grigory and Andrew at least one packet;  To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.

The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 10$$$) — the number of packets with balloons. The second line contains $$$n$$$ integers: $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \le a_i \le 1000$$$) — the number of balloons inside the corresponding packet.

If it's impossible to divide the balloons satisfying the conditions above, print $$$-1$$$. Otherwise, print an integer $$$k$$$ — the number of packets to give to Grigory followed by $$$k$$$ distinct integers from $$$1$$$ to $$$n$$$ — the indices of those. The order of packets doesn't matter. If there are multiple ways to divide balloons, output any of them.

NoteIn the first test Grigory gets $$$3$$$ balloons in total while Andrey gets $$$1$$$.In the second test there's only one way to divide the packets which leads to equal numbers of balloons.In the third test one of the boys won't get a packet at all.

import scala.io.StdIn

object Test extends App {

  def find(packages: List[Int],and: Map[Int,Int],gr: Map[Int,Int],index: Int): Map[Int,Int ] = {
    val sum1 = and.values.sum
    val sum2 = gr.values.sum
    if (packages.isEmpty && sum1 != sum2 && sum1 != 0 && sum2 != 0) gr
    else
      {
        if (packages.nonEmpty) {
          val current = packages.head
          val a1 = find(packages.tail, and.updated(index, current), gr, index + 1)
          if (a1.nonEmpty) a1
          else {
            find(packages.tail, and, gr.updated(index, current), index + 1)
          }
        }else Map.empty
      }
  }

  val n = StdIn.readLine().trim.toInt
  val s = StdIn.readLine().split(" ").map(_.toInt).toList

  val gr = find(s,Map.empty,Map.empty,0)
  if (gr.isEmpty)
    {
      println(-1)
    }else
    {
      println(gr.size)
      gr.keys.map(_ + 1).foreach(el => print(s"$el "))
    }
}

object Main{
  def main(args: Array[String]) {
    val n = readInt()
    if(n == 1){
      println(-1)
      return;
    }
    val a = readLine().split(" ").map(_.toInt)

    var minIndex = -1
    var minValue = Long.MaxValue
    var sum: Long = 0L
    for(i <- 0 to (a.length - 1)){
      if(a(i) < minValue){
        minValue = a(i)
        minIndex = i
      }
      sum += a(i)
    }

    if(sum - minValue == minValue){
      println(-1)
      return;
    }

    println(1)
    println(minIndex + 1)

  }
}

object Main{
  def main(args: Array[String]) {
    val n = readInt()
    if(n == 1){
      println(-1)
      return;
    }
    val a = readLine().split(" ").map(_.toInt)

    var minIndex = -1
    var minValue = Long.MaxValue
    var sum: Long = 0L
    for(i <- 0 to (a.length - 1)){
      if(a(i) < minValue){
        minValue = a(i)
        minIndex = i
      }
      sum += a(i)
    }

    if(sum - minValue == minValue){
      println(-1)
      return;
    }

    println(1)
    println(minIndex)

  }
}

object Main{
  def main(args: Array[String]) {
    val n = readInt()
    if(n == 1){
      println(-1)
      return;
    }
    val a = readLine().split(" ").map(_.toInt)

    var minIndex = -1
    var minValue = Long.MaxValue
    var sum: Long = 0L
    for(i <- 0 to (a.length - 1)){
      if(a(i) < minValue){
        minValue = a(i)
        minIndex = i
      }
      sum += a(i)
    }

    if(sum - minValue == minValue){
      println(-1)
      return;
    }

    println(1)
    println(minValue)

  }
}


The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.

The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.

Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.

object main{
  object Solver extends InputReader{
    val dp = Array.ofDim[Array[Double]](128, 128, 128)

    def merge(rate: Double, dst: Array[Double], src: Array[Double]){
      for(i <- 0 to dst.length - 1)
        dst(i) += rate * src(i)
    }

    def dfs(r: Int, s: Int, p: Int): Array[Double] = {
      if(dp(r)(s)(p) != null) return dp(r)(s)(p)
      val ret = new Array[Double](3)

      if(r == 0){
        ret(1) = 1
      }else if(s == 0){
        ret(2) = 1
      }else if(p == 0){
        ret(0) = 1
      }else{
        val all = r + s + p
        val b: Double = all * (all - 1) / 2

        merge((r * s) / b, ret, dfs(r, s - 1, p))
        merge((s * p) / b, ret, dfs(r, s, p - 1))
        merge((p * r) / b, ret, dfs(r - 1, s, p))

        val sum = ret.sum
        for(i <- 0 to ret.length - 1)
          ret(i) /= sum
      }

      dp(r)(s)(p) = ret
      return ret
    }

    def solve(){
      val r = getInt()
      val s = getInt()
      val p = getInt()

      for(a <- dfs(r, s, p))
        printf("%.12f ", a)
      println()
    }
  }

  // TEMPLATE ------------------------

  def main(args: Array[String]){
    Solver.solve()
  }

  trait InputReader{
    import java.io._
    import java.util._
    protected val stream = System.in
    private val reader = new BufferedReader(new InputStreamReader(stream))
    private var tokenizer = new StringTokenizer(reader.readLine())

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

    def getInt(): Int = getStr().toInt
    def getLong(): Long = getStr().toLong
    def getDouble(): Double = getStr().toDouble
  }
}

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable

object Codeforces {
  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)
    }
    st.nextToken
  }

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (r, s, p) = (nextInt, nextInt, nextInt)
    val dp = Array.ofDim[Double](r + 1, s + 1, p + 1)
    dp(r)(s)(p) = 1.0
    for (i <- (0 to r).reverse) {
      for (j <- (0 to s).reverse) {
        for (k <- (0 to p).reverse) {
          val total = i * j + j * k + i * k
          if (i > 0 && j > 0) {
            dp(i)(j - 1)(k) += dp(i)(j)(k) * (i * j) / total
          }
          if (j > 0 && k > 0) {
            dp(i)(j)(k - 1) += dp(i)(j)(k) * (j * k) / total
          }
          if (i > 0 && k > 0) {
            dp(i - 1)(j)(k) += dp(i)(j)(k) * (i * k) / total
          }
        }
      }
    }
    var (ans_r, ans_s, ans_p) = (0.0, 0.0, 0.0)
    for (i <- 1 to r) ans_r += dp(i)(0)(0)
    for (j <- 1 to s) ans_s += dp(0)(j)(0)
    for (k <- 1 to p) ans_p += dp(0)(0)(k)
    out.println(f"$ans_r%.12f $ans_s%.12f $ans_p%.12f")
  }

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

import annotation.tailrec

object main extends App with fastIO {

  val Array(a, b, c) = readLine split(" ") map(_.toInt)
  var dp = Array.fill[Double](101, 101, 101)(-1)

  def sum1n(n: Int) = n * (n - 1) >> 1

  def dfs(a: Int, b: Int, c: Int): Double = {
    if (a == 0) return 0
    if (b + c == 0) return 1

    if (dp(a)(b)(c) > -1e-10) return dp(a)(b)(c)
    var value: Double = 0

    var cnt: Double = sum1n(a + b + c)
    var q: Double = (sum1n(a) + sum1n(b) + sum1n(c)) / cnt

    if (a > 0) value += dfs(a - 1, b, c) * (a * c) / cnt
    if (b > 0) value += dfs(a, b - 1, c) * (b * a) / cnt
    if (c > 0) value += dfs(a, b, c - 1) * (c * b) / cnt

    value *= 1 / (1 - q)

    dp(a)(b)(c) = value
    value
  }

  println("%.10f %.10f %.10f" format(dfs(a, b, c), dfs(b, c, a), dfs(c, a, b)) replace(",","."))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}


This is the hard version of this problem. The only difference is the constraint on $$$k$$$ — the number of gifts in the offer. In this version: $$$2 \le k \le n$$$.Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "$$$k$$$ of goods for the price of one" is held in store.Using this offer, Vasya can buy exactly $$$k$$$ of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.More formally, for each good, its price is determined by $$$a_i$$$ — the number of coins it costs. Initially, Vasya has $$$p$$$ coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:  Vasya can buy one good with the index $$$i$$$ if he currently has enough coins (i.e $$$p \ge a_i$$$). After buying this good, the number of Vasya's coins will decrease by $$$a_i$$$, (i.e it becomes $$$p := p - a_i$$$).  Vasya can buy a good with the index $$$i$$$, and also choose exactly $$$k-1$$$ goods, the price of which does not exceed $$$a_i$$$, if he currently has enough coins (i.e $$$p \ge a_i$$$). Thus, he buys all these $$$k$$$ goods, and his number of coins decreases by $$$a_i$$$ (i.e it becomes $$$p := p - a_i$$$). Please note that each good can be bought no more than once.For example, if the store now has $$$n=5$$$ goods worth $$$a_1=2, a_2=4, a_3=3, a_4=5, a_5=7$$$, respectively, $$$k=2$$$, and Vasya has $$$6$$$ coins, then he can buy $$$3$$$ goods. A good with the index $$$1$$$ will be bought by Vasya without using the offer and he will pay $$$2$$$ coins. Goods with the indices $$$2$$$ and $$$3$$$ Vasya will buy using the offer and he will pay $$$4$$$ coins. It can be proved that Vasya can not buy more goods with six coins.Help Vasya to find out the maximum number of goods he can buy.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$t$$$ test cases.  The first line of each test case contains three integers $$$n, p, k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le p \le 2\cdot10^9$$$, $$$2 \le k \le n$$$) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — the prices of goods. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case in a separate line print one integer $$$m$$$ — the maximum number of goods that Vasya can buy.

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[this] val oj = System.getenv("MY_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 = {
    if (!oj){ System.err.println(s) }
  }
  def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

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

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

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

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

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

  def upperBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) > x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }
}

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, P, K = ni()
      val A = na(N)
      sort(A)
      val S = Array.ofDim[Long](N + 1)
      REP(N) { i =>
        if (i + 1 >= K) {
          S(i + 1) = S(i + 1 - K) + A(i)
        }
      }
      debug(S)
      val cum = Array.ofDim[Long](K - 1)
      cum(0) = A(0)
      REP(K - 2, 1) { i =>
        cum(i) = cum(i - 1) + A(i)
      }
      debug(cum)

      var ans = 0
      REP(N) { i =>
         if (S(i + 1) <= P) {
           val remain = P - S(i + 1)
           val c1 = (i + 1) / K * K
           val c2 = upperBound(cum, remain)
           val c = c1 + min(c2, i + 1 - c1)
           ans = max(ans, c)
         }
      }
      out.println(ans)
    }
  }
}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val t = stdin.next().toInt
  val res = stdin.take(t * 2).map(_.split(" ").map(_.toInt)).grouped(2).map {
    arr =>
      val Array(n, p, k) = arr.head
      val x = arr(1).sorted
      solve(x, p, k)
  }

  println(res.mkString("\n"))

  def solve(x: Array[Int], p: Int, k: Int) = {
    var startIndex = 0
    var endIndex = k
    val sum = x.scanLeft(0) {case(acc, el) => acc + el}.tail
    var currentVal = sol(x, p, k, k - 1)
//    println(currentVal)
    while (startIndex + 1 < endIndex) {
      val mid = (startIndex + endIndex) / 2
//      println("mid " + mid)
      val tr = if (mid == 0 || sum(mid - 1) > p) 0 else mid + sol(x, p - sum(mid - 1), k, mid + k - 1)
      if (tr > currentVal) {
        currentVal = tr
        startIndex = mid
      }
      else {
        endIndex = mid
      }
    }
    currentVal
  }

  def sol(x: Array[Int], p: Int, k: Int, tryIndex: Int): Int = {
    if (tryIndex >= x.length) Math.max(0, (tryIndex - k + 1) / k * k)
    else if (x(tryIndex) > p) Math.max(0, (tryIndex - k + 1) / k * k)
    else sol(x, p - x(tryIndex), k, tryIndex + k)
  }

}

// 5 11 2
// 2 3 4 5 7

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[this] val oj = System.getenv("MY_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 = {
    if (!oj){ System.err.println(s) }
  }
  def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

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

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

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

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

object Workspace {
  import Main._
  import java.util.Arrays.sort

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

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, P, K = ni()
      val A = na(N)
      sort(A)
      val S = Array.ofDim[Long](N)
      REP(N) { i =>
        if (i - K >= 0) {
          S(i) = A(i) + S(i - K)
        } else {
          S(i) = A(i)
        }
      }
      debug(S)
      var ans = 0
      REP(N) { i =>
        if (S(i) <= P) {
          val v = if (i + 1 >= K) i + 1 else 1
          ans = max(ans, v)
        }
      }
      out.println(ans)
    }
  }
}


Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.

In the first string, the number of games n (1 ≤ n ≤ 350000) is given. Each game is represented by a pair of scores a, b (1 ≤ a, b ≤ 109) – the results of Slastyona and Pushok, correspondingly.

For each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise. You can output each letter in arbitrary case (upper or lower).

NoteFirst game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.

import scala.collection.mutable
import scala.collection.mutable.ArrayBuilder.ofInt

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 LIMIT = 1003
  val divisors = Array.tabulate(LIMIT)(identity)
  val primeBuilder = new mutable.ArrayBuilder.ofInt

  var i = 2
  while (i < LIMIT) {
    if (divisors(i) == i) {
      primeBuilder += i
      var j = i * i
      while (j < LIMIT) {
        divisors(j) = i
        j += i
      }
    }
    i += 1
  }
  val primes = primeBuilder.result

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

  //  Stream.from(2).takeWhile(i => i*i*i < LIMIT).filter(prime(_)).foreach { i =>
  //    (i*i until LIMIT by i).foreach(prime(_) = false)
  //  }

  val Array(n) = readInts(1)
  val res = Array.ofDim[String](n)

  for (i <- 0 until n) {
    var ok = true
    val Array(_a, _b) = readInts(2)
    var g = gcd(_a, _b)
    var pi = 0
    var a = _a
    var b = _b
    while (pi < primes.length && g > 1 && ok) {
      val d = primes(pi)
      if (g % d == 0) {
        //println(g, d, a, b)
        var degA, degB = 0
        while (a % d == 0) {
          degA += 1
          a /= d
        }
        while (b % d == 0) {
          degB += 1
          b /= d
        }
        while ((degA > 0 && degB > 1) || (degB > 0 && degA > 1)) {
          if (degA >= degB) {
            degA -= 2
            degB -= 1
          } else {
            degA -= 1
            degB -= 2
          }
        }
        if (degA + degB > 0) ok = false
        while (g % d == 0) g /= d
      }
      pi += 1
    }
    if (a != b.toLong * b && b != a.toLong * a) ok = false
    res(i) = if (ok) "Yes" else "No"
  }

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

  println(res.mkString("\n"))

  Console.flush
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuilder.ofInt

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 LIMIT = 1003
  val divisors = Array.tabulate(LIMIT)(identity)
  val primeBuilder = new mutable.ArrayBuilder.ofInt

  var i = 2
  while (i * i < LIMIT) {
    if (divisors(i) == i) {
      primeBuilder += i
      var j = i * i
      while (j < LIMIT) {
        divisors(j) = i
        j += i
      }
    }
    i += 1
  }
  val primes = primeBuilder.result

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

  //  Stream.from(2).takeWhile(i => i*i*i < LIMIT).filter(prime(_)).foreach { i =>
  //    (i*i until LIMIT by i).foreach(prime(_) = false)
  //  }

  val Array(n) = readInts(1)
  val res = Array.ofDim[String](n)

  for (i <- 0 until n) {
    var ok = true
    val Array(_a, _b) = readInts(2)
    var g = gcd(_a, _b)
    var pi = 0
    var a = _a
    var b = _b
    while (pi < primes.length && g > 1) {
      val d = primes(pi)
      if (g % d == 0) {
        //println(g, d, a, b)
        var degA, degB = 0
        while (a % d == 0) {
          degA += 1
          a /= d
        }
        while (b % d == 0) {
          degB += 1
          b /= d
        }
        while ((degA > 0 && degB > 1) || (degB > 0 && degA > 1)) {
          if (degA >= degB) {
            degA -= 2
            degB -= 1
          } else {
            degA -= 1
            degB -= 2
          }
        }
        if (degA + degB > 0) ok = false
        while (g % d == 0) g /= d
      }
      pi += 1
    }
    if (a != b.toLong * b && b != a.toLong * a) ok = false
    res(i) = if (ok) "Yes" else "No"
  }

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

  println(res.mkString("\n"))

  Console.flush
}


Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper.Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?Note: uppercase and lowercase letters are considered different.

Input contains a single line containing a string s (1  ≤  |s|  ≤  105) — the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s. The string s contains lowercase and uppercase English letters, i.e. .

Output a single integer, the answer to the problem.

NoteIn the first case, you could pick: Bulbbasaur.In the second case, there is no way to pick even a single Bulbasaur.In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words "Bulbasaur".

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val str2 = in.next().toCharArray
  val answer = str2.filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.toList.sorted

  if (str.forall(str2.contains))
    println(answer.headOption.getOrElse(0))
  else
    println(0)

}

object A757 {

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

  def main(args: Array[String]): Unit = {
    val in = read
    val map = collection.mutable.Map.empty[Char, Int].withDefaultValue(0)
    in.foreach{char => map(char) += 1}

    var res = Array(map('B'), map('u')/2, map('l'), map('b'), map('a')/2, map('s'), map('r')).min//"Bulbasaur"
    println(res)
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))
    lazy val input = getFreq(readLine)
    println(getFreq("Bulbasaur").map(p => input.getOrElse(p._1, 0) / p._2).min)
  }
}

import scala.io.StdIn._

object Main extends App {
  val A = readLine()

  val G = A.groupBy(identity).mapValues(_.length)
  val min = Array(
    G.getOrElse('B', 0),
    G.getOrElse('u', 0) / 2,
    G.getOrElse('l', 0),
    G.getOrElse('b', 0),
    G.getOrElse('a', 0) / 2,
    G.getOrElse('s', 0),
    G.getOrElse('r', 0)).min

  println(min)
}

object GottaCatchEmAll extends App{
  val textCount = io.StdIn.readLine().groupBy(_.toChar).mapValues(_.length)
  val bulbasaur = "Bulbasaur".groupBy(_.toChar).mapValues(_.length)
  val ans = bulbasaur.collect{ case (k, v) => textCount.getOrElse(k, 0) / v }.min
  println(ans)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val answer = in.next().filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.toList.sorted

  if (str.forall(answer.contains))
    println(answer.headOption.getOrElse(0))
  else
    println(0)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val answer = in.next().filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.toList.sorted.headOption

  println(answer.getOrElse(0))

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val answer = in.next().filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.max

  println(answer)

}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))
    lazy val input = getFreq(readLine)
    println(getFreq("Bulbbasaur").map(p => input.getOrElse(p._1, 0) / p._2).min)
  }
}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))
    val input = getFreq(readLine)
    println(getFreq("Bulbbasaur").map(p => input.getOrElse(p._1, 0) / p._2).min)
  }
}

import scala.io.StdIn._

object Main extends App {
  val A = readLine()
  val Match = "Bulbbasaur"

  val G = A.groupBy(identity).mapValues(_.length)
  val min = Array(
  G.getOrElse('B', 0),
  G.getOrElse('u', 0) / 2,
  G.getOrElse('l', 0),
  G.getOrElse('b', 0) / 2,
  G.getOrElse('a', 0) / 2,
  G.getOrElse('s', 0),
  G.getOrElse('r', 0)).min

  println(min)
}


You are given three integers $$$a$$$, $$$b$$$, $$$k$$$.Find two binary integers $$$x$$$ and $$$y$$$ ($$$x \ge y$$$) such that   both $$$x$$$ and $$$y$$$ consist of $$$a$$$ zeroes and $$$b$$$ ones;  $$$x - y$$$ (also written in binary form) has exactly $$$k$$$ ones.  You are not allowed to use leading zeros for $$$x$$$ and $$$y$$$.

The only line contains three integers $$$a$$$, $$$b$$$, and $$$k$$$ ($$$0 \leq a$$$; $$$1 \leq b$$$; $$$0 \leq k \leq a + b \leq 2 \cdot 10^5$$$) — the number of zeroes, ones, and the number of ones in the result.

If it's possible to find two suitable integers, print "Yes" followed by $$$x$$$ and $$$y$$$ in base-2. Otherwise print "No". If there are multiple possible answers, print any of them.

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * b + "0" * a
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (b > k - a + 1 && a > 0 && k > a) {
      val s = "1" * b + "0" * a
      val t = "1" * (b - (k - a + 1)) + "0" + "1" * (k - a) + "0" * (a - 1) + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * b + "0" * a
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (b > k - a + 1 && a > 0) {
      val s = "1" * b + "0" * a
      val t = "1" * (b - (k - a + 1)) + "0" + "1" * (k - a) + "0" * (a - 1) + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * b + "0" * a
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (a == k - 1 && b > 2) {
      val s = "1" * b + "0" * a
      val t = "1" * (b - 2) + "01" + "0" * (a - 1) + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (b > k - a + 1) {
      val s = "1" * b + "0" * a
      val t = "1" * (b - (k - a + 1)) + "0" + "1" * (k - a) + "0" * (a - 1) + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * b + "0" * a
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (b > k - a + 1 && a > 1) {
      val s = "1" * b + "0" * a
      val t = "1" * (b - (k - a) - 1) + "0" + "1" * (k - a) + "0" * (a - 1) + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * b + "0" * a
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (b > k - a + 1) {
      val s = "1" * b + "0" * a
      val t = "1" * (b - (k - a) - 1) + "0" + "1" * (k - a) + "0" * (a - 1) + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * b + "0" * a
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (a == k - 1 && b > 2) {
      val s = "1" * b + "0" * a
      val t = "1" * (b - 2) + "01" + "0" * (a - 1) + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * b + "0" * a
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (a == k - 1 && b > 1) {
      val s = "1" * b + "0" * a
      val t = "1" + "0" * a + "1" * (b - 1)
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * k + "0" * b
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else if (a == k - 1 && b > 1) {
      val s = "1" * b + "0" * a
      val t = "1" + "0" * a + "1" * (b - 1)
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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

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

    val a, b, k = nextInt

    if (k == 0) {
      val s = "1" * k + "0" * b
      out.println("Yes")
      out.println(s)
      out.println(s)
    } else if (a >= k && b > 1) {
      val s = "1" * (b - 1) + "0" * (a - k) + "1" + "0" * k
      val t = "1" * (b - 1) + "0" * a + "1"
      out.println("Yes")
      out.println(s)
      out.println(t)
    } else {
      out.println("No")
    }

    out.flush()
  }

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


ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.Please note that the friends can't color the trees that are already colored.

The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively. The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci. Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.

Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print  - 1.

NoteIn the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is  - 1.In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.

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 Array(n, m, k) = readInts(3)
  val cs = readInts(n)
  val ps = Array.fill(n) { readInts(m) }

  val MAX = Long.MaxValue / 2
  val dp = Array.fill(n, k + 1, m){ MAX }

  if (cs(0) == 0) {
    for (color <- 0 until m) dp(0)(1)(color) = ps(0)(color)
  } else {
    dp(0)(1)(cs(0) - 1) =  0
  }

  for (tree <- 1 until n) {
    if (cs(tree) == 0) {
      for (groups <- 0 to k) {
        var prevColor = 0
        while (prevColor < m) {
          if (dp(tree - 1)(groups)(prevColor) < MAX) {
            var color = 0
            while (color < m) {
              if (prevColor == color) {
                dp(tree)(groups)(color) = Math.min(dp(tree)(groups)(color), dp(tree - 1)(groups)(prevColor) + ps(tree)(color))
              } else if (groups < k) {
                dp(tree)(groups + 1)(color) = Math.min(dp(tree)(groups + 1)(color), dp(tree - 1)(groups)(prevColor) + ps(tree)(color))
              }
              color += 1
            }
          }
          prevColor += 1
        }
      }
    } else {
      for (groups <- 0 to k) {
        val color = cs(tree) - 1
        var prevColor = 0
        while (prevColor < m) {
          if (dp(tree - 1)(groups)(prevColor) < MAX) {
            if (color == prevColor) {
              dp(tree)(groups)(color) = Math.min(dp(tree)(groups)(color), dp(tree - 1)(groups)(prevColor))
            } else if (groups < k) {
              dp(tree)(groups + 1)(color) = Math.min(dp(tree)(groups + 1)(color), dp(tree - 1)(groups)(prevColor))
            }
          }
          prevColor += 1
        }
      }
    }
  }

  val res0 = dp(n - 1)(k).min
  val res = if (res0 >= MAX) -1 else res0

  println(res)
}


You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most $$$9$$$ elements of this field (i.e. choose some $$$1 \le i, j \le 9$$$ and change the number at the position $$$(i, j)$$$ to any other number in range $$$[1; 9]$$$) to make it anti-sudoku. The anti-sudoku is the $$$9 \times 9$$$ field, in which:  Any number in this field is in range $$$[1; 9]$$$;  each row contains at least two equal elements;  each column contains at least two equal elements;  each $$$3 \times 3$$$ block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of $$$9$$$ lines, each line consists of $$$9$$$ characters from $$$1$$$ to $$$9$$$ without any whitespaces — the correct solution of the sudoku puzzle.

For each test case, print the answer — the initial field with at most $$$9$$$ changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.

import scala.io.StdIn

object Solution_D extends App {
  val T = StdIn.readInt()
  for (_ <- 1 to T) {
    val sudoku = Array.ofDim[String](9)
    val result = Array.ofDim[Int](9, 9)
    for (idx <- 0 until 9) {
      sudoku(idx) = StdIn.readLine()
      for (c <- 0 until 9) {
        result(idx)(c) = sudoku(idx)(c).toInt - '0'
      }
    }
    for (offset <- 0 until 3) {
      for (r <- 0 until 3) {
        val column = r + offset * 3
        val row = offset + r * 3
        result(row)(column) = 1 + result(row)(column) % 9
      }
    }
    for (idx <- 0 until 9) {
      println(result(idx).mkString)
    }
  }
}

object Main extends App {
  import scala.io.StdIn._
  val t = readInt

  for(_ <- 0 until t) {
    val state = Array.fill(9){readLine.trim.map(_.asDigit).toArray}
    var j = 0
    for (i <- 0 until 9) {
      state(i)(j) = state(i)(j) % 9 + 1
      j = (j + 4) % 9
    }
    println(state.map(_.mkString).mkString("\n"))
  }
}


Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

The first line contains integer n (1 ≤ n ≤ 100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the coins' values. All numbers are separated with spaces.

In the single line print the single number — the minimum needed number of coins.

NoteIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.

import java.util.Scanner
import scala.util.control.Breaks._

import sun.swing.SwingUtilities2.RepaintListener

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

    val s = new Scanner(System.in)
    val a = s.nextInt()
    val numbers: Array[Int] = Array.fill(a) {
      0
    }
    for (i <- 0 until a){
      numbers(i) = s.nextInt()
    }

    val list = numbers.toList.sorted

    val rev = list.reverse

    val llist = list.scanLeft(0)(_+_)

    val lllist = llist.reverse

    val rlist = rev.scanLeft(0)(_+_)

    def Index(al:(List[Int],List[Int])): Int =
      al match {
        case (Nil, Nil) => 999999
        case (xs :: xss, ys :: yss) => if (xs > ys) xs else Index((xss, yss))
      }

    println(rlist.indexOf( Index( (rlist,lllist)) ))

//    def minIndex(x: List[Int], y:List[Int]): List[Int] = {
//      var sol = List()
//      for(i <- 0 until a) {
//        if (x(i) > y(i)) {i :: sol} else sol
//      }
//    }

//    println(minIndex(rlist, lllist))
//
//    println(list)
//    println(rlist)
//    println(lllist)
//
//    println(rev)
//
  }
}

object One60A extends App {
	import java.io.{ PrintWriter => Out }
	import java.util.{ Scanner => In }
	import scala.util.control.Breaks._

	val in = new In(System.in)
	val out = new Out(System.out)
	val n = in.nextInt()
	var arr = new Array[Int](n)
	var left = 0
	var has = 0

	(0 until n).foreach { i =>
		arr(i) = in.nextInt()
		left += arr(i)
	}
	arr = arr.sortWith(_ > _)

	var buff = arr.takeWhile { x =>
		has += x
		left -= x
		has <= left
	}
	out.println(buff.size + 1)
	out.close
}

object Twins {
  def main(args: Array[String]): Unit = {
    readInt()
    val nums = readLine().split(" ").map(_.toInt).sorted
    var sum: Long = nums.sum
    var mySum: Long = 0
    var coinsCount = 0
    for (i <- nums.reverse) {
      if (mySum <= sum) coinsCount += 1
      mySum += i
      sum -= i
    }
    println(coinsCount)
  }
}

object CF0160A extends App {

  val n = readInt()
  val a = readLine().split(" ").map(_.toInt).toList.sorted.reverse

  var sum = a.sum

  var minSum = 0
  var min = 0

  a.foreach(n => {
    if (minSum <= sum) {
      minSum += n
      sum -= n
      min += 1
    }
  })
  println(min)

}

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

object Task {

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

    val n: Int = StdIn.readInt()
    var a: Array[Int] = StdIn.readLine().split(" ").map(_.toInt)
    println(solve(a))

  }

  private def solve(a: Array[Int]): Int = {
    Sorting.quickSort(a)
    var sum: Int = 0
    for (x <- a) {
      sum += x
    }
    var sol: Int = 0
    var currSum: Int = 0
    for (i <- a.length - 1 to 0 by -1) {
      sol += 1
      currSum += a(i)
      if (currSum > sum / 2) {
        return sol
      }
    }
    return -1
  }

}

object Solution160A extends App {

  def solution() {
    val n = _int
    val coins = 1.to(n).map(_ => _int).sortBy(-_)
    val sum = coins.foldLeft(0)((s, c) => s + c)
    val result = coins.foldLeft((0, 0))((memo, c) => memo._1 match {
      case l if l <= (sum - l) => (memo._1 + c, memo._2 + 1)
      case _ => memo
    })
    println(result._2)
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

//package round111.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 08.03.12
 * Time: 6:11
 * To change this template use File | Settings | File Templates.
 */

object A {
  readLine()
  val a = readLine() split ' ' map (_ toInt) sortBy (-_)
  var s = -a.sum / 2
  val b = for (coin <- a.iterator takeWhile (_ => s <= 0)) yield {
    s += coin
    coin
  }

  def main(args: Array[String]) = println(b.size)

}

object Competition extends App {

  import scala.io.StdIn._

  val k: Int = readInt()

  val coins: Seq[Int] = readLine().split(" ").map(Integer.parseInt).toSeq.sorted.reverse
  val amount: Int = coins.sum / 2

  def sumUp(half: Int, sum: Int, num: Int, coinsLeft: Seq[Int]): Int = {
    if (sum > half) num
    else sumUp(half, sum + coinsLeft.head, num + 1, coinsLeft.tail)
  }

  println(sumUp(amount, 0, 0, coins))
}

import scala.collection.mutable._
import scala.math._
import scala.util._
import scala.util.control.Breaks.break
import scala.util.control.Breaks.breakable
import java.util._
object Main extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val tt = for(i <- 1 to n) yield sc.nextInt
  val t = Sorting.stableSort(tt).reverse
  val sum = t.foldLeft(0){_+_}
  var tmp = 0
  var res = -1
  for(i <- 0 until n) {
    tmp += t(i)
    if(res == -1 && tmp > (sum-tmp)) res = i+1
  }
  println(res)
}

import scala.io.StdIn

object Twins_160 {
  def main(args: Array[String]): Unit = {
    val numOfCoins = StdIn.readInt()
    val coins = StdIn.readLine().split(" ").map(_.toInt)

    val coinsSorted = coins.sorted
    println(getMinCoins(0, coins.sum, coins.sorted(Ordering[Int].reverse), 0))
  }

  def getMinCoins(mySum: Int, twinSum: Int, coins: Array[Int], numOfCoins: Int): Int = {
    if (mySum > twinSum) return numOfCoins
    getMinCoins(mySum + coins.head, twinSum - coins.head, coins.tail, numOfCoins + 1)
  }

}

import scala.io.StdIn.readLine

/**
  * @author traff
  */

object Main extends App {
  val n = readLine().toInt

  val a = readLine().split("\\s+").map(_.toInt).sortWith(_ > _)

  val sum = a.sum

  println(a.scanLeft(0)(_ + _).takeWhile(c => c <= sum - c).length)
}

import scala.io.StdIn.readLine

/**
  * @author traff
  */

object Main extends App {
  val n = readLine().toInt

  val a = readLine().split("\\s+").map(_.toInt).sortWith(_ > _)

  val sum = a.sum

  var i = 0
  var s1 = 0
  while (i<n && s1<= sum - s1) {
    s1 += a(i)
    i+=1
  }

  println (i)

}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val a = in.next().split(" ").map(_.toInt).sorted.reverse
  val sum = a.sum
  var i = 0
  var count = 0
  while (i < a.length && sum - (count + a(i)) >= count + a(i)) {
    count = count + a(i)
    i += 1
  }
  println(i + 1)
}

object Main {

  def main(args: Array[String]) {
    val std = scala.io.StdIn

    val n = std.readLine().toInt
    val values = std.readLine().split(' ').map(_.toInt)

    val halfSum = values.sum / 2
    val result = values.sorted.foldRight((0,0))((y,x) => if (x._2 <= halfSum) (x._1 + 1, x._2 + y) else x)
    print(result._1)

  }
}

/**
 * Created by richard on 2015/6/9.
 */
import scala.io.StdIn
object cf160a {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val c = StdIn.readLine().split(" ").map(_.toInt).toSeq.sortWith(_>_)
    var sum = c.sum
    var msum = 0
    println(c.takeWhile( i=>{sum-=i; msum+=i; msum-i<=sum+i}).length)
  }
}

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

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

  val N = sc.nextInt

  def solve: Int = {
    val coins = List.fill(N)(sc.nextInt)
    val half = coins.sum / 2

    @tailrec
    def loop(acc: Int, cs: List[Int], num: Int): Int =
      if (acc > half) num
      else loop(acc + cs.head, cs.tail, num + 1)
    loop(0, coins.sortBy(identity[Int]).reverse, 0)
  }

  out.println(solve)
  out.close
}

object Twins {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in)
				val _ = scanner.nextLine
				val input = scanner.nextLine
				var sequence = input.split(" ").map(s => s.toInt)
				sequence = sequence.sortWith(_ > _)
				val sum = sequence.foldLeft(0){
			(acc, num) => acc + num
		}
		var tmpSum = 0
				var number = 0
				while (tmpSum <= sum / 2) {
					val elt = sequence(number)
							number += 1
							tmpSum += elt
				}
		println(number)
	}
}

object Codeforces160A extends App{

  def DivideCoins(coinnumber:Int):Int={
    var coinarray:Array[Int]=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    coinarray=coinarray.sorted
    for (i <- 0 until coinnumber){
      val (tempa,tempb)=coinarray.splitAt(coinnumber-i-1)
      if (tempa.sum < tempb.sum) return i+1
    }
    return coinnumber
  }
  val numberofcoin:Int=scala.io.StdIn.readInt
  println(DivideCoins(numberofcoin))

}

import java.io._

object Main {

  def main(args: Array[String]) {
    val n = readInt
    val list = (for(i <- 0 until n) yield readInt).sortWith(_ > _)
    val sum = (0 /: list)(_ + _)
    def getCnt(i: Int,  amount: Int) : Int = if(amount < 0) i else getCnt(i + 1, amount - list(i))
    println(getCnt(0, sum / 2))
  }

  val in = new StreamTokenizer(new InputStreamReader(System.in))

  def readInt = {
    in.nextToken()
    in.nval.asInstanceOf[Int]
  }
}

object Main {
  import java.io.{InputStreamReader, StreamTokenizer}

  def main(args: Array[String]) {
    val n = readInt
    val list = (for(i <- 0 until n) yield readInt).sortWith(_ > _)
    val sum = (0 /: list)(_ + _)
    def getCnt(i: Int,  amount: Int) : Int = if(amount < 0) i else getCnt(i + 1, amount - list(i))
    println(getCnt(0, sum / 2))
  }

  val in = new StreamTokenizer(new InputStreamReader(System.in))

  def readInt = {
    in.nextToken()
    in.nval.asInstanceOf[Int]
  }
}

object A extends App {
  val n = readLine
  val c = readLine.split(" ").map(_.toInt).toSeq.sortWith(_>_)
  var sum = c.sum
  var tsum = 0
  println (c.takeWhile( i => { sum -= i; tsum += i; tsum-i <= sum+i }).length)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val a = readLine().split(" ").map(_.toInt)
    val sum = a.sum / 2
    val sorted = a.sortWith(_ > _)
    val res = sorted.foldLeft((0, 0)) { (t, e) =>
      if (t._1 > sum) t
      else (t._1 + e, t._2 + 1)
    }
    println(res._2)
  }
}

import scala.io.StdIn._

object _160_A extends App {
  readInt()
  val coins = readLine().split(" ").map(_.toInt).sortWith(_ > _)

  var rest = coins.sum
  var current = 0
  var i = 0

  while (current <= rest) {
    current += coins(i)
    rest -= coins(i)
    i+=1
  }

  println(i)
}

import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
  val n = readLine.toInt
    val A = readLine.split(' ').map(_.toInt).sortWith(_ > _)
    var s = A.sum
    var t = 0
    var cnt = 0
   while(s >= t){
     s = s - A(cnt)
     t = t + A(cnt)
     cnt = cnt + 1
   }
    println(cnt)
  }
}

import java.util.Scanner

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

object HelloWorldMain {

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

    val sc = new Scanner(System.in)

    val n = sc.nextInt()

    var list = new Array[Int](n)

    var sum = 0
    for(i <- 0 until  n ) {
      list(i) = sc.nextInt()
      sum += list(i)
    }

    Sorting.quickSort(list)

    var takenAmount = 0
    var iterator = n-1
    var totalnumberOfCoins = 0
    while (takenAmount <= sum/2 ){
      takenAmount += list(iterator)
      totalnumberOfCoins += 1
      iterator -=1
    }

    println(totalnumberOfCoins)

  }
}

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

object Twins {

  def main(args: Array[String]) {
    val n = readInt
    val coins = readLine.split(' ').map(_.toInt).sorted.reverse
    val toTake = coins.sum/2 + 1
    println(coins.scanLeft(0)(_ + _)
      .zipWithIndex.find{ case (s,i) => s >= toTake}.getOrElse( (0,0))._2)
  }

}

import java.util.Scanner

/**
  * Created by dr0ff on 02/03/16.
  */
object Twins {

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)

    val num = in.nextLine().trim.toInt
    val coins = in.nextLine().trim.split(" ").map(_.toInt)
    print(minHalfNum(coins))
  }

  def minHalfNum(coins: Array[Int]): Int = {
    val half = coins.sum / 2.0
    def loop(coins: List[Int], num: Int, total: Long): Int =
      if (total > half)
        num
      else
        coins match {
          case c :: cs => loop(cs, num + 1, total + c)
          case Nil => num
        }

    loop(coins.sorted(Ordering[Int].reverse).toList, 0, 0)
  }
}

import scala.io.StdIn._

object Task extends App{
	val N = readLine.split(" ").map{_.toInt}.head
	val coins = readLine.split(" ").map{_.toInt}.sorted.reverse

	val leftSums = coins.scanLeft(0)((a,b) => a + b).tail
	val rightSums = coins.scanRight(0)((a,b) => a + b).tail

	//println(leftSums.mkString)
	//println(rightSums.mkString)

	val a = leftSums.zip(rightSums).filter{case (l,r) => l <= r}
	//println(a.mkString)

	println(a.size + 1)
}

import java.util.Scanner
import scala.collection.mutable.ListBuffer

object Main {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt
    val xs = new ListBuffer[Int]
    for (i <- 1 to n) {
      xs += sc.nextInt
    }
    val ys = xs.sortWith(_ > _).toList
    var sumA = 0
    var sumB = ys.sum
    var flag = false
    var index = ys.size
    for (i <- 0 until ys.size) {
      if (!flag) {
        if (sumA <= sumB) {
          sumA += ys(i)
          sumB -= ys(i)
        } else {
          index = i
          flag = true
        }
      }
    }
    println(index)
  }
}

import java.util.Scanner
import scala.util.control.Breaks._

import sun.swing.SwingUtilities2.RepaintListener

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

    val s = new Scanner(System.in)
    val a = s.nextInt()
    val numbers: Array[Int] = Array.fill(a) {
      0
    }
    for (i <- 0 until a){
      numbers(i) = s.nextInt()
    }

    val list = numbers.toList.sorted

    val rev = list.reverse

    val llist = list.scanLeft(0)(_+_)

    val lllist = llist.reverse

    val rlist = rev.scanLeft(0)(_+_)

//
    val uno = lllist.zip(rlist).filter{case (l,r) => l <= r}
    println(uno.length)

  }
}

import java.util.Scanner
import scala.util.control.Breaks._

import sun.swing.SwingUtilities2.RepaintListener

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

    val s = new Scanner(System.in)
    val a = s.nextInt()
    val numbers: Array[Int] = Array.fill(a) {
      0
    }
    for (i <- 0 until a){
      numbers(i) = s.nextInt()
    }

    val list = numbers.toList.sorted

    val rev = list.reverse

    val llist = list.scanLeft(0)(_+_)

    val lllist = llist.reverse

    val rlist = rev.scanLeft(0)(_+_)

    val uno = lllist.zip(rlist).filter{case (l,r) => l <= r}
    println(uno)

  }
}

object One60A extends App {
        import java.io.{ PrintWriter => Out }
        import java.util.{ Scanner => In }
        import scala.util.control.Breaks._

	val in = new In(System.in)
	val out = new Out(System.out)
	val n = in.nextInt()
	var arr = new Array[Int](n)
	var left = 0
	var has = 0

	(0 until n).foreach { i =>
		arr(i) = in.nextInt()
		left += arr(i)
	}
	arr = arr.sortWith(_ > _)

	var buff = arr.takeWhile { x =>
		has += x
		left -= x
		has < left
	}
	out.println(buff.size + 1)
	out.close
}

object One60A extends App {
        import java.io.{ PrintWriter => Out }
        import java.util.{ Scanner => In }
        import scala.util.control.Breaks._

	val in = new In(System.in)
	val out = new Out(System.out)
	val n = in.nextInt()
	var arr = new Array[Int](n)
	var left = 0
	var has = 0

	(0 until n).foreach { i =>
		arr(i) = in.nextInt()
		left += arr(i)
	}
	arr = arr.sortWith(_ > _)

	var buff = arr.takeWhile { x =>
		has += x
		has < left
	}
	out.println(buff.size + 1)
	out.close
}

object CF0160A extends App {

  val n = readInt()
  val a = readLine().split(" ").map(_.toInt).toList.sorted

  var sum = a.sum

  var minSum = 0
  var min = 0

  a.foreach(n => {
    if (minSum <= sum) {
      minSum += n
      sum -= n
      min += 1
    }
  })
  println(min)

}

//package round111.div2

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 08.03.12
 * Time: 6:11
 * To change this template use File | Settings | File Templates.
 */

object A {
  readLine()
  val a = readLine() split ' ' map (_ toInt) sorted
  var s = -a.sum / 2
  val b = for (coin <- a.iterator takeWhile (_ => s <= 0)) yield {
    s += coin
    coin
  }

  def main(args: Array[String]) = println(b.size)

}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val a = in.next().split(" ").map(_.toInt).sorted.reverse
  val sum = a.sum
  var i = 0
  var count = 0
  while (i < a.size && count + a(i) > a.sum / 2) i += 1
  println(i)
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val a = in.next().split(" ").map(_.toInt).sorted.reverse
  val sum = a.sum
  var i = 0
  var count = 0
  while (i < a.length && count + a(i) <= sum / 2) i += 1
  println(i)
}

/**
 * Created by richard on 2015/6/9.
 */
import scala.io.StdIn
object cf160a {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val c = StdIn.readLine().split(" ").map(_.toInt).sortWith(_>_)
    var sum = c.sum
    var msum = 0
    println(c.takeWhile( i=>{sum-=i; msum+=i; msum-i<sum+i}).length)
  }
}

import java.io._

object Main {

  def main(args: Array[String]) {
    val n = readInt
    val list = for(i <- 0 until n) yield readInt
    list.sortWith(_ > _)
    val sum = (0 /: list)(_ + _)
    def getCnt(i: Int,  amount: Int) : Int = if(amount < 0) i else getCnt(i + 1, amount - list(i))
    println(getCnt(0, sum / 2))
  }

  val in = new StreamTokenizer(new InputStreamReader(System.in))

  def readInt = {
    in.nextToken()
    in.nval.asInstanceOf[Int]
  }
}

import scala.io.StdIn._

object _160_A extends App {
  readInt()
  val coins = readLine().split(" ").map(_.toInt).sortWith(_ > _)
  println(coins.mkString(" "))

  var rest = coins.sum
  var current = 0
  var i = 0

  while (current <= rest) {
    current += coins(i)
    rest -= coins(i)
    i+=1
  }

  println(i)
}

import java.util.Scanner

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

object HelloWorldMain {

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

    val sc = new Scanner(System.in)

    val n = sc.nextInt()

    var list = new Array[Int](n)

    var sum = 0
    for(i <- 0 until  n ) {
      list(i) = sc.nextInt()
      sum += list(i)
    }

    Sorting.quickSort(list)

    var takenAmount = 0
    var iterator = n-1
    var totalnumberOfCoins = 0
    while (takenAmount <= sum/2 ){
      takenAmount += list(iterator)
      totalnumberOfCoins += 1
    }

    println(totalnumberOfCoins)

  }
}

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

object Twins {

  def main(args: Array[String]) {
    val n = readInt
    val coins = readLine.split(' ').map(_.toInt).sorted
    val toTake = coins.sum/2 + 1
    println(coins.scanLeft(0)(_ + _)
      .zipWithIndex.find{ case (s,i) => s >= toTake}.getOrElse( (0,0))._2)
  }

}

import scala.io.StdIn._

object Task extends App{
	val N = readLine.split(" ").map{_.toInt}.head
	val coins = readLine.split(" ").map{_.toInt}.sorted

	val leftSums = coins.scanLeft(0)((a,b) => a + b).tail
	val rightSums = coins.scanRight(0)((a,b) => a + b).tail

	//println(leftSums.mkString)
	//println(rightSums.mkString)

	val a = leftSums.zip(rightSums).filter{case (l,r) => l <= r}
	//println(a.mkString)

	println(a.size + 1)
}


Pashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.

The first line contains four space-separated x1, y1, x2, y2 ( - 100 ≤ x1, y1, x2, y2 ≤ 100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.

If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3, y3, x4, y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them.  Note that x3, y3, x4, y4 must be in the range ( - 1000 ≤ x3, y3, x4, y4 ≤ 1000).

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

/**
 * Created by arseny on 15.08.14.
 */
object A extends App {

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

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

  def solve() = {
    val x1 = nextInt
    val y1 = nextInt
    val x2 = nextInt
    val y2 = nextInt
    if(x1 == x2) {
      val x3 = x1 + math.abs(y2 - y1)
      out.print(Array(x3, y1, x3, y2).mkString(" "))
    } else if(y1 == y2) {
      val y3 = y1 + math.abs(x2 - x1)
      out.print(Array(x1, y3, x2, y3).mkString(" "))
    } else {
      val x = math.abs(x2 - x1)
      val y = math.abs(y2 - y1)
      if(x != y) {
        out.print(-1)
      } else {
        if((x2 - x1) * (y2 - y1) > 0) {
          out.print(Array(math.min(x1, x2), math.max(y1, y2), math.max(x1, x2), math.min(y1, y2)).mkString(" "))
        } else {
          out.print(Array(math.min(x1, x2), math.min(y1, y2), math.max(x1, x2), math.max(y1, y2)).mkString(" "))
        }
      }
    }
  }

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

import java.util.StringTokenizer

object _459A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val x1 = next.toInt
  val y1 = next.toInt
  val x2 = next.toInt
  val y2 = next.toInt
  if (x1 == x2) {
    val len = (y1 - y2).abs
    println("%d %d %d %d".format(x1 - len, y1, x1 - len, y2))
  } else if (y1 == y2) {
    val len = (x1 - x2).abs
    println("%d %d %d %d".format(x1, y1 - len, x2, y1 - len));
  } else {
    if ((x1 - x2).abs != (y1 - y2).abs) println(-1)
    else {
      val len = (x1 - x2).abs
      println("%d %d %d %d".format(x1, y2, x2, y1));
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var Array(x1, y1, x2, y2) = in.next().split(" ").map(_.toInt)
  if (x2 < x1 || (x2 == x2 && y2 < y1)) {
    val tmp = x2
    x2 = x1
    x1 = tmp
    val tmp2 = y2
    y2 = y1
    y1 = tmp2
  }

  val width = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2))
  if (Math.abs(x1 - x2) != 0 && Math.abs(y1 - y2) != 0 && Math.abs(x1 - x2) != Math.abs(y1 - y2))
    println(-1)
  else if (x1 == x2)
    println(List(x1 + width, y1, x2 + width, y2).mkString(" "))
  else if (y1 == y2)
    println(List(x1, y1 + width, x2, y2 + width).mkString(" "))
  else
    println(List(x1, y2, x2, y1).mkString(" "))
}

/**
 * Created by lurker on 2014. 8. 15..
 */
object CF261_1 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(x1, y1, x2, y2) = readInts(4)

  val minx = x1 min x2
  val maxx = x1 max x2
  val miny = y1 min y2
  val maxy = y1 max y2

  if (minx == maxx) {
    val dist = maxy - miny
    val Array(x3, y3, x4, y4) = Array(minx + dist, miny, minx + dist, maxy)
    println(s"${x3} ${y3} ${x4} ${y4}")
  } else if (miny == maxy) {
    val dist = maxx - minx
    val Array(x3, y3, x4, y4) = Array(minx, miny + dist, maxx, miny + dist)
    println(s"${x3} ${y3} ${x4} ${y4}")
  } else {
    if (maxx - minx != maxy - miny) {
      println("-1")
    } else {
      val Array(x3, y3, x4, y4) = Array(x1, y2, x2, y1)
      println(s"${x3} ${y3} ${x4} ${y4}")
    }
  }
}

object A459 {
  @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(x1, y1, x2, y2) = readInts(4)
    if(x1 == x2) {
      if(y1 != y2) {
        println(s"${x1 + math.abs(y2 - y1)} $y2 ${x1 + math.abs(y2 - y1)} $y1")
      } else {
        println("-1")
      }
    } else if(y1 == y2) {
      if(x1 != x2) {
        println(s"$x2 ${y1 + math.abs(x2 - x1)} $x1 ${y1 + math.abs(x2 - x1)}")
      } else {
        println("-1")
      }
    } else {
      if(math.abs(x1-x2) == math.abs(y1-y2)) {
        println(s"$x1 $y2 $x2 $y1")
      } else {
        println("-1")
      }
    }
  }
}

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 x1 = nextInt
    val y1 = nextInt
    val x2 = nextInt
    val y2 = nextInt
    if (x1 != x2 && y1 != y2) {
      if (Math.abs(x1 - x2) != Math.abs(y1 - y2)) {
        out.println(-1)
      } else {
        out.print(x1 + " " + y2 + " " + x2 + " " + y1)
      }
    } else if (x1 == x2) {
      val d = Math.abs(y1 - y2)
      out.print((x1 + d) + " " + y1 + " " + (x1 + d) + " " + y2)
    } else if (y1 == y2) {
      val d = Math.abs(x1 - x2)
      out.print(x1 + " " + (y1 + d) + " " + x2 + " " + (y1 + d))
    }
    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.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A459 extends App{
  val sc = new Scanner(System.in)
  val x1, y1, x2, y2 = sc.nextInt()

  if (x1 == x2) {
    println((x1 + math.abs(y2 - y1)) + " " + y1 + " " + (x1 + math.abs(y2 - y1)) + " " + y2)
  } else if (y1 == y2){
    println(x1 + " " + (y1 + math.abs(x2 - x1)) + " " + x2 + " " + (y1 + math.abs(x2 - x1)))
  } else if (math.abs((x2 - x1) / (y2 - y1).toDouble) == 1) {
    println(x1 + " " + y2 + " " + x2 + " " + y1)
  } else {
    println(-1)
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    println(findCoords(io.StdIn.readLine().split(' ').map(x => Integer.parseInt(x))))
  }

  def findCoords(points: Array[Int]): String = {
    if (points(0) == points(2)) {
      val side = points(3) - points(1)
      List(points(0) + side, points(1), points(2) + side, points(3)).mkString(" ")
    }
    else if (points(1) == points(3)) {
      val side = points(2) - points(0)
      List(points(0), points(1) + side, points(2), points(3) + side).mkString(" ")
    }
    else {
      val h = points(2) - points(0)
      val v = points(3) - points(1)
      if (Math.abs(h) - Math.abs(v) != 0) {
        return -1 + ""
      } else {
        List(points(0) + h, points(1), points(0), points(1) + v).mkString(" ")
      }
    }
  }

}

object main extends App with fastIO {

  case class Point(x: Int, y: Int)

  var p1 = Point(nextInt, nextInt)
  var p2 = Point(nextInt, nextInt)
  var length = (p1.x - p2.x + p1.y - p2.y).abs

  var p3 = Point(0, 0)
  var p4 = Point(0, 0)

  var f = true
  if ((p1.x - p2.x).abs == (p1.y - p2.y).abs) { p3 = Point(p1.x, p2.y); p4 =  Point(p2.x, p1.y) }
  else if (p1.x == p2.x) { p3 = Point(p1.x + length, p1.y); p4 =  Point(p1.x + length, p2.y) }
  else if (p1.y == p2.y) { p3 = Point(p1.x, p1.y + length); p4 =  Point(p2.x, p1.y + length) }
  else f = false

  if (!f) println(-1) else
    println("%d %d %d %d" format (p3.x, p3.y, p4.x, p4.y))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

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

/**
 * Created by arseny on 15.08.14.
 */
object A extends App {

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

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

  def solve() = {
    val x1 = nextInt
    val y1 = nextInt
    val x2 = nextInt
    val y2 = nextInt
    if(x1 == x2) {
      val x3 = x1 + math.abs(y2 - y1)
      out.print(Array(x3, y1, x3, y2).mkString(" "))
    } else if(y1 == y2) {
      val y3 = y1 + math.abs(x2 - x1)
      out.print(Array(x1, y3, x2, y3).mkString(" "))
    } else {
      val x = math.abs(x2 - x1)
      val y = math.abs(y2 - y1)
      if(x != y) {
        out.print(-1)
      } else {
        out.print(Array(math.min(x1, x2), math.max(y1, y2), math.max(x1, x2), math.min(y1, y2)).mkString(" "))
      }
    }
  }

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

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

/**
 * Created by arseny on 15.08.14.
 */
object A extends App {

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

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

  def solve() = {
    val x1 = nextInt
    val y1 = nextInt
    val x2 = nextInt
    val y2 = nextInt
    if(x1 == x2) {
      val x3 = x1 + math.abs(y2 - y1)
      out.print(Array(x3, y1, x3, y2).mkString(" "))
    } else if(y1 == y2) {
      val y3 = y1 + math.abs(y2 - y1)
      out.print(Array(x1, y3, x2, y3).mkString(" "))
    } else {
      val x = math.abs(x2 - x1)
      val y = math.abs(y2 - y1)
      if(x != y) {
        out.print(-1)
      } else {
        out.print(Array(math.min(x1, x2), math.max(y1, y2), math.max(x1, x2), math.min(y1, y2)).mkString(" "))
      }
    }
  }

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var Array(x1, y1, x2, y2) = in.next().split(" ").map(_.toInt)
  if (x2 < x1 || (x2 == x2 && y2 < y1)) {
    val tmp = x2
    x2 = x1
    x1 = tmp
    val tmp2 = y2
    y2 = y1
    y1 = tmp2
  }

  val width = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2))
  if (Math.abs(x1 - x2) != 0 && Math.abs(y1 - y2) != 0 && Math.abs(x1 - x2) != Math.abs(y1 - y2))
    println(-1)
  else if (y2 < y1)
    println(List(x1, y2, x2, y1).mkString(" "))
  else if (x1 == x2)
    println(List(x1 + width, y1, x2 + width, y2).mkString(" "))
  else if (y1 == y2)
    println(List(x1, y1 + width, x2, y2 + width).mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next().split(" ").map(_.toInt)
  if (data.distinct.length != 2) println(-1)
  else {
    val min = data.min
    val max = data.max
    val s = Set((min, max), (max, min), (min, min), (max, max)) -- Set((data(0), data(1)), (data(2), data(3)))
    println(s.toList.flatMap(t => List(t._1, t._2)).mkString(" "))
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next().split(" ").map(_.toInt)
  if (data.distinct.length != 2) println(-1)
  else {
    val min = data.min
    val max = data.max
    val s = Set((min, max), (max, min), (min, min), (max, max)) -- Set((data(0), data(1)), (data(2), data(3)))
    println(s.flatMap(t => List(t._1, t._2)).mkString(" "))
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var Array(x1, y1, x2, y2) = in.next().split(" ").map(_.toInt)
  if (x2 < x1 || (x2 == x2 && y2 < y1)) {
    val tmp = x2
    x2 = x1
    x1 = tmp
    val tmp2 = y2
    y2 = y1
    y1 = tmp2
  }

  val width = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2))
  if (Math.abs(x1 - x2) != 0 && Math.abs(y1 - y2) != 0 && Math.abs(x1 - x2) != Math.abs(y1 - y2))
    println(-1)
  if (x1 == x2)
    println(List(x1 + width, y1, x2 + width, y2).mkString(" "))
  else if (y1 == y2)
    println(List(x1, y1 + width, x2, y2 + width).mkString(" "))
  else
    println(List(x1, y2, x2, y1).mkString(" "))
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A459 extends App{
  val sc = new Scanner(System.in)
  val x1, y1, x2, y2 = sc.nextInt()

  if (x1 == x2) {
    println((x1 + math.abs(y2 - y1)) + " " + y1 + " " + (x1 + math.abs(y2 - y1)) + " " + y2)
  } else if (y1 == y2){
    println(x1 + " " + (y1 + math.abs(x2 - x1)) + " " + x2 + " " + (y1 + math.abs(x2 - x1)))
  } else if ((x2 - x1) / (y2 - y1).toDouble == 1) {
    println(x1 + " " + y2 + " " + x2 + " " + y1)
  } else {
    println(-1)
  }
}