object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    def minimal(a:String):String={
      if(a.length%2==1){
        return a
      }
      val a1=minimal(a slice(0,a.length/2))
      val a2=minimal(a slice(a.length/2,a.length))
      if(a1<a2){
        return a1+a2
      }else{
        return a2+a1
      }
    }
    val a=nextString
    val b=nextString
    if(minimal(a)==minimal(b)){
      out.println("YES")
    }else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    val a = readLine()
    val b = readLine()

    if (gao(a) == gao(b)) println("YES") else println("NO")
  }

  private def gao(s: String): String = {
    val n = s.length
    if (n % 2 == 1) s
    else {
      val l = gao(s.take(n/2))
      val r = gao(s.drop(n/2))
      if (l < r) l + r else r + l
    }
  }

}

import scala.io.Source

object Solution extends App {

  def isEq(a: String, b: String, start1: Int, start2: Int, length: Int): Boolean = {
    if (length % 2 == 1)  (0 until length).forall(i => a(start1 + i) == b(start2 + i))
    else {
      val nLength = length / 2
      (isEq(a, b, start1, start2, nLength) && isEq(a, b, start1 + nLength, start2 + nLength, nLength)) ||
        (isEq(a, b, start1 + nLength, start2, nLength) && isEq(a, b, start1, start2 + nLength, nLength))
    }
  }

  val in = Source.stdin.getLines()
  val str1 = in.next()
  val str2 = in.next()
  if (isEq(str1, str2, 0, 0, str1.length))
    println("YES")
  else
    println("NO")
}

// ----------------------------------------------------------------------------0
// ----------------------------------------------------------------------------0
object Main {
  def main(args: Array[String]) : Unit = {
    def equiv(a : String, b : String) : Boolean = {
      if(a == b) true
      else if(a.length % 2 == 1) false
      else {
        val (a1,a2) = a.splitAt(a.length/2)
        val (b1,b2) = b.splitAt(b.length/2)
        (equiv(a1,b1) && equiv(a2,b2)) ||
        (equiv(a2,b1) && equiv(a1,b2))
      }
    }
    def naive(a : String, b : String) : Boolean = {
      equiv(a,b)
    }
    def fast(a : String, b : String) : Boolean = {
      fast_equiv(a,b,0,a.length-1,0,b.length-1)
    }

    def check(sa : String, sb : String, n : Int, a0 : Int, b0 : Int) : Boolean = {
      (0 to n).forall((i) => sa(a0+i) == sb(b0+i))
    }
    def fast_equiv(sa : String,
                   sb : String,
                   a0 : Int, a1 : Int,
                   b0 : Int, b1 : Int) : Boolean = {
      val n = a1 - a0
      if(check(sa,sb,n,a0,b0)) true
      else if(n % 2 == 0) false
      else {
        val c = a0 + n/2
        val d = b0 + n/2
        val e = c + 1
        val f = d + 1
        (fast_equiv(sa,sb,a0,c,b0,d) && fast_equiv(sa,sb,e,a1,f,b1)) ||
        (fast_equiv(sa,sb,a0,c,f,b1) && fast_equiv(sa,sb,e,a1,b0,d))
      }
    }

    def main() : Unit = {
      val a = readLine()
      val b = readLine()
      val ans = naive(a,b)
      if(ans){
        println("YES")
      }else{
        println("NO")
      }
    }
    main()
  }
}

object EquivalentStrings {

  def main(args: Array[String]) {
    //read the strings
    val a = readLine
    val b = readLine

    if(lexicoHash(a) == lexicoHash(b))
      printf("YES")
    else
      printf("NO")

  }

  def lexicoHash(string: String) : String = {
    if(string.length % 2 == 1)
      return string

    var rightHalf = lexicoHash(string.substring(0, string.length / 2))
    var leftHalf = lexicoHash(string.substring(string.length / 2, string.length))

    if(rightHalf > leftHalf)
      return leftHalf + rightHalf
    else return rightHalf + leftHalf
  }

}

import scala.io.StdIn._

/**
 * Created by slie742 on 18/09/2015.
 */
object EquivalentStrings {

  def canonical(s: String) : String = {
    if (s.length%2 != 0) s
    else {
      val s1 = canonical(s.take(s.length/2))
      val s2 = canonical(s.drop(s.length/2))
      if (s1 <= s2) s1 + s2 else s2 + s1
    }
  }

  def equivalent(a: String, b: String) : Boolean = {
    //println(s"$a $b")
    if (a == b ) true
    else if (a.length%2 != 0 || a.sorted != b.sorted) false
         else {
      val a1 = a.take(a.length/2)
      val a2 = a.drop(a.length/2)
      val b1 = b.take(a.length/2)
      val b2 = b.drop(b.length/2)
      (equivalent(a1,b1) && equivalent(a2,b2)) || (equivalent(a1,b2) && equivalent(a2,b1))
    }
  }

  def main(args: Array[String]): Unit = {
    val s1 = readLine()
    val s2 = readLine()
    // if (s1.length == s2.length && equivalent(s1,s2)) println("YES") else println("NO")
    //println(s"can s1 = ${canonical(s1)}")
    //println(s"can s2 = ${canonical(s2)}")
    if (canonical(s1) == canonical(s2))
      println("YES")
    else
      println("NO")
  }

}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    val a = readLine()
    val b = readLine()

    if (gao(a, b)) println("YES") else println("NO")
  }

  private def gao(a: String, b: String): Boolean = {
    var n = a.length
    while (n % 2 == 0) {
      n /= 2
    }

    a.grouped(2 * n).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted == b.grouped(2*n).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted

  }

}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    val a = readLine()
    val b = readLine()

    if (gao(a, b)) println("YES") else println("NO")
  }

  private def gao(a: String, b: String): Boolean = {
    var n = a.length
    while (n % 2 == 0) {
      n /= 2
    }

    a.grouped(2 * n).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted == b.grouped(2).map(_.grouped(n).toSeq.sorted.mkString).toSeq.sorted

  }

}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    val a = readLine()
    val b = readLine()

    if (gao(a, b)) println("YES") else println("NO")
  }

  private def gao(a: String, b: String): Boolean = {
    if (a == b) true
    else {
      val n = a.length
      if (n == 1) false
      else {
        if (gao(a.take(n/2), b.take(n/2)) && gao(a.drop(n/2), b.drop(n/2))) true
        else gao(a.take(n/2), b.drop(n/2)) && gao(a.drop(n/2), b.take(n/2))
      }
    }
  }
}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    val a = readLine()
    val b = readLine()

    if (gao(a, b)) println("YES") else println("NO")
  }

  private def gao(a: String, b: String): Boolean = {
    var n = a.length
    while(n % 2 == 0) {
      n /= 2
    }

    if (n == 1) {
      a.grouped(2).map(_.sorted).toSeq.sorted == b.grouped(2).map(_.sorted).toSeq.sorted
    } else {
      a.grouped(n).toSeq.sorted == b.grouped(n).toSeq.sorted
    }

  }

}

import io.StdIn._

object Solution {
  def main(args: Array[String]) {
    val a = readLine()
    val b = readLine()

    if (gao(a, b)) println("YES") else println("NO")
  }

