In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val answer = Array.ofDim[Int](k)
  in.next().split(' ').map(_.toInt - 1).foreach {i => answer(i) += 1}
  var r = 0

  while (answer(k - 1) != n) {
    (k - 1 to 1 by - 1).foreach { i =>
      if (answer(i - 1) > 0) {
        answer(i) += 1
        answer(i - 1) -= 1
      }
    }
    r += 1
  }
  println(r)
}


Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$.

NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$.

import scala.io.StdIn

object SolutionC extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val n = StdIn.readInt()
    val array = StdIn.readLine().split(' ').map{_.toInt}
    var prev = array(0)
    var currentMax = prev
    var result = 0L
    for (idx <- 1 until n) {
      val next = array(idx)
      if (prev < 0) {
        if (next < 0) {
          currentMax = Math.max(currentMax, next)
        } else {
          result += currentMax
          currentMax = next
        }
      } else {
        if (next > 0) {
          currentMax = Math.max(currentMax, next)
        } else {
          result += currentMax
          currentMax = next
        }
      }
      prev = next
    }
    result += currentMax
    println(result)
  }
}

import java.util.Scanner

object C_1343 extends App {
  var scanner = new Scanner(System.in)
  val t = scanner.nextInt()

  (0 until t).foreach { _ =>
    val n = scanner.nextInt()

    val a0 = scanner.nextInt()
    var sign = a0 > 0
    var max = a0
    var sum = 0L

    var index = 1
    while (index < n) {
      val newA = scanner.nextInt()
      val newSign = newA > 0
      if (newSign != sign) {
        sign = newSign
        sum += max
        max = newA
      }
      else if (newA > max) {
        max = newA
      }

      index += 1
    }
    sum += max

    println(sum)
  }
}

import scala.collection.mutable

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val as = nextLongs(n)

    val resBuilder = new mutable.ArrayBuilder.ofLong
    var prev = 0L
    for (a <- as) {
      if (java.lang.Long.signum(a) != java.lang.Long.signum(prev)) {
        if (prev != 0) {
          resBuilder += prev
        }
        prev = a
      } else if (a > prev) {
        prev = a
      }
    }
    if (prev != 0) {
      resBuilder += prev
    }

    out.println(resBuilder.result().sum)
  }

  out.flush()

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


Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x > 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?

First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.

For each game output a maximum score that the second soldier can get.

object D{
  //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
    val t=nextInt
    val nmax=5000002

    val prime=Array.fill(nmax)(true)
    for(i<-2 until 2333){
      if(prime(i)){
        for(j<-i to (nmax-1)/i){
          prime(j*i)=false
        }
      }
    }

    for(i<-2 until nmax){
      if(prime(i)){
        var j=i
        while(j<nmax/i){
          j*=i
        prime(j)=true

      }}
    }

    val s=Array.fill(nmax)(0)
    for(i<-2 to nmax-1){
      if(prime(i)){
        for(j<-1 to (nmax-1)/i){
          s(i*j)+=1
        }
      }
    }
    for(i<-1 to nmax-1){
      s(i)+=s(i-1)
    }

    for(_<-0 until t){
      var sum=0L

      val a=nextInt
      val b=nextInt
      out.println(s(a)-s(b))
    }

    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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
    val t=nextInt
    val prime=Array.fill(5000002)(true)
    for(i<-2 until 2233){
      if(prime(i)){
        for(j<-i until 5000002/i){
          prime(j*i)=false
        }
      }
    }
/*    for(i<-2L until 2233L){
      if(prime(i.toInt)){
      var j=i*i
      while(j<5000002){
        prime(j.toInt)=true
        j*=i
      }}
    }*/
    for(_<-0 until t){
      var sum=0

      val a=nextInt
      val b=nextInt
      for(k<- 2 to a){

        if(prime(k)){
          var m=k
          while(m<a){
            sum+=a/m-b/m
            m=m*k
          }
//          out.println(k+" "+a/k+" "+b/k)
        }
      }
          out.println(sum)
    }

    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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
    val t=nextLong
    val prime=Array.fill(5000001)(true)
    for(i<-2 until 2233){
      if(prime(i)){
        for(j<-i until 5000001/i){
          prime(j*i)=false
        }
      }
    }
    for(i<-2L until 2233L){
      var j=i*i
      while(j<5000001L){
        prime(j.toInt)=true
        j*=i
      }
    }
    for(_<-0L until t){
      var sum=0L

      val a=nextLong
      val b=nextLong
      for(k<- 2L to a){
        if(prime(k.toInt)){
          sum+=a/k-b/k
      //    out.println(k+" "+(a/k-b/k))
        }
      }
          out.println(sum)
    }

    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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
    val t=nextInt
    val prime=Array.fill(5000002)(true)
    for(i<-2 until 2233){
      if(prime(i)){
        for(j<-i until 5000002/i){
          prime(j*i)=false
        }
      }
    }
/*    for(i<-2L until 2233L){
      if(prime(i.toInt)){
      var j=i*i
      while(j<5000002){
        prime(j.toInt)=true
        j*=i
      }}
    }*/
    for(_<-0 until t){
      var sum=0

      val a=nextInt
      val b=nextInt
      for(k<- 2 to a){

        if(prime(k)){
          var m=k
          while(m<=a){
            sum+=a/m-b/m
            m=m*k
          }
//          out.println(k+" "+a/k+" "+b/k)
        }
      }
          out.println(sum)
    }

    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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
    val t=nextLong
    val prime=Array.fill(5000002)(true)
    for(i<-2 until 2233){
      if(prime(i)){
        for(j<-i until 5000002/i){
          prime(j*i)=false
        }
      }
    }
    for(i<-2L until 2233L){
      if(prime(i.toInt)){
      var j=i*i
      while(j<5000002L){
        prime(j.toInt)=true
        j*=i
      }}
    }
    for(_<-0L until t){
      var sum=0L

      val a=nextLong
      val b=nextLong
      for(k<- 2L to a){
        if(prime(k.toInt)){
          sum+=a/k-b/k
        }
      }
          out.println(sum)
    }

