Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases:   They are equal.  If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct:   a1 is equivalent to b1, and a2 is equivalent to b2  a1 is equivalent to b2, and a2 is equivalent to b1  As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.Gerald has already completed this home task. Now it's your turn!

The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.

Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.

NoteIn the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".

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

}

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


Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?

The first line of input contains a single integer n (2 ≤ n ≤ 2000) — the number of balls in the jar. The second line contains n integers ai (1 ≤ ai ≤ 5000) — the number written on the ith ball. It is guaranteed that no two balls have the same number.

Print a single real value — the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.In the second case, each game could've had three outcomes — 10 - 2, 10 - 1, or 2 - 1. Jerry has a higher total if and only if Andrew won 2 - 1 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability .

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

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


It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.Serval will go to the bus station at time $$$t$$$, and there are $$$n$$$ bus routes which stop at this station. For the $$$i$$$-th bus route, the first bus arrives at time $$$s_i$$$ minutes, and each bus of this route comes $$$d_i$$$ minutes later than the previous one.As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.

The first line contains two space-separated integers $$$n$$$ and $$$t$$$ ($$$1\leq n\leq 100$$$, $$$1\leq t\leq 10^5$$$) — the number of bus routes and the time Serval goes to the station.  Each of the next $$$n$$$ lines contains two space-separated integers $$$s_i$$$ and $$$d_i$$$ ($$$1\leq s_i,d_i\leq 10^5$$$) — the time when the first bus of this route arrives and the interval between two buses of this route.

Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.

NoteIn the first example, the first bus of the first route arrives at time $$$6$$$, and the first bus of the second route arrives at time $$$9$$$, so the first route is the answer.In the second example, a bus of the third route arrives at time $$$5$$$, so it is the answer.In the third example, buses of the first route come at times $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, and so fourth, buses of the second route come at times $$$2$$$, $$$5$$$, $$$8$$$, and so fourth and buses of the third route come at times $$$2$$$, $$$6$$$, $$$10$$$, and so on, so $$$1$$$ and $$$2$$$ are both acceptable answers while $$$3$$$ is not.

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

}


Given an array $$$a$$$ of length $$$n$$$, you can do at most $$$k$$$ operations of the following type on it:  choose $$$2$$$ different elements in the array, add $$$1$$$ to the first, and subtract $$$1$$$ from the second. However, all the elements of $$$a$$$ have to remain non-negative after this operation. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 20$$$) – the number of test cases you need to solve. The first line of each test case contains $$$2$$$ integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 100$$$, $$$1 \le k \le 10000$$$) — the number of elements in the array and the maximum number of operations you can make. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i \le 100$$$) — the elements of the array $$$a$$$.

For each test case, print the lexicographically smallest array you can obtain after at most $$$k$$$ operations.

NoteIn the second test case, we start by subtracting $$$1$$$ from the first element and adding $$$1$$$ to the second. Then, we can't get any lexicographically smaller arrays, because we can't make any of the elements negative.

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


We just discovered a new data structure in our research group: a suffix three!It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.It's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms.Let us tell you how it works.  If a sentence ends with "po" the language is Filipino.  If a sentence ends with "desu" or "masu" the language is Japanese.  If a sentence ends with "mnida" the language is Korean. Given this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean.Oh, did I say three suffixes? I meant four.

The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 30$$$) denoting the number of test cases. The next lines contain descriptions of the test cases.  Each test case consists of a single line containing a single string denoting the sentence. Spaces are represented as underscores (the symbol "_") for ease of reading. The sentence has at least $$$1$$$ and at most $$$1000$$$ characters, and consists only of lowercase English letters and underscores. The sentence has no leading or trailing underscores and no two consecutive underscores. It is guaranteed that the sentence ends with one of the four suffixes mentioned above.

For each test case, print a single line containing either "FILIPINO", "JAPANESE", or "KOREAN" (all in uppercase, without quotes), depending on the detected language.

8
kamusta_po
genki_desu
ohayou_gozaimasu
annyeong_hashimnida
hajime_no_ippo
bensamu_no_sentou_houhou_ga_okama_kenpo
ang_halaman_doon_ay_sarisari_singkamasu
si_roy_mustang_ay_namamasu

FILIPINO
JAPANESE
JAPANESE
KOREAN
FILIPINO
FILIPINO
JAPANESE
JAPANESE