  private def gao(a: String, b: String): Boolean = {
    var n = a.length
    while(n % 2 == 0) {
      n /= 2
    }

    if (n == 1) {
      a.grouped(2).map(_.sorted).toSeq.sorted == b.grouped(2).map(_.sorted).toSeq.sorted
    } else {
      a.grouped(2).toSeq.sorted == b.grouped(2).toSeq.sorted
    }

  }

}

object EquivalentStrings {

  //big prime number
  val PRIME = 666013

  def main(args: Array[String]) {
    //read the strings
    val a = readLine
    val b = readLine

    if(equivalent(a,b))
      printf("YES")
    else printf("NO")

  }

  //hash the string in order to see if it contains the same characters
  def hash(string: String) : Int = {
    var value = 1
    for(char <- string)
      value  = value * char.toInt % PRIME

    return value
  }

  def equivalent(a: String, b: String) : Boolean = {
    if(a == b)
      return true
    if(hash(a) != hash(b))
      return false

    //split the strings
    val a1 = a.substring(0, a.length / 2)
    val a2 = a.substring(a.length / 2, a.length)
    val b1 = b.substring(0, b.length / 2)
    val b2 = b.substring(b.length / 2, b.length)

    if(hash(a1) == hash(b1) && hash(a2) == hash(b2))
      return if(equivalent(a1,b1) && equivalent (a2,b2)) true else false

    if(hash(a1) == hash(b2) && hash(a2) == hash(b1))
      return if(equivalent(a1,b2) && equivalent(a2,b1)) true else false

    return false
  }

}

object EquivalentStrings {

  def main(args: Array[String]) {
    //read the strings
    val a = readLine
    val b = readLine

    if(lexicoHash(a) == lexicoHash(b))
      printf("YES")
    else
      printf("NO")

  }

  def lexicoHash(string: String) : String = {
    if(string.length == 1)
      return string

    var rightHalf = lexicoHash(string.substring(0, string.length / 2))
    var leftHalf = lexicoHash(string.substring(string.length / 2, string.length))

    if(rightHalf > leftHalf)
      return leftHalf + rightHalf
    else return rightHalf + leftHalf
  }

}

import scala.io.StdIn._

/**
 * Created by slie742 on 18/09/2015.
 */
object EquivalentStrings {

  def equivalent(s1: String, s2: String) : Boolean = {
    if (s1 == s2) true
    else if (s1.length%2 != 0 || s1.sorted != s2.sorted) false
         else equivalent(s1.take(s1.length/2), s2.drop(s1.length/2)) ||
              equivalent(s2.take(s1.length/2), s1.drop(s1.length/2))
  }

  def main(args: Array[String]): Unit = {
    val s1 = readLine()
    val s2 = readLine()
    if (s1.length == s2.length && equivalent(s1,s2)) println("YES") else println("NO")
  }

}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    def myEqual(a:String,b:String):Boolean={
      if(a.length>10){
        out.println(a.length+" "+b.length)
      }
      if(a==b){
        return true
      }
      if(a.length!=b.length || a.length%2==1){
        if(a.length>10){
          out.println(a.length+" "+b.length)
        }
        return false
      }
      val a1=a slice(0,a.length/2)
      val a2=a slice(a.length/2,a.length)
      val b1=b slice(0,b.length/2)
      val b2=b slice(b.length/2,b.length)
      if(a.length>10){
        out.println(a.length+" "+b.length)
      }
      return myEqual(a1,b2) && myEqual(a2,b1)
    }
    val a=nextString
    val b=nextString
    if(myEqual(a,b)){
      out.println("YES")
    }else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    def myEqual(a:String,b:String):Boolean={
      if(a.length>10){
        out.println(a.length+" "+b.length)
      }
      if(a==b){
        return true
      }
      if(a.length!=b.length || a.length%2==1){
        out.println(a.length+" "+b.length)
        return false
      }
      val a1=a slice(0,a.length/2)
      val a2=a slice(a.length/2,a.length)
      val b1=b slice(0,b.length/2)
      val b2=b slice(b.length/2,b.length)

      return myEqual(a1,b2) && myEqual(a2,b1)
    }
    val a=nextString
    val b=nextString
    if(myEqual(a,b)){
      out.println("YES")
    }else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    def myEqual(a:String,b:String):Boolean={
      if(a.length>10){
        out.println(a.length+" "+b.length)
      }
      if(a==b){
        return true
      }
      if(a.length!=b.length || a.length%2==1){
        return false
      }
      val a1=a slice(0,a.length/2)
      val a2=a slice(a.length/2,a.length)
      val b1=b slice(0,b.length/2)
      val b2=b slice(b.length/2,b.length)

      return myEqual(a1,b2) && myEqual(a2,b1)
    }
    val a=nextString
    val b=nextString
    if(myEqual(a,b)){
      out.println("YES")
    }else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    def myEqual(a:String,b:String):Boolean={
      if(a==b){
        return true
      }
      if(a.length!=b.length || a.length%2==1){
        return false
      }
      val a1=a slice(0,a.length/2)
      val a2=a slice(a.length/2,a.length)
      val b1=b slice(0,b.length/2)
      val b2=b slice(b.length/2,b.length)

      return myEqual(a1,b2) && myEqual(a2,b1)
    }
    val a=nextString
    val b=nextString
    if(myEqual(a,b)){
      out.println("YES")
    }else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    def myEqual(a:String,b:String):Boolean={
      if(a.length>10){
        out.println(a.length+" "+b.length)
      }
      if(a==b){
        return true
      }
      if(a.length!=b.length || a.length%2==1){
        if(a.length>10){
          out.println(a.length+" "+b.length)
        }
        return false
      }
      val a1=a slice(0,a.length/2)
      val a2=a slice(a.length/2,a.length)
      val b1=b slice(0,b.length/2)
      val b2=b slice(b.length/2,b.length)

      return myEqual(a1,b2) && myEqual(a2,b1)
    }
    val a=nextString
    val b=nextString
    if(myEqual(a,b)){
      out.println("YES")
    }else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    def myEqual(a:String,b:String):Boolean={

      if(a==b){
        return true
      }
      if(a.length!=b.length || a.length%2==1){

        return false
      }
      val a1=a slice(0,a.length/2)
      val a2=a slice(a.length/2,a.length)
      val b1=b slice(0,b.length/2)
      val b2=b slice(b.length/2,b.length)

      return myEqual(a1,b2) && myEqual(a2,b1)
    }
    val a=nextString
    val b=nextString
    if(a.length>10){
      out.println(a)
      out.println(b)
    }
    if(myEqual(a,b)){
      out.println("YES")
    }else{
      out.println("NO")
    }
    //code ends here
    out.flush
    out.close
  }
}