    //code ends here
    out.flush
    out.close
  }
}


Konrad is a Human Relations consultant working for VoltModder, a large electrical equipment producer. Today, he has been tasked with evaluating the level of happiness in the company.There are $$$n$$$ people working for VoltModder, numbered from $$$1$$$ to $$$n$$$. Each employee earns a different amount of money in the company — initially, the $$$i$$$-th person earns $$$i$$$ rubles per day.On each of $$$q$$$ following days, the salaries will be revised. At the end of the $$$i$$$-th day, employee $$$v_i$$$ will start earning $$$n+i$$$ rubles per day and will become the best-paid person in the company. The employee will keep his new salary until it gets revised again.Some pairs of people don't like each other. This creates a great psychological danger in the company. Formally, if two people $$$a$$$ and $$$b$$$ dislike each other and $$$a$$$ earns more money than $$$b$$$, employee $$$a$$$ will brag about this to $$$b$$$. A dangerous triple is a triple of three employees $$$a$$$, $$$b$$$ and $$$c$$$, such that $$$a$$$ brags to $$$b$$$, who in turn brags to $$$c$$$. If $$$a$$$ dislikes $$$b$$$, then $$$b$$$ dislikes $$$a$$$.At the beginning of each day, Konrad needs to evaluate the number of dangerous triples in the company. Can you help him do it?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le m \le 100\,000$$$) — the number of employees in the company and the number of pairs of people who don't like each other. Each of the following $$$m$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$) denoting that employees $$$a_i$$$ and $$$b_i$$$ hate each other (that is, $$$a_i$$$ dislikes $$$b_i$$$ and $$$b_i$$$ dislikes $$$a_i$$$). Each such relationship will be mentioned exactly once. The next line contains an integer $$$q$$$ ($$$0 \le q \le 100\,000$$$) — the number of salary revisions. The $$$i$$$-th of the following $$$q$$$ lines contains a single integer $$$v_i$$$ ($$$1 \le v_i \le n$$$) denoting that at the end of the $$$i$$$-th day, employee $$$v_i$$$ will earn the most.

Output $$$q + 1$$$ integers. The $$$i$$$-th of them should contain the number of dangerous triples in the company at the beginning of the $$$i$$$-th day.

NoteConsider the first sample test. The $$$i$$$-th row in the following image shows the structure of the company at the beginning of the $$$i$$$-th day. A directed edge from $$$a$$$ to $$$b$$$ denotes that employee $$$a$$$ brags to employee $$$b$$$. The dangerous triples are marked by highlighted edges.

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

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

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }
  def cumSum(as: Array[Int]): 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にしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n, m = ni()
    val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())
    val degIn, degOut = Array.ofDim[Int](n)

    def addEdge(from: Int, to: Int): Unit = {
      g(from) += to
      degIn(from) += 1
      degOut(to) += 1
    }

    REP(m) { _ =>
      val a, b = ni() - 1
      // bragされる側からの有向グラフ
      if (a < b) addEdge(a, b) else addEdge(b, a)
    }

    var ans = 0L
    REP(n) { v =>
      ans += degIn(v).toLong * degOut(v)
    }
    out.println(ans)
    REP(ni()) { _ =>
      val v = ni() - 1
      val prev = degOut(v).toLong * degIn(v)
      degOut(v) += degIn(v)
      degIn(v) = 0
      ans -= prev
      var i = 0
      while (i < g(v).length) {
        val u = g(v)(i)
        g(u) += v
        val prev = degIn(u).toLong * degOut(u)
        degIn(u) += 1
        degOut(u) -= 1
        val cur = degIn(u).toLong * degOut(u)
        ans += cur - prev
        i += 1
      }
      g(v).clear()
      out.println(ans)
    }
  }
}

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

  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 = {
    var i = from
    while (i <= to) {
      f(i); i += 1
    }
  }

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

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

  def cumSum(as: Array[Int]): 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 java.util.Arrays.sort

  import Main._
  import sc._

  import scala.collection.mutable
  import mutable.ArrayBuffer

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

  def solve(): Unit = {
    val n, m = ni()
    val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())
    val degIn, degOut = Array.ofDim[Long](n)

    def addEdge(from: Int, to: Int): Unit = {
      g(from) += to
      degIn(from) += 1
      degOut(to) += 1
    }

    REP(m) { _ =>
      val a, b = ni() - 1
      // bragされる側からの有向グラフ
      if (a < b) addEdge(a, b) else addEdge(b, a)
    }

    var ans = 0L
    REP(n) { v =>
      ans += degIn(v) * degOut(v)
    }
    out.println(ans)
    REP(ni()) { _ =>
      val v = ni() - 1
      val prev = degOut(v) * degIn(v)
      degOut(v) += degIn(v)
      degIn(v) = 0
      ans -= prev
      var i = 0
      val len = g(v).length
      while (i < len) {
        val u = g(v)(i)
        g(u) += v
        val prev = degIn(u) * degOut(u)
        degIn(u) += 1
        degOut(u) -= 1
        val cur = degIn(u) * degOut(u)
        ans += cur - prev
        i += 1
      }
      g(v).clear()
      out.println(ans)
    }
  }
}

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

  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 = {
    var i = from
    while (i <= to) {
      f(i); i += 1
    }
  }

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

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

  def cumSum(as: Array[Int]): 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 java.util.Arrays.sort

  import Main._
  import sc._

  import scala.collection.mutable
  import mutable.ArrayBuffer

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

  def solve(): Unit = {
    val n, m = ni()
    val g = Array.fill[ArrayBuffer[Integer]](n)(ArrayBuffer())
    val degIn, degOut = Array.ofDim[Long](n)

    def addEdge(from: Int, to: Int): Unit = {
      g(from) += to
      degIn(from) += 1
      degOut(to) += 1
    }

    REP(m) { _ =>
      val a, b = ni() - 1
      // bragされる側からの有向グラフ
      if (a < b) addEdge(a, b) else addEdge(b, a)
    }

    var ans = 0L
    REP(n) { v =>
      ans += degIn(v) * degOut(v)
    }
    out.println(ans)
    REP(ni()) { _ =>
      val v = ni() - 1
      val prev = degOut(v) * degIn(v)
      degOut(v) += degIn(v)
      degIn(v) = 0
      ans -= prev
      val vInt: Integer = v // boxing対策
      var i = 0
      while (i < g(v).length) {
        val u = g(v)(i).intValue()
        g(u) += vInt
        val prev = degIn(u) * degOut(u)
        degIn(u) += 1
        degOut(u) -= 1
        val cur = degIn(u) * degOut(u)
        ans += cur - prev
        i += 1
      }
      g(v).clear()
      out.println(ans)
    }
  }
}


Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: where  is equal to 1 if some ai = 1, otherwise it is equal to 0.Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as Aij. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:.(Bij is OR of all elements in row i and column j of matrix A)Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.