NoteThe first sentence ends with "po", so it is written in Filipino.The second and third sentences end with "desu" and "masu", so they are written in Japanese.The fourth sentence ends with "mnida", so it is written in Korean.

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

}

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


Phoenix has $$$n$$$ coins with weights $$$2^1, 2^2, \dots, 2^n$$$. He knows that $$$n$$$ is even.He wants to split the coins into two piles such that each pile has exactly $$$\frac{n}{2}$$$ coins and the difference of weights between the two piles is minimized. Formally, let $$$a$$$ denote the sum of weights in the first pile, and $$$b$$$ denote the sum of weights in the second pile. Help Phoenix minimize $$$|a-b|$$$, the absolute value of $$$a-b$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 30$$$; $$$n$$$ is even) — the number of coins that Phoenix has.

For each test case, output one integer — the minimum possible difference of weights between the two piles.

NoteIn the first test case, Phoenix has two coins with weights $$$2$$$ and $$$4$$$. No matter how he divides the coins, the difference will be $$$4-2=2$$$.In the second test case, Phoenix has four coins of weight $$$2$$$, $$$4$$$, $$$8$$$, and $$$16$$$. It is optimal for Phoenix to place coins with weights $$$2$$$ and $$$16$$$ in one pile, and coins with weights $$$4$$$ and $$$8$$$ in another pile. The difference is $$$(2+16)-(4+8)=6$$$.

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

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


One important contest will take place on the most famous programming platform (Topforces) very soon!The authors have a pool of $$$n$$$ problems and should choose at most three of them into this contest. The prettiness of the $$$i$$$-th problem is $$$a_i$$$. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be maximum possible).But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are $$$x, y, z$$$, then $$$x$$$ should be divisible by neither $$$y$$$, nor $$$z$$$, $$$y$$$ should be divisible by neither $$$x$$$, nor $$$z$$$ and $$$z$$$ should be divisible by neither $$$x$$$, nor $$$y$$$. If the prettinesses of chosen problems are $$$x$$$ and $$$y$$$ then neither $$$x$$$ should be divisible by $$$y$$$ nor $$$y$$$ should be divisible by $$$x$$$. Any contest composed from one problem is considered good.Your task is to find out the maximum possible total prettiness of the contest composed of at most three problems from the given pool.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the prettiness of the $$$i$$$-th problem. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print one integer — the maximum possible cumulative prettiness of the contest composed of at most three problems from the given pool of problems in the query.

import scala.util.Sorting

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = na(N)
      sort(A)

      // 1 + a > 1/2 + a かつ 1 + a > 1/2 + 1/3 なので
      // 必ず一番大きい値を含む
      def two: Option[Int] = _two(_ => true, N - 1)

      def _two(condition: Int => Boolean, last: Int): Option[Int] = {
        for {
          _ <- Option(Unit)
          fstIx = A.lastIndexWhere(condition, last)
          if fstIx != -1
          fst = A(fstIx)
          sndIx = A.lastIndexWhere(a => condition(a) && fst % a != 0, fstIx - 1)
          if sndIx != -1
          snd = A(sndIx)
          _ <- {debug(s"last:$last fst:$fst snd:$snd"); Option(Unit)}
        } yield fst + snd
      }

      def _three(condition: Int => Boolean): Option[Int] = {
        for {
          _ <- Option(Unit)
          fstIx = A.lastIndexWhere(condition)
          if fstIx != -1
          fst = A(fstIx)
          twoAndThree <- _two(a => condition(a) && fst % a != 0, fstIx - 1) // あとはtwoのときと同じ要領で
        } yield twoAndThree + fst
      }

      // 一番大きい値か２番めを含む
      // 1/2+1/3+1/5 > 1 + a + b がありえるので、１番目がない場合もある
      def withFst = _three(_ => true)
      def withoutFst = _three(_ != A.last)

      val ans = Seq(A.lastOption, two, withFst, withoutFst).flatten.max
      out.println(ans)
    }
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }
}