import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  def main(args: Array[String]) {
    val n = readLine.toInt
    val a = readInts(n)

    val d = Array.fill(5001)(0)
    val s = Array.fill(5001)(0)

    for (i <- 0 to n-1) {
      for (j <- 0 to i-1) {
        d(Math.abs(a(i) - a(j))) += 1
      }
    }

    for (i <- 1 to 5000) {
      s(i) = d(i) + s(i-1)
    }

    val t = n * (n - 1) / 2
    var res: Double = 0

    for (i <- 3 to 5000) {
      for (j <- 1 to i-2) {
        res += 1.0 * d(i) / t * d(j) / t * s(i-j-1) / t
      }
    }

    println(res)

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

import scala.collection._

object D 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) = readInts(1)
  val as = readInts(n)

  val cntNeg, cntPos = Array.fill(5000)(0L)

  for (i <- 0 until n) {
    for (j <- 0 until n) if (i != j) {
      val d = as(i) - as(j)
      if (d < 0) cntNeg(-d) += 1
      else cntPos(d) += 1
    }
  }

  val negSum = cntNeg.sum
  val posSum = cntPos.sum

  val cntNegSufSum = Array.fill(5001)(0L)
  for (i <- 4999 to 0 by -1) {
    cntNegSufSum(i) = cntNegSufSum(i + 1) + cntNeg(i)
  }

  var cntTot = posSum * posSum * negSum
  var cntOk = 0L
  for (d1 <- 0 until 5000) {
    for (d2 <- 0 until 5000) if (d1 + d2 < 5000) {
      //cntTot += cntPos(d1) * cntPos(d2) * negSum
      cntOk += cntPos(d1) * cntPos(d2) * cntNegSufSum(d1 + d2 + 1)
//      for (d3 <- d1 + d2 + 1 until 5000) {
//        cntOk += cntPos(d1) * cntPos(d2) * cntNeg(d3)
//      }
    }
  }

  println(cntOk.toDouble / cntTot)
}


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("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private 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 = _

    @inline private[this] final 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._
}

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 = {
    val n, t = ni()
    val (s, d) = na2(n)
    def f(i: Int): Long = {
      if (s(i) >= t) s(i)
      else {
        val c = ((t - s(i)) + d(i) - 1) / d(i)
        c.toLong * d(i) + s(i)
      }
    }
    debug((0 until n).map(f).mkString(" "))
    val ans = (0 until n).map(f).zipWithIndex.minBy(_._1)._2 + 1
    out.println(ans)
  }
}

import scala.io.StdIn

object Codeforces1153A {

  def findRoute(n: Int, t: Int, routes: Seq[Route]): Int = {
    val routeMeetingTimes = routes.map(route => {
      val meetingTime = getFirstMeetingTime(t, route)
      RouteMeetingTime(route, meetingTime)
    })

    routeMeetingTimes.minBy(routeMeetingTime => routeMeetingTime.meetingTime).route.i
  }

  def getFirstMeetingTime(t: Int, route: Route): Long = {
    var x = math.ceil(1.0 * (t - route.s) / route.d).toLong
    x = math.max(x - 10, 0)
    while (true) {
      if (t <= route.s + route.d * x) {
        return route.s + route.d * x
      }
      x += 1
    }
    0
  }

  def main(args: Array[String]): Unit = {
    val Array(n, t) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val routes = (1 to n).map(i => {
      val Array(s, d) = StdIn.readLine().trim.split(" ").map(_.toInt)
      Route(i, s, d)
    })

    val routeIndex = findRoute(n, t, routes)
    println(routeIndex)
  }

  case class Route(i: Int, s: Int, d: Int) {}

  case class RouteMeetingTime(route: Route, meetingTime: Long) {}

}

object Solution {

  case class Bus(start: Int, interval: Int)

  def main(args: Array[String]): Unit = {
    val in: Iterator[String] = io.Source.stdin.getLines()
    val Array(n, t) = in.next().split(" ").map(_.toInt)

    val routes = (1 to n).map { i => in.next().split(" ").map(_.toInt)}.map { a =>  Bus(a(0), a(1)) }

    var index = 0
    var minTime = Int.MaxValue

    routes.zipWithIndex.foreach { case (b, i) =>
      var arrival = b.start
      while(arrival < t) {
        arrival += b.interval
      }
      if (arrival < minTime) {
        minTime = arrival
        index = i
      }
    }
    println(index + 1)
  }

}

import scala.io.StdIn

object Codeforces1153A {

  def findRoute(n: Int, t: Int, routes: Seq[Route]): Int = {
    val routeMeetingTimes = routes.map(route => {
      val meetingTime = getFirstMeetingTime(t, route)
      RouteMeetingTime(route, meetingTime)
    })

    routeMeetingTimes.minBy(routeMeetingTime => routeMeetingTime.meetingTime).route.i
  }

  def getFirstMeetingTime(t: Int, route: Route): Long = {
    val x = math.ceil(1.0 * (t - route.s) / route.d).toLong
    route.s + route.d * x
  }

  def main(args: Array[String]): Unit = {
    val Array(n, t) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val routes = (1 to n).map(i => {
      val Array(s, d) = StdIn.readLine().trim.split(" ").map(_.toInt)
      Route(i, s, d)
    })

    val routeIndex = findRoute(n, t, routes)
    println(routeIndex)
  }

  case class Route(i: Int, s: Int, d: Int) {}

  case class RouteMeetingTime(route: Route, meetingTime: Long) {}

}


object cf1516a {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val ints = readInts()
			val n = ints(0)
			var k = ints(1)

			val nums = readInts()
			var i = 0
			while ( (i < nums.size - 1) && (k > 0) ) {
				if (nums(i) <= k) {
					nums(nums.size-1) += nums(i)
					k -= nums(i)
					nums(i) = 0
				} else {
					nums(nums.size-1) += k
					nums(i) -= k
					k = 0
				}
				i += 1
			}
			println(nums.mkString(" "))
    }
  }
}

object S_1516A extends App {
  import scala.io.StdIn.{readInt, readLine}
  val nInputs = readInt()
  for (_ <- 1 to nInputs) solveInput()

  def solveInput(): Unit = {
    val Array(_, k) = readLine().split(" ").map(_.toInt)
    val arr = readLine().split(" ").map(_.toInt)
    val res = solve(arr, k)
    println(res.mkString(" "))
  }

  def solve(arr: Array[Int], k: Int): Array[Int] = {
    @scala.annotation.tailrec
    def go(i: Int, k: Int, a: Int): Array[Int] = {
      if (k <= 0 || i >= arr.length - 1) { arr(arr.length - 1) += a; arr }
      else {
        val d = arr(i) min k
        arr(i) -= d
        go(i + 1, k - d, a + d)
      }
    }
    go(0, k, 0)
  }
}


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("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private 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 = _

    @inline private[this] final 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._
}

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 s = ns()
      val ans = if (s.endsWith("po")) {
        "FILIPINO"
      } else if (s.endsWith("mnida")) {
        "KOREAN"
      } else {
        "JAPANESE"
      }
      out.println(ans)
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn

object Codeforces1281A extends App {
  var t = StdIn.readLine().toInt
  while (t > 0) {
    val word = StdIn.readLine()
    if (word.endsWith("po"))
      println("FILIPINO")
    else if (word.endsWith("mnida"))
      println("KOREAN")
    else
      println("JAPANESE")
    t -= 1
  }

}

import scala.io.StdIn

object CF1281A {

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