The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively. The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).

In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(m, n) = in.next().split(' ').map(_.toInt)
  val sourceMatrix = Array.ofDim[Int](m, n)
  val emptyRow = Array.ofDim[Boolean](m)
  val emptyCol = Array.ofDim[Boolean](n)
  (0 until m).foreach{i =>
    val row = in.next().split(' ').map(_.toInt)
    sourceMatrix(i) = row
    val index = row.indexOf(0)
    if (index != -1) {
      emptyRow(i) = true
      (index until n).foreach { i => emptyCol(i) ||= row(i) == 0 }
    }
  }

  val res = (0 until m).forall {i =>
    (0 until n).forall { j =>
      val cell = emptyCol(j) && emptyRow(i)
      if (cell)
        sourceMatrix(i)(j) == 0
      else
        sourceMatrix(i)(j) == 1
      }
    }
  val fillRows = emptyRow.count(_ == false)
  val fillCols = emptyCol.count(_ == false)

  if (res && (fillRows == fillCols || (fillRows != 0 && fillCols != 0))) {
    println("YES")
    println((0 until m).map {i =>
      (0 until n).map { j =>
        if (emptyRow(i) || emptyCol(j)) 0 else 1
      }.mkString(" ")
    }.mkString("\n"))
  } else
    println("NO")

}

import scala.io.StdIn._

object ProblemB {
  def main(args: Array[String]) {
    val Array(m, n) = readLine split " " map (_.toInt)
    var B = new Array[Array[Int]](m)
    for (i <- 0 until m) {
      B(i) = readLine split " " map (_.toInt)
    }

    var A = Array.tabulate(m, n)((x, y) => 1)
    for (i <- 0 until m) {
      for (j <- 0 until n) {
        if (B(i)(j) == 0) {
          for (k <- 0 until m) A(k)(j) = 0
          for (k <- 0 until n) A(i)(k) = 0
        }
      }
    }

    val rows = for (i <- 0 until m) yield { A(i) exists (_ == 1) }
    val cols = for (j <- 0 until n) yield {
      (for (i <- 0 until m) yield A(i)(j)) exists (_ == 1)
    }

    var win = true
    for (i <- 0 until m) {
      for (j <- 0 until n) {
        if ((B(i)(j) == 1) != (rows(i) || cols(j)))
          win = false
      }
    }

    if (!win) {
      println("NO")
    } else {
      println("YES")
      for (i <- 0 until m) {
        println(A(i) mkString " ")
      }
    }

  }
}

import java.util.Scanner
import java.util.Arrays

object Solution {
    def main(args: Array[String]) = {
	val in = new Scanner(System.in)
	val n = in.nextInt()
	val m = in.nextInt()
	val b: Array[Array[Int]] = new Array(n)
	var i = 0
	for (i <- 0 until n) {
	    b(i) = new Array(m)
	    var j = 0
	    for (j <- 0 until m)
		b(i)(j) = in.nextInt()
	}
	val a: Array[Array[Int]] = new Array(n)
	for (i <- 0 until n) {
	    a(i) = new Array(m)
	    Arrays.fill(a(i), 1)
	}
	for (i <- 0 until n) {
	    var j = 0
	    for (j <- 0 until m) {
		if (b(i)(j) == 0) {
		    var k = 0
		    for (k <- 0 until m)
			a(i)(k) = 0
		    for (k <- 0 until n)
			a(k)(j) = 0
		}
	    }
	}
	var ok = true
	for (i <- 0 until n) {
	var j = 0
	    for (j <- 0 until m) {
		var curr = 0
		var k = 0
		for (k <- 0 until m)
		    curr |= a(i)(k)
		for (k <- 0 until n)
		    curr |= a(k)(j)
		if (curr != b(i)(j))
		    ok = false
	    }
	}
	if (ok) {
	    println("YES")
	    for (i <- 0 until n) {
		var j = 0
		for (j <- 0 until m)
		    print(a(i)(j) + " ")
		println()
	    }
	} else {
	    println("NO")
	}
    }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(m, n) = in.next().split(' ').map(_.toInt)
  val sourceMatrix = Array.ofDim[Int](m, n)
  val emptyRow = Array.ofDim[Boolean](m)
  val emptyCol = Array.ofDim[Boolean](n)
  (0 until m).foreach{i =>
    val row = in.next().split(' ').map(_.toInt)
    sourceMatrix(i) = row
    val index = row.indexOf(0)
    if (index != -1) {
      emptyRow(i) = true
      (index until n).foreach { i => emptyCol(i) ||= row(i) == 0 }
    }
  }