import scala.util.Sorting

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = na(N)
      sort(A)

      // 必ず一番大きい値を含む
      // 1 > 1/2 + 1/3 なので
      def two: Option[Int] = _two(_ => true, N - 1)

      def _two(condition: Int => Boolean, last: Int): Option[Int] = {
        for {
          _ <- Option(Unit)
          fstIx = A.lastIndexWhere(condition, last)
          if fstIx != -1
          fst = A(fstIx)
          sndIx = A.lastIndexWhere(a => condition(a) && fst % a != 0, fstIx)
          if sndIx != -1
          snd = A(sndIx)
        } yield fst + snd
      }

      def _three(condition: Int => Boolean): Option[Int] = {
        for {
          _ <- Option(Unit)
          fstIx = A.lastIndexWhere(condition)
          if fstIx != -1
          fst = A(fstIx)
          twoAndThree <- _two(a => condition(a) && fst % a != 0, fstIx) // あとはtwoのときと同じ要用で
        } yield twoAndThree + fst
      }

      // 一番大きい値か２番めを含む
      // 1/2+1/3+1/4 > 1 なので１番目がない場合もあるえる
      def three: Option[Int] = {
        def withFst = _three(_ => true)
        def withoutFst = _three(_ != A.last)

        withFst orElse withoutFst
      }

      val ans = Seq(A.lastOption, two, three).flatten.max
      out.println(ans)
    }
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }
}

import scala.util.Sorting

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = na(N)
      sort(A)

      // 必ず一番大きい値を含む
      // 1 > 1/2 + 1/3 なので
      def two: Option[Int] = _two(_ => true, N - 1)

      def _two(condition: Int => Boolean, last: Int): Option[Int] = {
        for {
          _ <- Option(Unit)
          fstIx = A.lastIndexWhere(condition, last)
          if fstIx != -1
          fst = A(fstIx)
          sndIx = A.lastIndexWhere(a => condition(a) && fst % a != 0, fstIx)
          if sndIx != -1
          snd = A(sndIx)
        } yield fst + snd
      }

      def _three(last: Int): Option[Int] = {
        for {
          _ <- Option(Unit)
          fstIx = A.lastIndexWhere(_ => true, last)
          if fstIx != -1
          fst = A(fstIx)
          _ <- {debug(s"_three($last) fst:$fst"); Option(Unit)}
          twoAndThree <- _two(fst % _ != 0, fstIx) // あとはtwoのときと同じ要用で
        } yield twoAndThree + fst
      }

      // 一番大きい値か２番めを含む
      // 1/2+1/3+1/4 > 1 なので１番目がない場合もあるえる
      def three: Option[Int] = {
        def withFst = _three(N - 1)
        def withoutFst = _three(N - 2)

        withFst orElse withoutFst
      }

      val ans = Seq(A.lastOption, two, three).flatten.max
      out.println(ans)
    }
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }
}


Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.Please be careful that answer might not fit in 32 bit data type.

The first line will contain two space separated integers n, x (1 ≤ n, x ≤ 105). The next line will contain n space separated integers: c1, c2, ..., cn (1 ≤ ci ≤ 105).

Output a single integer representing the answer to the problem.

NoteLook at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2 × 1 = 2 hours. Hence you will need to spend 12 + 2 = 14 hours.Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3 × 1 = 3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2 × 4 = 8 hours. Hence you will need to spend 11 hours.So overall, minimum of both the cases is 11 hours.Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours.

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

}

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

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

      })

  }

}


The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of $$$5 = 101_2$$$ and $$$14 = 1110_2$$$ equals to $$$3$$$, since $$$0101$$$ and $$$1110$$$ differ in $$$3$$$ positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from $$$0$$$ to $$$n$$$. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.

The input consists of multiple test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. The following $$$t$$$ lines contain a description of test cases. The first and only line in each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^{18})$$$.

Output $$$t$$$ lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to $$$0$$$, $$$1$$$, ..., $$$n - 1$$$, $$$n$$$.

NoteFor $$$n = 5$$$ we calculate unfairness of the following sequence (numbers from $$$0$$$ to $$$5$$$ written in binary with extra leading zeroes, so they all have the same length):   $$$000$$$  $$$001$$$  $$$010$$$  $$$011$$$  $$$100$$$  $$$101$$$ The differences are equal to $$$1$$$, $$$2$$$, $$$1$$$, $$$3$$$, $$$1$$$ respectively, so unfairness is equal to $$$1 + 2 + 1 + 3 + 1 = 8$$$.

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 {

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

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