    val n = StdIn.readLine().toInt
    (1 to n).map { _ =>
      val s = StdIn.readLine()
      if (s.endsWith("po")) {
        println("FILIPINO")
      }
      if (s.endsWith("desu") || s.endsWith("masu")) {
        println("JAPANESE")
      }
      if (s.endsWith("mnida")) {
        println("KOREAN")
      }
    }
  }

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

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

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

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

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

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

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

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

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

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

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

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


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

  private def prefix(i: Int): Long = (1L << (i + 1)) - 2L

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()

    val b = (1L << n) + prefix(n / 2 - 1)
    val a = prefix(n - 1) - prefix(n / 2 - 1)

    val ans = b - a

    println(ans)
  }
}

import scala.io.StdIn.readLine

object A {
  def solution(n: Int): Int =
    (2 << (n / 2)) - 2

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val n = readLine.toInt
      println(solution(n))
    }
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val numCases = in.nextInt()
    (1 to numCases).foreach{ _ =>
      val n = in.nextInt()
      val m = n/2
      val left: Long = ((1L << (m))-1L)<<(m)
      val right: Long = ((1L <<(n+1)) -1L)-left-1
      out.println((left-right).abs)
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val numCases = in.nextInt()
    (1 to numCases).foreach{ _ =>
      val n = in.nextInt()
      var left: Long = 0L
      var right: Long = 0L
      (1 to n by 2).foreach{ i =>
        val a = 1L << i
        val b = 1L << (i+1)

        if(left > right){
          left += a
          right += b
        }else{
          left += b
          right += a
        }
      }
      out.println((left-right).abs)
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


import scala.util.Sorting
object Proba {
def main(args: Array[String]) {
   val read = new java.util.StringTokenizer(readLine)
   val n=read.nextToken().toInt
   var x=read.nextToken().toLong
   val reads = new java.util.StringTokenizer(readLine)
   val a = new Array[Int](n + 1)
   for(i <- 1 to n)
     a(i) = reads.nextToken().toInt
     Sorting.quickSort(a);
   var sum:Long=0;
     for(i <- 1 to n){
         sum+=a(i)*x
         if(x>1)
           x-=1;
     }
     println(sum);
}
}

//package template

object Template {
	def main(args: Array[String]) {
		var Array(n, x) = readLine.split(" ").map(_.toLong)
		var input = readLine.split(' ').map(_.toLong).sorted
		var t = 0L
		var current_x = x
		for(i <- input){
			t += current_x*i;
			if(current_x > 1) current_x -= 1
		}
		print(t)
	}
}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    var Array(n,x) = StdIn.readLine().split(" ").map(_.toLong)
    print(StdIn.readLine()
      .split(" ")
      .map(_.toLong)
      .sorted
      .foldLeft( 0L ) { case (r, c) =>
        var ret = r + c * x
        x = math.max(1L, x - 1L)
        ret

      })

  }

}

import scala.util.Sorting._

object Devu {
  def main(args: Array[String]) {
	  val Array(n, m) = readLine().split(" ").map(_.toLong)
	  val d = readLine().split(" ").map(_.toLong)
	  quickSort(d)
	  var x = m
	  def f(a: Long) = {
		  val t = x
		  x = if (x - 1 < 1) 1 else x - 1
		  a * t
	  }
	  println(d.map(f).reduceLeft(_ + _))
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/** Created by azat (mail@azat.me) on 31/01/15 */
object Main {

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    var input = ArrayBuffer[Int]()
    while (scanner.hasNext) input += scanner.nextInt

    val n = input(0)
    val x: Long = input(1)
    val cs = input.drop(2).sorted
    val xAndSum = cs.foldLeft((x, 0l))((xAndSum, c) => (Math.max(xAndSum._1 - 1, 1), c * xAndSum._1 + xAndSum._2))

    println(xAndSum._2)
  }
}

import java.util.StringTokenizer

object _439B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val x = next.toInt
  val a = (1 to n).map(i => next.toLong).sorted.toArray

  def doit(i: Int, cost: Int, acc: Long): Long = {
    if (i == n) acc
    else doit(i + 1, 1 max (cost - 1), acc + cost * a(i))
  }

  println(doit(0, x, 0))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, x) = in.next().split(" ").map(_.toInt)
  println(in.next().split(" ").map(_.toInt).sorted.foldLeft((0l, x.toLong)) {
    case ((acc, 1), el) => (el + acc, 1)
    case ((acc, time), el) => (acc + el * time, time - 1)
  }._1)

}

object B439 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, x) = readInts(2)
    val c = readLongs(n).sorted
    var res = 0L
    for(i <- 0 until n) {
      res += c(i)*x
      if(x >= 2)
        x -=1
    }
    println(res)
  }

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

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

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

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

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

}

import scala.util.Sorting._

object Main {
  def main(args: Array[String]) {
	  val Array(n, m) = readLine().split(" ").map(_.toInt)
	  val d = readLine().split(" ").map(_.toInt)
	  quickSort(d)
	  var x = m
	  def f(a: Int) = {
		  val t = x
		  x = if (x - 1 < 1) 1 else x - 1
		  a * t
	  }
	  println(d.map(f).reduceLeft(_ + _))
  }
}

import scala.util.Sorting._

object Main {
  def main(args: Array[String]) {
	  val Array(n, m) = readLine().split(" ").map(_.toInt)
	  val d = readLine().split(" ").map(_.toInt)
	  quickSort(d)
	  var x = m
	  def f(a: Int) = {
		  val t = x
		  x = if (x - 1 < 1) 1 else x - 1
		  a * t
	  }
	  println(d.map(f).reduceLeft((a: Int, b: Int) => a + b))
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/** Created by azat (mail@azat.me) on 31/01/15 */
object Main {

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    var input = ArrayBuffer[Int]()
    while (scanner.hasNext) input += scanner.nextInt

    val n = input(0)
    val x = input(1)
    val cs = input.drop(2).sorted
    val xAndSum = cs.foldLeft((x, 0))((xAndSum, c) => (Math.max(xAndSum._1 - 1, 1), c * xAndSum._1 + xAndSum._2))

    println(xAndSum._2)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, x) = in.next().split(" ").map(_.toInt)
  println(in.next().split(" ").map(_.toInt).sorted.foldLeft((0l, x)) {
    case ((acc, 1), el) => (el + acc, 1)
    case ((acc, time), el) => (el * time + acc, time - 1)
  }._1)

}

//package template

object Template {
	def main(args: Array[String]) {
		var Array(n, x) = readLine.split(" ").map(_.toInt)
		var input = readLine.split(' ').map(_.toInt).sorted
		var t = 0L
		var current_x = x
		for(i <- input){
			t += current_x*i;
			if(current_x > 1) current_x -= 1
		}
		print(t)
	}
}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    var Array(n,x) = StdIn.readLine().split(" ").map(_.toInt)
    print(StdIn.readLine()
      .split(" ")
      .map(_.toInt)
      .sorted
      .foldLeft( 0 ) { case (r, c) =>
        var ret = r + c * x
        x = math.max(1, x - 1)
        ret

      })

  }

}


object C extends App {
  import java.{util => ju}