  val res = (0 until m).forall {i =>
    (0 until n).forall { j =>
      (sourceMatrix(i)(j) == 1) ||
        sourceMatrix(i).contains(1) || (0 until m).exists(i => sourceMatrix(i)(j) == 1)
      }
    }

  if (res) {
    println("YES")
    println((0 until m).map {i =>
      (0 until n).map { j =>
        if (emptyRow(i) || emptyCol(j)) 0 else 1
      }.mkString(" ")
    }.mkString("\n"))
  } else
    println("NO")

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(m, n) = in.next().split(' ').map(_.toInt)
  val sourceMatrix = Array.ofDim[Int](m, n)
  val emptyRow = Array.ofDim[Boolean](m)
  val emptyCol = Array.ofDim[Boolean](n)
  (0 until m).foreach{i =>
    val row = in.next().split(' ').map(_.toInt)
    sourceMatrix(i) = row
    val index = row.indexOf(0)
    if (index != -1) {
      emptyRow(i) = true
      (index until n).foreach { i => emptyCol(i) ||= row(i) == 0 }
    }
  }

  val res = (0 until m).forall {i =>
    (0 until n).forall { j =>
      val cell = emptyCol(j) && emptyRow(i)
      if (sourceMatrix(i)(j) == 1)
        !cell
      else
        cell
      }
    }

  if (res) {
    println("YES")
    println((0 until m).map {i =>
      (0 until n).map { j =>
        if (emptyRow(i) || emptyCol(j)) 0 else 1
      }.mkString(" ")
    }.mkString("\n"))
  } else
    println("NO")

}

import scala.io.StdIn._

object ProblemB {
  def main(args: Array[String]) {
    val Array(m, n) = readLine split " " map (_.toInt)
    var B = new Array[Array[Int]](m)
    for (i <- 0 until m) {
      B(i) = readLine split " " map (_.toInt)
    }

    var rows = Array.fill(m)(1)
    var cols = Array.fill(n)(1)
    for (i <- 0 until m) {
      for (j <- 0 until n) {
        if (B(i)(j) == 0) {
          rows(i) = 0
          cols(j) = 0
        }
      }
    }

    var win = true
    for (i <- 0 until m) {
      for (j <- 0 until n) {
        if (B(i)(j) != (rows(i) & cols(j)))
          win = false
      }
    }

    val row = for (j <- 0 until n) yield j

    if (!win) {
      println("NO")
    } else {
      println("YES")
      for (i <- 0 until m) {
        println(row map (cols(_) & rows(i)) mkString " ")
      }
    }
  }
}

import scala.io.StdIn._

object ProblemB {
  def main(args: Array[String]) {
    val Array(m, n) = readLine split " " map (_.toInt)
    var B = new Array[Array[Int]](m)
    for (i <- 0 until m) {
      B(i) = readLine split " " map (_.toInt)
    }

    var rows = Array.fill(m)(1)
    var cols = Array.fill(n)(1)
    for (i <- 0 until m) {
      for (j <- 0 until n) {
        if (B(i)(j) == 0) {
          rows(i) = 0
          cols(j) = 0
        }
      }
    }

    var win = true
    for (i <- 0 until m) {
      for (j <- 0 until n) {
        if (B(i)(j) != (rows(i) | cols(j)))
          win = false
      }
    }

    val row = for (j <- 0 until n) yield j

    if (!win) {
      println("NO")
    } else {
      println("YES")
      for (i <- 0 until m) {
        println(row map (cols(_) & rows(i)) mkString " ")
      }
    }
  }
}


Gerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows.A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a basic polygon. If you shake a Randomizer, it draws some nondegenerate (i.e. having a non-zero area) convex polygon with vertices at some vertices of the basic polygon. The result of the roll (more precisely, the result of the shaking) is considered to be the number of points with integer coordinates, which were strictly inside (the points on the border are not considered) the selected polygon. Now Gerald is wondering: what is the expected result of shaking the Randomizer?During the shaking the Randomizer considers all the possible non-degenerate convex polygons with vertices at the vertices of the basic polygon. Let's assume that there are k versions of the polygons. Then the Randomizer chooses each of them with probability .

The first line of the input contains a single integer n (3 ≤ n ≤ 100 000) — the number of vertices of the basic polygon.  Next n lines contain the coordinates of the vertices of the basic polygon. The i-th of these lines contain two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex of the polygon. The vertices are given in the counter-clockwise order.

Print the sought expected value with absolute or relative error at most 10 - 9.

NoteA polygon is called strictly convex if it is convex and no its vertices lie on the same line.Let's assume that a random variable takes values x1, ..., xn with probabilities p1, ..., pn, correspondingly. Then the expected value of this variable equals to .

object D{
  //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}
  import math.{pow,abs,min}
  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 gcd(a:Int,b:Int):Int={
      if(b==0||a==0){
        a+b
      }else{
        gcd(b,a%b)
      }
    }
    val n=nextInt
    val x=Array.ofDim[Int](n)
    val y=Array.ofDim[Int](n)
    val xD=Array.ofDim[Double](n)
    val yD=Array.ofDim[Double](n)
    val po=for(i<-0 until n+1) yield pow(2,-i)
    for(i<- 0 until n){
      x(i)=nextInt
      y(i)=nextInt

    }
    for(i<-0 until n){
      xD(i)=x(i)
      yD(i)=y(i)
    }
    var A=0.0
    var b=0.0

    val p0:Double=(1-(1+n*(n+1)/2)*pow(2,-n))
    for(i<-0 until n;k<-1 until min(61,n)){
      val p=(po(k+1)-po(n))/p0
      val j=(i+k)%n
      A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2
      b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))
    }
    val ans=abs(A)-b/2+1

      out.println("%10.9f".format(ans))

    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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}
  import math.{pow,abs,min}
  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 gcd(a:Int,b:Int):Int={
      if(b==0||a==0){
        a+b
      }else{
        gcd(b,a%b)
      }
    }
    val n=nextInt
    val x=Array.ofDim[Int](n)
    val y=Array.ofDim[Int](n)
    val xD=Array.ofDim[Double](n)
    val yD=Array.ofDim[Double](n)
    for(i<- 0 until n){
      x(i)=nextInt
      y(i)=nextInt

    }
    for(i<-0 until n){
      xD(i)=x(i)
      yD(i)=y(i)
    }
    var A=0.0
    var b=0.0
    if(n==100000){
      return
    }else{

    for(i<-0 until n;k<-1 until min(61,n)){
      val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))
      val j=(i+k)%n
      A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2
      b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))
    }
    val ans=abs(A)-b/2+1

      out.println("%10.9f".format(ans))
    }
    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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}
  import math.{pow,abs,min}
  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 gcd(a:Int,b:Int):Int={
      if(b==0||a==0){
        a+b
      }else{
        gcd(b,a%b)
      }
    }
    val n=nextInt
    val x=Array.ofDim[Int](n)
    val y=Array.ofDim[Int](n)
    val xD=Array.ofDim[Double](n)
    val yD=Array.ofDim[Double](n)
    val timeStart=java.lang.System.currentTimeMillis()
    for(i<- 0 until n){
      x(i)=nextInt
      y(i)=nextInt

    }
    for(i<-0 until n){
      xD(i)=x(i)
      yD(i)=y(i)
    }
    var A=0.0
    var b=0.0
    if(n==100000){
      out.println(java.lang.System.currentTimeMillis()-timeStart)
      return
    }else{

    for(i<-0 until n;k<-1 until min(61,n)){
      val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))
      val j=(i+k)%n
      A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2
      b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))
    }
    val ans=abs(A)-b/2+1

      out.println("%10.9f".format(ans))
    }
    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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}
  import math.{pow,abs,min}
  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 gcd(a:Int,b:Int):Int={
      if(b==0||a==0){
        a+b
      }else{
        gcd(b,a%b)
      }
    }
    val n=nextInt
    val x=Array.ofDim[Int](n)
    val y=Array.ofDim[Int](n)
    val xD=Array.ofDim[Double](n)
    val yD=Array.ofDim[Double](n)
    val timeStart=java.lang.System.currentTimeMillis()
    for(i<- 0 until n){
      x(i)=nextInt
      y(i)=nextInt

    }
    for(i<-0 until n){
      xD(i)=x(i)
      yD(i)=y(i)
    }
    var A=0.0
    var b=0.0
    if(n==100000){
      out.println(java.lang.System.currentTimeMillis()-timeStart)

    }else{

    for(i<-0 until n;k<-1 until min(61,n)){
      val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))
      val j=(i+k)%n
      A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2
      b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))
    }
    val ans=abs(A)-b/2+1

      out.println("%10.9f".format(ans))
    }
    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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}
  import math.{pow,abs,min}
  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 gcd(a:Int,b:Int):Int={
      if(b==0||a==0){
        a+b
      }else{
        gcd(b,a%b)
      }
    }
    val n=nextInt
    val x=Array.ofDim[Int](n)
    val y=Array.ofDim[Int](n)
    val xD=Array.ofDim[Double](n)
    val yD=Array.ofDim[Double](n)
    for(i<- 0 until n){
      x(i)=nextInt
      y(i)=nextInt

    }
    var A=0.0
    var b=0.0
    if(n==100000){
      return
    }else{
    for(i<-0 until n){
      xD(i)=x(i)
      yD(i)=y(i)
    }
    for(i<-0 until n;k<-1 until min(61,n)){
      val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))
      val j=(i+k)%n
      A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2
      b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))
    }
    val ans=abs(A)-b/2+1

      out.println("%10.9f".format(ans))
    }
    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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}
  import math.{pow,abs,min}
  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 gcd(a:Int,b:Int):Int={
      if(b==0||a==0){
        a+b
      }else{
        gcd(b,a%b)
      }
    }
    val n=nextInt
    val x=Array.ofDim[Int](n)
    val y=Array.ofDim[Int](n)
    val xD=Array.ofDim[Double](n)
    val yD=Array.ofDim[Double](n)
    val timeStart=java.lang.System.currentTimeMillis()
    for(i<- 0 until n){
      x(i)=nextInt
      y(i)=nextInt

    }
    for(i<-0 until n){
      xD(i)=x(i)
      yD(i)=y(i)
    }
    var A=0.0
    var b=0.0
    if(n==100000){

    }else{
    val p0:Double=(1-(1+n*(n+1)/2)*pow(2,-n))
    for(i<-0 until n;k<-1 until min(61,n)){
      val p=(pow(2,-k-1)-pow(2,-n))/p0
      val j=(i+k)%n
      A+=p*(xD(i)*yD(j)-xD(j)*yD(i))/2
      b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))
    }
    val ans=abs(A)-b/2+1

      out.println("%10.9f".format(ans))
    }
    //code ends here
    out.flush
    out.close
  }
}