  val in = new ju.Scanner(System.in)
  (1 to in.nextInt()).foreach { _ =>
    val n = in.nextLong()

    def accumulateDifferences(bitIndex: Int = 0, shiftedNum: Long = 1, acc: Long = 0): Long = {
      val contribution = n / shiftedNum
      if (contribution > 0) {
        accumulateDifferences(bitIndex + 1, shiftedNum << 1, acc + contribution)
      } else acc
    }

    println(accumulateDifferences())
  }
}

object C extends App {

  private def count(n: Long): Long = {

    @scala.annotation.tailrec
    def go(n: Long, c: Long): Long =
      if (n == 0L) c
      else {
        val k = (1 to 63).view.collectFirst { case i if n < (1L << i) => i }.getOrElse(0) - 1
        go(n & ~(1L << k), c - 1L + (1L << (k + 1)))
      }

    go(n, 0L)
  }

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n   = scala.io.StdIn.readLong()
    val ans = count(n)

    println(ans)
  }
}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val n = readLine().toLong
      println(findK(n, 1, 2, 0))
    }
    //          println(minNum(List[Boolean](false, false, true)))
//    findK(1, 1, 2, 0)
  }

  def findK(n: Long, i: Long, d: Long, acc: Long): Long = {
    if (n >= d / 2) findK(n, i + 1, 2 * d, acc + (((n - d / 2) / d) + 1) * i)
    else acc
  }

  def calcCost(tree: Array[List[Int]], nodes: Array[List[Int]]): Long = {
    def helper(visited: Array[Boolean], ind: Int, min: Int): (Int, Int, Long) = {
      val neighs = tree(ind).filter(n => !visited(n))
      neighs.foreach(visited(_) = true)
      val ourCost = nodes(ind).head
      val newMin = Math.min(min, ourCost)

      val costs = neighs.map(n => {
        helper(visited, n, newMin)
      }).reduce((one, two) => (one._1 + two._1, one._2 + two._2, one._3 + two._3))

      if (min <= ourCost) costs else {
        val posExchanges = Math.min(costs._1, costs._2)
        (costs._1 - posExchanges, costs._2 - posExchanges, costs._3 + posExchanges * ourCost)
      }
    }

    val visitedArr = Array.ofDim[Boolean](nodes.length + 1)
    visitedArr(1) = true
    helper(visitedArr, 1, Int.MaxValue)._3
  }

  def constructTree(nodes: Array[List[Int]], edges: List[List[Int]]): Array[List[Int]] = {
    val edgesNice = Array.ofDim[List[Int]](nodes.length + 1)
    for (i <- edgesNice.indices)
      edgesNice(i) = List[Int]()

    edges.foreach(edge => {
      edgesNice(edge.head) = edge.last :: edgesNice(edge.head)
      edgesNice(edge.last) = edge.head :: edgesNice(edge.last)
    })

    edgesNice.map(_.toList)
  }

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

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

  def printArray[T](arr: Array[T]) {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

object C extends App {

  private def count(n: Long): Long = {

    @scala.annotation.tailrec
    def go(n: Long, c: Long): Long =
      if (n == 0L) c
      else {
        val k = (1 to 64).find(i => n < (1L << i)).getOrElse(0) - 1
        go(n & ~(1L << k), c - 1L + (1L << (k + 1)))
      }

    go(n, 0L)
  }

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n   = scala.io.StdIn.readLong()
    val ans = count(n)

    println(ans)
  }
}

object C extends App {

  private def count(n: Long): Long = {

    @scala.annotation.tailrec
    def go(n: Long, c: Long): Long =
      if (n == 0L) c
      else {
        val k = (1 to 63).collectFirst { case i if n < (1L << i) => i }.getOrElse(0) - 1
        go(n & ~(1L << k), c - 1L + (1L << (k + 1)))
      }

    go(n, 0L)
  }

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n   = scala.io.StdIn.readLong()
    val ans = count(n)

    println(ans)
  }
}

object C extends App {

  private def powof2(n: Long): Int =
    (1 to 64).find(i => n < (1L << i)).getOrElse(0) - 1

  private def count(n: Long): Long = {

    @scala.annotation.tailrec
    def go(n: Long, c: Long): Long =
      if (n == 0L) c
      else {
        val k  = powof2(n)
        val k2 = (math.log10(n) / math.log10(2)).toInt
        val m  = n & ~(1L << k)

        go(n & ~(1L << k), c - 1L + (1L << (k + 1)))
      }

    go(n, 0L)
  }

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n   = scala.io.StdIn.readLong()
    val ans = count(n)

    println(ans)
  }
}


object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    readLine()
    val Array(k, n, m) = readLine().split(" ").map(_.toInt)
    val an             = readLine().split(" ").map(_.toInt)
    val bm             = readLine().split(" ").map(_.toInt)

    @annotation.tailrec
    def go(i: Int, j: Int, l: Int, ops: List[Int]): Option[List[Int]] =
      if (i == n && j == m) Some(ops)
      else if (i != n && an(i) == 0) go(i + 1, j, l + 1, 0 :: ops)
      else if (j != m && bm(j) == 0) go(i, j + 1, l + 1, 0 :: ops)
      else if (i != n && j != m && an(i) <= bm(j) && an(i) <= l) go(i + 1, j, l, an(i) :: ops)
      else if (i != n && j != m && bm(j) <= an(i) && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)
      else if (i == n && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)
      else if (j == m && an(i) <= l) go(i + 1, j, l, an(i) :: ops)
      else None

    go(0, 0, k, List.empty[Int]) match {
      case Some(ops) => println(ops.reverse.mkString(" "))
      case _         => println(-1)
    }
  }
}

object C extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    readLine()
    val Array(k, n, m) = readLine().split(" ").map(_.toInt)
    val an             = readLine().split(" ").map(_.toInt)
    val bm             = readLine().split(" ").map(_.toInt)

    @annotation.tailrec
    def go(i: Int, j: Int, l: Int, ops: List[Int]): Option[List[Int]] =
      if (i == n && j == m) Some(ops)
      else if (i != n && an(i) == 0) go(i + 1, j, l + 1, 0 :: ops)
      else if (j != m && bm(j) == 0) go(i, j + 1, l + 1, 0 :: ops)
      else if (i != n && an(i) <= l) go(i + 1, j, l, an(i) :: ops)
      else if (j != m && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)
      else None

    go(0, 0, k, List.empty[Int]) match {
      case Some(ops) => println(ops.reverse.mkString(" "))
      case _         => println(-1)
    }
  }
}


object CFEDU47A extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    val n = nextInt
    val m = nextInt
    val games = (new Array[Int](n)).map(_ => nextInt)
    val bills = (new Array[Int](m)).map(_ => nextInt)

    def buy (games: Array[Int], bills: Array[Int], bought: Int): (Array[Int], Array[Int], Int) = {
      if (games.isEmpty || bills.isEmpty)
        return (games, bills, bought)
      if (games.head <= bills.head)
        return buy(games.tail, bills.tail, bought + 1)
      else
        return buy(games.tail, bills, bought)
    }

    out.println(buy(games, bills, 0)._3)
  }

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