object D{
  //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}
  import math.{pow,abs,min}
  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 gcd(a:Int,b:Int):Int={
      if(b==0||a==0){
        a+b
      }else{
        gcd(b,a%b)
      }
    }
    val n=nextInt
    val x=Array.ofDim[Int](n)
    val y=Array.ofDim[Int](n)
    for(i<- 0 until n){
      x(i)=nextInt;
      y(i)=nextInt;
    }
    var A=0.0
    var b=0.0
    for(i<-0 until n;k<-1 until min(61,n)){
      val p=(pow(2,-k-1)-pow(2,-n))/(1-(1+n*(n+1)/2)*pow(2,-n))
      val j=(i+k)%n
      A+=p*(x(i)*y(j)-x(j)*y(i))/2
      b+=p*gcd(abs(x(i)-x(j)),abs(y(i)-y(j)))
    }
    val ans=A-b/2+1

    out.println("%10.9f".format(ans))
    //code ends here
    out.flush
    out.close
  }
}


This problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string $$$s$$$ of length $$$n$$$, consisting only of lowercase English letters. The player can ask two types of queries:   ? l r – ask to list all substrings of $$$s[l..r]$$$. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled.  ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than $$$3$$$ queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed $$$\left\lceil 0.777(n+1)^2 \right\rceil$$$ ($$$\lceil x \rceil$$$ is $$$x$$$ rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.

First line contains number $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the picked string.

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Map
import scala.collection.mutable.StringBuilder

object Main {

  def query(n: Int) = {
    println(f"? 1 $n"); Console.flush
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim.sorted)
  }

  def extraChar(cArr: List[Char], s: String): Char = {
    if (cArr.isEmpty || s.length == 1) {
      s(0)
    } else {
      val i = s.indexOf(cArr.head)
      val (pA, pB) = s.splitAt(i)
      extraChar(cArr.tail, pA ++ pB.tail)
    }
  }

  def hackPart(n: Int): String = {
    val ssButOne = collection.mutable.Map[String, Int]()

    query(n).foreach(s => {
      ssButOne(s) = ssButOne.getOrElse(s, 0) + 1
    })

    query(n - 1).foreach(s =>
      ssButOne.getOrElse(s, -1) match {
        case 1    => ssButOne -= s
        case -1   => {}
        case _ @x => ssButOne(s) = x - 1
      }
    )

    ssButOne.keySet.toList
      .sortBy(_.length)
      .foldLeft(List[Char]())((z, s) => extraChar(z, s) :: z)
      .mkString
  }

  def genWeight(arr: Array[Int], i: Int): List[Array[Int]] = {
    if (i == arr.length - 1) List()
    else {
      val nArr =
        arr.zipWithIndex.map({ case (x, j) => if (j > i) x + 1 else x })
      nArr :: genWeight(nArr, i + 1)
    }
  }

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

    if (n < 2) {
      val c = query(1).head
      println(f"! $c")

    } else if (n <= 4) {
      val substrs = hackPart(n)
      println(f"! $substrs")

    } else {

      val half = hackPart((n + 1) / 2)

      /* println(half) */

      val allSubstrs = query(n)
      val allLetters = allSubstrs.filter(_.length == n)(0)
      val substrs = allSubstrs
        .filter(x => x.length <= (n + 1) / 2 && x.length > 1)

      val freqLeft = (1 to (n - 1) / 2)
        .zip(genWeight(Array.fill((n + 1) / 2) { 1 }, 0))
        .map {
          case (i, weights) => {
            val cFreq = Array.fill(26) { 0 }

            substrs
              .filter(_.length == i + 1)
              .foreach(x => x.foreach(c => cFreq(c - 97) += 1))

            /* cFreq.foreach(x => if (x > 0) print(x + "\t"))
            println() */

            half.zip(weights).foreach {
              case (c, w) => {
                /* print(f"($c: $w) ") */
                cFreq(c - 97) -= w
              }
            }
            /* println */

            cFreq
          }
        }

      /* freqLeft.foreach(arr => {
        arr.zipWithIndex.foreach(x =>
          if (x._1 > 0) print(f"(${(x._2 + 97).toChar}: ${x._1})\t")
        )
        println
      }) */

      val accumFreq = Array.fill(26) { 0 }
      var lastHalf = ""

      val x = (2 to (n + 1) / 2).zip(freqLeft).foreach {
        case (i, x) => {
          for (j <- 0 until 26) x(j) -= accumFreq(j)
          x.zipWithIndex.foreach(pair =>
            if (pair._1 % i != 0 && (pair._1 - i + 1) % i == 0) {
              lastHalf = (pair._2 + 97).toChar + lastHalf
              accumFreq(pair._2) += i - 1
            }
          )
        }
      }

      /* println(lastHalf) */

      var middle = ""
      if (half.length + lastHalf.length < n)
        middle = extraChar((half + lastHalf).toList, allLetters).toString

      println(f"! ${half ++ middle ++ lastHalf}")
    }
  }
}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Map

object Main extends App {
  val n = readInt()

  if (n < 2) {
    println("? 1 1"); Console.flush
    val c = readLine.trim.head
    println(f"! $c")

  } else {

    println(f"? 1 $n"); Console.flush
    val ssButOne = collection.mutable.Map[String, Int]()
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim.sorted)
      .foreach(s => ssButOne(s) = ssButOne.getOrElse(s, 0) + 1)

    println(f"? 1 ${n - 1}"); Console.flush
    (1 to (n * (n - 1) / 2))
      .map(_ => readLine.trim.sorted)
      .foreach(s =>
        ssButOne.getOrElse(s, -1) match {
          case 1    => ssButOne -= s
          case -1   => {}
          case _ @x => ssButOne(s) = x - 1
        }
      )

    val remains = ssButOne.keySet.toList.sortBy(_.length)

    def extraChar(cArr: List[Char], s: String): Char = {
      if (cArr.isEmpty || s.length == 1) {
        s(0)
      } else {
        val i = s.indexOf(cArr.head)
        val (pA, pB) = s.splitAt(i)
        extraChar(cArr.tail, pA ++ pB.tail)
      }
    }

    val hack = remains
      .foldLeft(List[Char]())((z, s) => {
        extraChar(z, s) :: z
      })
      .mkString
    println(f"! $hack")
  }
}

/* aabc */
/*
xyz
yz
xy
z
x
y
zy
z
y
 */

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Map
import scala.collection.mutable.StringBuilder

object Main {

  def query(n: Int) = {
    println(f"? 1 $n"); Console.flush
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim.sorted)
  }

  def extraChar(cArr: List[Char], s: String): Char = {
    if (cArr.isEmpty || s.length == 1) {
      s(0)
    } else {
      val i = s.indexOf(cArr.head)
      val (pA, pB) = s.splitAt(i)
      extraChar(cArr.tail, pA ++ pB.tail)
    }
  }

  def hackPart(n: Int): String = {
    val ssButOne = collection.mutable.Map[String, Int]()

    query(n).foreach(s => {
      ssButOne(s) = ssButOne.getOrElse(s, 0) + 1
    })

    query(n - 1).foreach(s =>
      ssButOne.getOrElse(s, -1) match {
        case 1    => ssButOne -= s
        case -1   => {}
        case _ @x => ssButOne(s) = x - 1
      }
    )

    ssButOne.keySet.toList
      .sortBy(_.length)
      .foldLeft(List[Char]())((z, s) => extraChar(z, s) :: z)
      .mkString
  }

  def genWeight(arr: Array[Int], i: Int): List[Array[Int]] = {
    if (i == arr.length - 1) List()
    else {
      val nArr =
        arr.zipWithIndex.map({ case (x, j) => if (j > i) x + 1 else x })
      nArr :: genWeight(nArr, i + 1)
    }
  }

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

    if (n < 2) {
      val c = query(1).head
      println(f"! $c")

    } else {

      val half = hackPart((n + 1) / 2)

      /* println(half) */

      val allSubstrs = query(n)
      val allLetters = allSubstrs.filter(_.length == n)(0)
      val substrs = allSubstrs
        .filter(x => x.length <= (n + 1) / 2 && x.length > 1)

      val freqLeft = (1 to (n - 1) / 2)
        .zip(genWeight(Array.fill((n + 1) / 2) { 1 }, 0))
        .map {
          case (i, weights) => {
            val cFreq = Array.fill(26) { 0 }

            substrs
              .filter(_.length == i + 1)
              .foreach(x => x.foreach(c => cFreq(c - 97) += 1))

            /* cFreq.foreach(x => if (x > 0) print(x + "\t"))
            println() */

            half.zip(weights).foreach {
              case (c, w) => {
                /* print(f"($c: $w) ") */
                cFreq(c - 97) -= w
              }
            }
            /* println */

            cFreq
          }
        }

      /* freqLeft.foreach(arr => {
        arr.zipWithIndex.foreach(x =>
          if (x._1 > 0) print(f"(${(x._2 + 97).toChar}: ${x._1})\t")
        )
        println
      }) */

      val accumFreq = Array.fill(26) { 0 }
      var lastHalf = ""

      val x = (2 to (n + 1) / 2).zip(freqLeft).foreach {
        case (i, x) => {
          for (j <- 0 until 26) x(j) -= accumFreq(j)
          x.zipWithIndex.foreach(pair =>
            if (pair._1 % i != 0 && (pair._1 - i + 1) % i == 0) {
              lastHalf = (pair._2 + 97).toChar + lastHalf
              accumFreq(pair._2) += i - 1
            }
          )
        }
      }

      /* println(lastHalf) */

      var middle = ""
      if (half.length + lastHalf.length < n)
        middle = extraChar((half + lastHalf).toList, allLetters).toString

      println(f"! ${half ++ middle ++ lastHalf}")
    }
  }
}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Map
import scala.collection.mutable.StringBuilder

object Main {

  def query(n: Int) = {
    println(f"? 1 $n"); Console.flush
    (1 to (n * (n + 1) / 2))
      .map(_ => readLine.trim.sorted)
  }

  def extraChar(cArr: List[Char], s: String): Char = {
    if (cArr.isEmpty || s.length == 1) {
      s(0)
    } else {
      val i = s.indexOf(cArr.head)
      val (pA, pB) = s.splitAt(i)
      extraChar(cArr.tail, pA ++ pB.tail)
    }
  }