import scala.io._

object A3 {

  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().take(3).toArray.map(_.split(' ').map(_.toInt))
    var j =0
    var count = 0
    for (i <- lines(2).indices) {
      while (j<lines(1).length && lines(1)(j) > lines(2)(i)) j+=1
      if (j<lines(1).length) {count+=1; j+=1}
    }
    println(count)
  }
}


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

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

  val Array(n, _) = readInts
  val a = readInts
  val pq1 = mutable.PriorityQueue(a: _*)
  val pq2 = mutable.PriorityQueue(a: _*)(Ordering.Int.reverse)
  val pq = Array(pq1, pq2)
  def ans = pq.map { q =>
    (for(_ <- 1 to n) yield {
      val x = q.dequeue()
      if(x > 1)
        q.enqueue(x - 1)
      x
    }).sum
  }.mkString(" ")

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val queue = new scala.collection.mutable.PriorityQueue[Int]()
  queue.enqueue(data:_*)
  val max = (1 to n).map{ _ =>
    val res = queue.dequeue()
    queue.enqueue(res - 1)
    res
  }.sum
  val queueMin = new scala.collection.mutable.PriorityQueue[Int]()
  queueMin.enqueue(data.map(-_):_*)
  val min = (1 to n).map{ _ =>
    val res = queueMin.dequeue()
    if (res != -1)
      queueMin.enqueue(res + 1)
    res
  }.sum
  println(max + " " + -min)
}

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

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

  def solve(): Unit = {
    val N, M = sc.nextInt
    val Planes = List.fill(M)(sc.nextInt)

    @tailrec
    def loop(acc: Int, n : Int, planes: PriorityQueue[Int]): Int = {
      if (n == 0) acc
      else {
        val x = planes.dequeue
        val y = x - 1
        if (y > 0) {
          planes.enqueue(x - 1)
        }
        loop(acc + x, n - 1, planes)
      }
    }

    val pqMax = new PriorityQueue[Int]() ++ Planes
    val max = loop(0, N, pqMax)
    val pqMin = new PriorityQueue[Int]()(Ordering.Int.reverse) ++ Planes
    val min = loop(0, N, pqMin)

    out.println(max + " " + min)
 }

  solve
  out.close
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 25 Jun 2016
 */
object B218 extends App {

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val minPQ: mutable.PriorityQueue[Int] = mutable.PriorityQueue.empty(Ordering.fromLessThan[Int](_ > _))
    val maxPQ: mutable.PriorityQueue[Int] = mutable.PriorityQueue.empty(Ordering.fromLessThan[Int](_ < _))
    a.foreach(minPQ += _)
    a.foreach(maxPQ += _)

    var min = 0
    var max = 0

    for (i <- 0 until n) {
      val mi = minPQ.dequeue()
      min += mi
      if (mi - 1 > 0) {
        minPQ += (mi - 1)
      }

      val ma = maxPQ.dequeue()
      max += ma
      if (ma - 1 > 0) {
        maxPQ += (ma - 1)
      }
    }
    println(max + " " + min)
  }

  solve()

}

import collection.mutable._

object A extends App {
  val max = new PriorityQueue[Int]
  val min = new PriorityQueue[Int]()(new Ordering[Int] {
    def compare(x: Int, y: Int) = y.compare(x)
  })

  val Array(n, m) = readLine split ' ' map (_.toInt)
  val a = readLine split ' ' map (_.toInt)
  max.enqueue(a: _*)
  min.enqueue(a: _*)

  var ans0, ans1 = 0
  for (i <- 0 until n) {
    val x = max.dequeue
    ans0 += x
    if (x > 1) max.enqueue(x-1)
  }
  for (i <- 0 until n) {
    val x = min.dequeue
    ans1 += x
    if (x > 1) min.enqueue(x-1)
  }

  println("%d %d" format (ans0, ans1))
}

import scala.collection.mutable.PriorityQueue
object Main{
  def main(args: Array[String]): Unit = {
    val maxHeap = new PriorityQueue[Int]
    val minHeap = new PriorityQueue[Int]()(new Ordering[Int] {
      def compare(x: Int, y :Int) = y.compare(x)
    })
    var ans = 0
    val temp = readLine.split(' ') map (_.toInt)
    val (n, m) = (temp(0), temp(1))

    val emptySeats = readLine.split(' ') map (_.toInt)
    maxHeap.enqueue(emptySeats:_*)
    minHeap.enqueue(emptySeats:_*)

    for (i <- 0 until n) {
      var x = maxHeap.dequeue
      ans += x
      x -= 1
      if (x > 0) maxHeap.enqueue(x)
    }
    print(ans + " ")

    ans = 0
    for (i <- 0 until n) {
      var x = minHeap.dequeue
      ans += x
      x -= 1
      if (x > 0) minHeap.enqueue(x)
    }
    println(ans)
  }
}

object Main {
  def min(n: Int, a: TraversableOnce[Int]) = {
    var ax = scala.collection.mutable.Seq[Int]() ++ a
    (1 to n).foldLeft(0) { (sum, _) =>
      val e = ax.head
      ax(0) -= 1
      if(ax(0) == 0) ax = ax.drop(1)
      sum + e
    }
  }

  def max(n: Int, a: TraversableOnce[Int]) = {
    var ax = scala.collection.mutable.Seq[Int]() ++ a
    (1 to n).foldLeft(0) { (sum, _) =>
      val e = ax.last
      ax(ax.size - 1) -= 1
      ax = ax.sorted
      sum + e
    }
  }

  def main(args: Array[String]) = {
    val nk = readLine() split(" ") map(_.toInt)
    val a = readLine() split(" ") map(_.toInt) sorted
    val mi = min(nk(0), a)
    val ma = max(nk(0), a)
    println(ma + " " + mi)
  }
}

import scala.collection.mutable.PriorityQueue
import java.util.Scanner
object Main {
  def main(args: Array[String]): Unit = {
    val queueDesc = new PriorityQueue[Int]()(Ordering[Int].reverse)
    val queueAsc = new PriorityQueue[Int]()
    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()
    val m = scanner.nextInt()
    for (i <- 1 to m) {
      val a = scanner.nextInt()
      queueAsc.enqueue(a)
      queueDesc.enqueue(a)
    }
    var maximum = 0
    var minimum = 0
    for (i <- 1 to n) {
      val priceMax = queueAsc.dequeue()
      maximum += priceMax
      if (priceMax > 1)
        queueAsc.enqueue(priceMax - 1)
      val priceMin = queueDesc.dequeue()
      minimum += priceMin
      if (priceMin  > 1)
        queueDesc.enqueue(priceMin -  1)
    }
    println(maximum.toString() + " " + minimum.toString())
  }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val (sum, l) = data.foldLeft((0l, k)) {
    case ((s, 0), el) => (s + el, 0)
    case ((s, left), el) if el <= 0 => (s - el, left - 1)
    case ((s, left), el) => (s + el, left)
  }
  if (l % 2 == 0)
    println(sum)
  else
    println(sum - 2 * data.map(Math.abs).min)
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0)
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    val add = if (rest == 1) 2 * a.map(_.abs).min else 0
    println(poss.sum - negs.take(k).sum  + negs.drop(k).sum - add)
  }
}