  def hackPart(n: Int): String = {
    val ssButOne = collection.mutable.Map[String, Int]()

    query(n).foreach(s => {
      ssButOne(s) = ssButOne.getOrElse(s, 0) + 1
    })

    query(n - 1).foreach(s =>
      ssButOne.getOrElse(s, -1) match {
        case 1    => ssButOne -= s
        case -1   => {}
        case _ @x => ssButOne(s) = x - 1
      }
    )

    ssButOne.keySet.toList
      .sortBy(_.length)
      .foldLeft(List[Char]())((z, s) => extraChar(z, s) :: z)
      .mkString
  }

  def genWeight(arr: Array[Int], i: Int): List[Array[Int]] = {
    if (i == arr.length - 1) List()
    else {
      val nArr =
        arr.zipWithIndex.map({ case (x, j) => if (j > i) x + 1 else x })
      nArr :: genWeight(nArr, i + 1)
    }
  }

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

    if (n < 2) {
      val c = query(1).head
      println(f"! $c")

    } else {

      val half = hackPart((n + 1) / 2)
      val substrs = query(n)
        .filter(x => x.length <= (n + 1) / 2 && x.length > 1)

      val freqLeft = (1 to (n - 1) / 2)
        .zip(genWeight(Array.fill((n + 1) / 2) { 1 }, 0))
        .map {
          case (i, weights) => {
            val cFreq = Array.fill(26) { 0 }

            substrs
              .filter(_.length == i + 1)
              .foreach(x => x.foreach(c => cFreq(c - 97) += 1))

            /* cFreq.foreach(x => if (x > 0) print(x + "\t"))
            println() */

            half.zip(weights).foreach {
              case (c, w) => {
                /* print(f"($c: $w) ") */
                cFreq(c - 97) -= w
              }
            }
            /* println */

            cFreq
          }
        }

      /* x.foreach(arr => {
        arr.zipWithIndex.foreach(x =>
          if (x._1 > 0) print(f"(${(x._2 + 97).toChar}: ${x._1})\t")
        )
        println
      }) */

      val accumFreq = Array.fill(26) { 0 }
      var lastHalf = ""

      val x = (2 to (n + 1) / 2).zip(freqLeft).foreach {
        case (i, x) => {
          for (j <- 0 until 26) x(j) -= accumFreq(j)
          x.zipWithIndex.foreach(pair =>
            if (pair._1 % i != 0 && (pair._1 - i + 1) % i == 0) {
              lastHalf = (pair._2 + 97).toChar + lastHalf
              accumFreq(pair._2) += i - 1
            }
          )
        }
      }

      println(f"! ${half ++ lastHalf}")
    }
  }
}

/* aabc */
/*
xyz
yz
xy
z
x
y
zy
z
y
 */


While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.

The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.

If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.

NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.

import scala.io.StdIn.readLine
object UncommonSeq extends App {
  val x = readLine
  val y = readLine
  println(if (x == y) -1 else x.length.max(y.length))
}

object A766 {

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

  def main(args: Array[String]): Unit = {
    val first = read
    val second = read

    if(first.compareTo(second) == 0) {
      println(-1)
    } else {
      println(math.max(first.length, second.length))
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

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

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

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

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

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

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

import io.StdIn.readLine

object Mahmoud extends App {

  val a = readLine()
  val b = readLine()
  val s = solve(a, b)
  println (s)

  def solve (a: String, b: String) : Int = {

    if (a == b) -1 else a.length.max(b.length)
  }
}

object A766 {

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

  def main(args: Array[String]): Unit = {
    val first = read
    val second = read

    if(first.distinct.length == 1 && second.distinct.length == 1) {
      if(first.head == second.head)
        println(-1)
      else
        println(1)
    } else if(first.length == second.length) {
      println(first.length - 1)
    } else {
      println(math.max(first.length, second.length))
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object A766 {

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

  def main(args: Array[String]): Unit = {
    val first = read
    val second = read

    if(first.distinct.length == 1 && second.distinct.length == 1) {
      if(first.head == second.head)
        println(-1)
      else
        println(1)
    } else if(first.compareTo(second) == 0) {
      println(first.length - 1)
    } else {
      println(math.max(first.length, second.length))
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object A766 {

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

  def main(args: Array[String]): Unit = {
    val first = read
    val second = read

    if(first.distinct.length == 1 && second.distinct.length == 1 && first.head == second.head) {
      println(-1)
    } else if(first.compareTo(second) == 0) {
      println(first.length - 1)
    } else {
      println(math.max(first.length, second.length))
    }
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


In the pet store on sale there are:  $$$a$$$ packs of dog food;  $$$b$$$ packs of cat food;  $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ lines are given, each containing a description of one test case. Each description consists of five integers $$$a, b, c, x$$$ and $$$y$$$ ($$$0 \le a,b,c,x,y \le 10^8$$$).

For each test case in a separate line, output:   YES, if suitable food can be bought for each of $$$x$$$ dogs and for each of $$$y$$$ cats;  NO else.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

object Task1 extends App {
  import scala.io.StdIn

  def readLine = StdIn.readLine()
  def readNum = StdIn.readLine().toInt

  val testCases = readNum

  for (_ <- 0 until testCases) {
    val Array(dogFoodPacks, catFoodPacks, univPacks, dogsCount, catsCount) = readLine.split(" ").map(_.toInt)
    val dogPackNeeded = dogFoodPacks - dogsCount
    val catPackNeeded = catFoodPacks - catsCount
    val totalPackNeeded = (if (dogPackNeeded < 0) dogPackNeeded else 0) + (if (catPackNeeded < 0) catPackNeeded else 0)

    if (Math.abs(totalPackNeeded) > univPacks) {
      println("NO")
    } else {
      println("YES")
    }
  }

}