object B{
  def main(args: Array[String]){

    val (n,k)={
      val sp= readLine.split(" ")
      (sp(0).toInt,sp(1).toInt)
    }
    var a= readLine.split(" ").toList.map(_.toInt)

    val negalen=a.prefixLength(_<=0)
    if(negalen>=k){
      //先頭k個
      val (a1,a2)=a.splitAt(k)
      println(-(a1.sum)+a2.sum)
    }else{
      a=a.map(Math.abs(_))
      if((k-negalen)%2==0){
        //all +
        println(a.sum)
      }else{
        //min -> -min
        println(a.sum - 2* a.min)
      }
    }
  }
}

object Roma extends App {
  def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var result = seq.map {e =>
  		if (e < 0 && remainingSwaps > 0) {
  			remainingSwaps -= 1
  			-e
  		} else e
  	}

  	result = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0) {
  			result
  		} else {
  			val sorted = result.sorted
  			 (-sorted.head) :: sorted.tail
  		}
  	} else {
  		result
  	}

  	result.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object CF262B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i + 1
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      if (j == 0) {
        a(j) *= -1
      } else if (j == n || a(j - 1) < a(j)) {
        a(j - 1) *= -1
      } else {
        a(j) *= -1
      }
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object Roma {

  def main(args: Array[String]): Unit = {
    val Array(n: Int, k: Int) = readLine.split(' ').map(_.toInt)
    val aa: Seq[Int] = readLine.split(' ').map(_.toInt)

    val negCount = aa.count(_ < 0)
    val result = if (k > negCount) {
      if ((k - negCount) % 2 == 0) {
        aa.map(_.abs).sum
      }
      else {
        aa.map(_.abs).sum - 2*aa.map(_.abs).min
      }
    }
    else {
      val origSeq: Map[Int, Int] = aa.zipWithIndex.map(_.swap).toMap
      val negFlipped: Map[Int, Int] = aa.zipWithIndex
        .filter{ case (a: Int, i: Int) => a < 0 }
        .sortBy { case (a: Int, i: Int) => a }
        .take(k)
        .map { case (a: Int, i: Int) => (-1*a, i) }
        .map(_.swap)
        .toMap
      (origSeq ++ negFlipped).values.sum
    }

    println(result)
  }

}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0).reverse
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    val add = 2 * a.map(_.abs).min * rest
    println(poss.sum - negs.take(k).sum  + negs.drop(k).sum - add)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0)
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    println(poss.sum - negs.reverse.take(k).sum - (poss.min.min(-negs.max)) * rest)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0).reverse
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    val add = - 2 * a.map(_.abs).min * rest
    println(poss.sum - negs.take(k).sum  + negs.drop(k).sum - add)
  }
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = (seq.take(nSwaps).map(_ * -1) ::: seq.drop(nSwaps)).sum

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = (seq.take(nSwaps).map(math.abs) ::: seq.drop(nSwaps)).sum

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
  def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var response = seq.map { e =>
  		if (e < 0) {
  			remainingSwaps -= 1
  			e * -1
  		} else 	e
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
  def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var response = seq.map { e =>
  		if (e < 0) e * -1
  		else {
  			remainingSwaps = remainingSwaps - 1
  			e
  		}
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	println("Remaining swaps = " + remainingSwaps)

  	var response = seq.map { e =>
  		if (e < 0 && remainingSwaps > 0) {
  			println("It is negative: " + e)
  			remainingSwaps -= 1
  		println("Remaining swaps = " + remainingSwaps)
  			e * -1

  		} else 	e
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var response = seq.map { e =>
  		if (e < 0 && remainingSwaps > 0) {
  			remainingSwaps -= 1
  			e * -1

  		} else 	e
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object CF262B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    if (math.abs(a(0)) > math.abs(a(n - 1))) {
      a = a.reverse
    }

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i
      }
      i += 1
    }

    if ((k - kk) % 2 != 0) {
      j = if (j != 0 && j + 1 < n) j + 1 else j
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    if (math.abs(a(0)) > math.abs(a(n - 1))) {
      a = a.reverse
    }

    var kk = 0
    var i = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
      }
      i += 1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      j = if (j != 0 && j + 1 < n) j + 1 else j
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    if (math.abs(a(0)) > math.abs(a(n - 1))) {
      a = a.reverse
    }

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      j = if (j != 0 && j + 1 < n) j + 1 else j
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i + 1
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      if (j == 0) {
        a(j) *= -1
      } else if (j == n || a(j - 1) < a(j)) {
        a(j - 1) *= 1
      } else {
        a(j) *= 1
      }
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i + 1
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      j = if (j == 0) j else if (j < n) j else j - 1
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val time = in.next().split(' ').map(_.toInt)

  def hasSolution(endIndex: Int): Boolean = {
    val cache = Array.ofDim[Boolean](m)
    var mr = 0
    val t = (endIndex to 0 by -1).foldLeft(0) {
      case (overuse, i) if line(i) == 0 || cache(line(i) - 1) => Math.max(overuse - 1, 0)
      case (overuse, i) =>
        cache(line(i) - 1) = true
        mr += 1
        overuse + time(line(i) - 1)
    }
    t <= 0 && m == mr
  }

  def binary(start: Int, end: Int): Option[Int] = {
    if (start >= end) {
      None
    }
    else if (end - start == 1)
      Some(end)
    else {
      val middle = start + Math.max(1, (end - start) / 2)
      if (hasSolution(middle))
        binary(start, middle)
      else
        binary(middle, end)
    }
  }

  if (!hasSolution(n - 1))
    println(-1)
  else {
    println(binary(0, n - 1).get + 1)
  }

}

import java.io._

import scala.io.Source
import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  // Declare type aliases for readability (but not type-safety)...
  type SubjectId = Int;
  type PrepTime = Int;
  type DayIndex = Int;

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line1 = lines.next()
    val strings = line1.split(" ")
    val n = strings(0).toInt
    val m = strings(1).toInt

    val line2 = lines.next()
    val d = line2.split(" ")
      .map(_.toInt)
      .map(di => if (di == 0) None else Some(di - 1))  // zero-base the d's

    val line3 = lines.next()
    val a = line3.split(" ").map(pt => pt.toInt)

    val soln = solve(n, m, d, a)
    soln match {
      case Some(days) => bw.write((days + 1).toString)  // Make d's one-based again
      case _ => bw.write("-1")
    }
    bw.newLine()
  }

  def solve(numDays: Int, numSubjects: Int, examByDay: Array[Option[SubjectId]], prepTimes: Array[PrepTime])
    : Option[DayIndex] = {

    // Get a sorted array of exam days for each subject:
    val maxPrepTimeOfAnyExam = prepTimes.max
    val examDaysBySubject = Array.fill(numSubjects)(ListBuffer[DayIndex]())
    for (dayIndex <- 0 until numDays) {
      val subjectOpt = examByDay(dayIndex)
      if (subjectOpt.isDefined) {
        val subjectId = subjectOpt.get
        if (dayIndex >= maxPrepTimeOfAnyExam || prepTimes(subjectId) <= dayIndex) {
          examDaysBySubject(subjectId).append(dayIndex)
        }
      }
    }

    def findDayIndexOfLastExamForSubjectOnOrBefore(subjectId: SubjectId, dayIndex: DayIndex): Option[Int] = {
      val examDays = examDaysBySubject(subjectId)

      @tailrec
      def binarySearch(lowerIx: Int, upperIx: Int): Int = {
        if (lowerIx == upperIx) lowerIx else {
          val midIx = (lowerIx + upperIx + 1) / 2
          val midVal = examDays(midIx)
          if ((midIx == upperIx) || (midVal == dayIndex))
            midVal
          else if (midVal > dayIndex) binarySearch(lowerIx, midIx)
          else binarySearch(midIx, upperIx)
        }
      }

      if (examDays.isEmpty) None else {
        val lowerVal = examDays(0)
        if (lowerVal > dayIndex) None else {
          val upperIndex = examDays.length - 1
          val upperVal = examDays(upperIndex)
          if (upperVal <= dayIndex) Some(upperVal)
          else Some(binarySearch(0, upperIndex))
        }
      }
    }

    def isSolution(dayIndex: DayIndex): Boolean = {
      val subjectExamDays = (0 until numSubjects).map { subjectId =>
        subjectId -> findDayIndexOfLastExamForSubjectOnOrBefore(subjectId, dayIndex)
      }
      if (!subjectExamDays.forall(_._2.isDefined)) false else {
        val sortedSubjectExamDays = subjectExamDays.map(pair => (pair._1, pair._2.get)).sortBy(_._2)

        def loop(sortIndex: Int, prevDayIndex: Int): Boolean = {
          val sed = sortedSubjectExamDays(sortIndex)
          val nextDayIndex = prevDayIndex + prepTimes(sed._1) + 1
          if (nextDayIndex > sed._2) false else {
            val nextSortIndex = sortIndex + 1
            if (nextSortIndex == numSubjects) true else loop(nextSortIndex, nextDayIndex)
          }
        }

        loop(0, -1)
      }
    }

    // Do a binary search to find the best solution
    @tailrec
    def search(lowerBound: DayIndex, upperBound: DayIndex): DayIndex = {
      if (lowerBound == upperBound) lowerBound else {
        val middleDay: DayIndex = (lowerBound + upperBound + 1) / 2
        if (isSolution(middleDay)) search(lowerBound, middleDay)
        else if (middleDay == upperBound) upperBound
        else search(middleDay, upperBound)
      }
    }

    if (examDaysBySubject.exists(_.length == 0)) None else {
      val ub: DayIndex = numDays - 1
      if (!isSolution(ub)) None
      else {
        val lowerBoundByTotalPrepAndExamTime = prepTimes.sum + numSubjects - 1
        val lowerBoundByMaxOfFirstExamDays = examDaysBySubject.map(_(0)).max
        val lowerBoundIndex = lowerBoundByMaxOfFirstExamDays max lowerBoundByTotalPrepAndExamTime
        val lb: DayIndex = lowerBoundIndex
        if (isSolution(lb)) Some(lb) else {
          if (lowerBoundIndex >= numDays) None
          else if (lowerBoundIndex == numDays - 1) Some(lb)
          else Some(search(lb, ub))
        }
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val time = in.next().split(' ').map(_.toInt)

  def hasSolution(endIndex: Int): Boolean = {
    val cache = Array.ofDim[Boolean](m)
    val t = (endIndex to 0 by -1).foldLeft(0) {
      case (overuse, i) if line(i) == 0 || cache(line(i) - 1) => Math.max(overuse - 1, 0)
      case (overuse, i) =>
        cache(line(i) - 1) = true
        overuse + time(line(i) - 1)

    }
    t <= 0
  }

  def binary(start: Int, end: Int): Option[Int] = {
    if (end - start == 1)
      Some(end)
    else if (start >= end) {
      None
    }
    else {
      val middle = start + Math.max(1, (end - start) / 2)
      if (hasSolution(middle))
        binary(start, middle)
      else
        binary(middle, end)
    }
  }

  if (!hasSolution(n - 1))
    println(-1)
  else {
    println(binary(0, n - 1).get + 1)
  }

}


object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val sum    = an.foldLeft(0L)(_ + _)
    val (c, r) = (sum / n, sum % n)

    val ans = r * (n - r)

    println(ans)
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val c = an.foldLeft(0L)(_ + _) % n

    val ans = c * (n - c)

    println(ans)
  }
}


object B {
	def main(args: Array[String]) {
		val rawS = Console.readLine

		val sum = rawS.toSeq.sorted.groupBy(c => c).mapValues(_.length % 2).values.sum

		println(if(sum == 0) "First" else if(sum % 2 == 0) "Second" else "First")
	}
}

object B {
  def main(args: Array[String]) {
    var s = readLine()
    var r=List.range('a', 'z'+1) map(x => s count(x==)) filter (_%2==1) size;
    println(if (r == 0 || r%2==1) "First" else "Second")
  }
}

object Main {
  def main(args: Array[String]) = {
    val a = readLine()
    val map = scala.collection.mutable.Map[Char, Int]()
    a.foreach(c => map(c) = map.getOrElse(c, 0) + 1)
    val count = map.values.count(_ % 2 == 1)
    if (count == 0 || count % 2 == 1) println("First")
    else println("Second")
  }
}

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

object P276B extends App {
  def solve(s: String): Boolean = {
    val x = s.toCharArray.groupBy(identity[Char]).map(_._2.length % 2).filter(_ == 1).size
    (x < 2) || (x % 2 == 1)
  }

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.next().map(_ - 'a').foldLeft(0) {
    case(a, el) => a ^ (1 << el)
  }.toBinaryString.count(_ == '1')
  if (res < 2 || res % 2 == 1)
    println("First")
  else
    println("Second")
}

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

object P276B extends App {
  def solve(s: String): Boolean = false

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")

  out.flush
  out.close
}

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

object P276B extends App {
  def solve(s: String): Boolean = false

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

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

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray
      .groupBy(identity[Char])
      .map(_._2.length)
      .filter(_ % 2 == 0)
      .size % 2 == 1

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

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

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray
      .groupBy(identity[Char])
      .map(_._2.length % 2)
      .filter(_ == 1)
      .size % 2 == 0

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

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

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray.groupBy(identity[Char]).size % 2 == 0

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

object Main {
  def main(args: Array[String]) = {
    val a = readLine()
    val map = scala.collection.mutable.Map[Char, Int]()
    a.foreach(c => map(c) = map.getOrElse(c, 0) + 1)
    if (map.values.count(_ % 2 == 1) % 2 == 1) println("First")
    else println("Second")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.next().map(_ - 'a').foldLeft(0) {
    case(a, el) => a ^ (1 << el)
  }.toBinaryString.count(_ == '1') % 2 == 0
  if (!res)
    println("First")
  else
    println("Second")
}

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

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray
      .groupBy(identity[Char])
      .map(_._2.length % 2)
      .filter(_ == 1)
      .size % 2 == 1

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}