So you decided to hold a contest on Codeforces. You prepared the problems: statements, solutions, checkers, validators, tests... Suddenly, your coordinator asks you to change all your tests to multiple testcases in the easiest problem!Initially, each test in that problem is just an array. The maximum size of an array is $$$k$$$. For simplicity, the contents of arrays don't matter. You have $$$n$$$ tests — the $$$i$$$-th test is an array of size $$$m_i$$$ ($$$1 \le m_i \le k$$$).Your coordinator asks you to distribute all of your arrays into multiple testcases. Each testcase can include multiple arrays. However, each testcase should include no more than $$$c_1$$$ arrays of size greater than or equal to $$$1$$$ ($$$\ge 1$$$), no more than $$$c_2$$$ arrays of size greater than or equal to $$$2$$$, $$$\dots$$$, no more than $$$c_k$$$ arrays of size greater than or equal to $$$k$$$. Also, $$$c_1 \ge c_2 \ge \dots \ge c_k$$$.So now your goal is to create the new testcases in such a way that:   each of the initial arrays appears in exactly one testcase;  for each testcase the given conditions hold;  the number of testcases is minimum possible. Print the minimum possible number of testcases you can achieve and the sizes of arrays included in each testcase.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5$$$) — the number of initial tests and the limit for the size of each array. The second line contains $$$n$$$ integers $$$m_1, m_2, \dots, m_n$$$ ($$$1 \le m_i \le k$$$) — the sizes of the arrays in the original tests. The third line contains $$$k$$$ integers $$$c_1, c_2, \dots, c_k$$$ ($$$n \ge c_1 \ge c_2 \ge \dots \ge c_k \ge 1$$$); $$$c_i$$$ is the maximum number of arrays of size greater than or equal to $$$i$$$ you can have in a single testcase.

In the first line print a single integer $$$ans$$$ ($$$1 \le ans \le n$$$) — the minimum number of testcases you can achieve. Each of the next $$$ans$$$ lines should contain the description of a testcase in the following format: $$$t$$$ $$$a_1$$$ $$$a_2$$$ $$$\dots$$$ $$$a_{t}$$$ ($$$1 \le t\le n$$$) — the testcase includes $$$t$$$ arrays, $$$a_i$$$ is the size of the $$$i$$$-th array in that testcase. Each of the initial arrays should appear in exactly one testcase. In particular, it implies that the sum of $$$t$$$ over all $$$ans$$$ testcases should be equal to $$$n$$$. Note that the answer always exists due to $$$c_k \ge 1$$$ (and therefore $$$c_1 \ge 1$$$). If there are multiple answers, you can output any one of them.

NoteIn the first example there is no way to distribute the tests into less than $$$3$$$ testcases. The given answer satisfies the conditions: each of the testcases includes no more than $$$4$$$ arrays of size greater than or equal to $$$1$$$ and no more than $$$1$$$ array of sizes greater than or equal to $$$2$$$ and $$$3$$$.Note that there are multiple valid answers for this test. For example, testcases with sizes $$$[[2], [1, 2], [3]]$$$ would also be correct.However, testcases with sizes $$$[[1, 2], [2, 3]]$$$ would be incorrect because there are $$$2$$$ arrays of size greater than or equal to $$$2$$$ in the second testcase.Note the difference between the third and the fourth examples. You can include up to $$$5$$$ arrays of size greater than or equal to $$$1$$$ in the third example, so you can put all arrays into a single testcase. And you can have only up to $$$1$$$ array in the fourth example. Thus, every array should be included in a separate testcase.

import scala.collection.mutable

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

  val n, k = nextInt
  val ms = nextInts(n)
  val cs = nextInts(k)

  val lastBigger = mutable.Map.empty[Int, Int]
  var prev = -1
  var prevM = -1
  for (i <- 0 until k) {
    if (prev != cs(i)) {
      prev = cs(i)
      prevM = i
    }
    lastBigger(i) = prevM
  }

  val counts = new java.util.TreeMap[Int, Int]
  for (m <- ms) {
    counts.put(m, counts.getOrDefault(m, 0) + 1)
  }

  var resBuilders = mutable.ArrayBuffer.empty[mutable.ArrayBuilder.ofInt]
  while (!counts.isEmpty) {
    resBuilders += new mutable.ArrayBuilder.ofInt
    var lim = Int.MaxValue
    val it = counts.keySet().iterator
    //val removeBuilder = new mutable.ArrayBuilder.ofInt
    var used = 0
    var current = counts.lastKey()
    while (current > 0) {
      val value = counts.get(current)
      lim = cs(current - 1) - used
      if (lim > 0) {
        val take = value min lim
        used += take
        if (value == take) {
          counts.remove(current)
        } else {
          counts.put(current, value - take)
        }
        var i = 0
        while (i < take) {
          resBuilders.last += current
          i += 1
        }
        current = counts.lowerKey(current)
      } else {
        current = lastBigger(current)
      }
    }
//    var i = 0
//    val remove = removeBuilder.result()
//    while (i < remove.length)  {
//      counts.remove(remove(i))
//      i += 1
//    }
  }

  val res = resBuilders.map(_.result())

  out.println(res.size)
  res.foreach { r =>
    out.print(r.length)
    out.println(r.mkString(" ", " ", ""))
  }

  out.flush()

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

object D {
  import InOut._

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

  val n, k = nextInt
  val mn   = nextInts(n).sorted(Ordering.Int.reverse)
  val ck   = nextInts(k)

  val (ans, _, _) = ck.reverse.zipWithIndex
    .foldLeft((0, 0, 0d)) {
      case ((b, j, g), (c, i)) =>
        var t = mn.indexWhere(_ < (k - i), j)
        if (t < 0) t = n

        val h = g + t - j

        (b max math.ceil(h / c).toInt, t, h)
    }

  val kv = collection.mutable.Map.empty[Int, List[Int]]

  mn.zipWithIndex.foreach {
    case (m, i) =>
      val k = i % ans
      val v = m :: kv.getOrElse(k, Nil)

      kv += (k -> v)
  }

  out.println(ans)
  kv.foreach {
    case (_, vs) =>
      out.println(s"${vs.length} ${vs.mkString(" ")}")
  }
  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
  }
}

import scala.collection.mutable

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

  val n, k = nextInt
  val ms = nextInts(n)
  val cs = nextInts(k)

  val counts = mutable.TreeMap.empty[Int, Int].withDefaultValue(0)
  for (m <- ms) {
    counts(m) += 1
  }

  var resBuilders = mutable.ArrayBuffer.empty[mutable.ArrayBuilder.ofInt]
  while (counts.nonEmpty) {
    resBuilders += new mutable.ArrayBuilder.ofInt
    var lim = Int.MaxValue
    val it = counts.iterator
    val removeBuilder = new mutable.ArrayBuilder.ofInt
    while (it.hasNext && lim > 0) {
      val (key, value) = it.next()
      lim = lim min cs(key - 1)
      val take = value min lim
      counts(key) -= take
      if (value == take) {
        removeBuilder += key
      }
      var i = 0
      while (i < take) {
        resBuilders.last += key
        i += 1
      }
      lim -= take
    }
    val remove = removeBuilder.result()
    for (r <- remove) {
      counts.remove(r)
    }
  }

  val res = resBuilders.map(_.result())

  out.println(res.size)
  res.foreach { r =>
    out.print(r.length)
    out.println(r.mkString(" ", " ", ""))
  }

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

import scala.collection.mutable

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

  val n, k = nextInt
  val ms = nextInts(n)
  val cs = nextInts(k)

  val counts = mutable.TreeMap.empty[Int, Int].withDefaultValue(0)
  for (m <- ms) {
    counts(m) += 1
  }

  var resBuilders = mutable.ArrayBuffer.empty[mutable.ArrayBuilder.ofInt]
  while (counts.nonEmpty) {
    resBuilders += new mutable.ArrayBuilder.ofInt
    var lim = Int.MaxValue
    val it = counts.iterator
    val updates = mutable.ArrayBuffer.empty[(Int, Int)]
    while (it.hasNext && lim > 0) {
      val (key, value) = it.next()
      lim = lim min cs(key - 1)
      val take = value min lim
      counts(key) -= take
      updates += ((key, value - take))
      var i = 0
      while (i < take) {
        resBuilders.last += key
        i += 1
      }
      lim -= take
    }
    for ((k, v) <- updates) {
      if (v == 0) {
        counts.remove(k)
      } else {
        counts(k) = v
      }
    }
  }

  val res = resBuilders.map(_.result())

  out.println(res.size)
  res.foreach { r =>
    out.print(r.length)
    out.println(r.mkString(" ", " ", ""))
  }

  out.flush()

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

object D extends App {
  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val mn          = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)
  val ck          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans = ck.reverse.zipWithIndex
    .foldLeft((mn, 0d, 0)) {
      case ((mn, g, b), (c, i)) =>
        val mm = mn.dropWhile(_ >= (k - i))
        val t  = g + mn.length - mm.length

        (mm, t, b.max((t / c).toInt))
    }
    ._3

  val kv = collection.mutable.Map.empty[Int, List[Int]]

  mn.zipWithIndex.foreach {
    case (m, i) =>
      val k = i % ans
      val v = m :: kv.getOrElse(k, Nil)

      kv += (k -> v)
  }

  println(ans)

  kv.foreach {
    case (_, vs) =>
      println(s"${vs.length} ${vs.mkString(" ")}")
  }
}

object D {
  import InOut._

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

  val n, k = nextInt
  val mn   = nextInts(n).sorted(Ordering.Int.reverse)
  val ck   = nextInts(k)

  val (ans, _, _) = ck.reverse.zipWithIndex
    .foldLeft((0, 0, 0d)) {
      case ((b, j, g), (c, i)) =>
        val t = mn.indexWhere(_ < (k - i), j)

        val h = g + (if (t < 0) n - j else t - j)

        (b max math.ceil(h / c).toInt, t, h)
    }

  val kv = collection.mutable.Map.empty[Int, List[Int]]

  mn.zipWithIndex.foreach {
    case (m, i) =>
      val k = i % ans
      val v = m :: kv.getOrElse(k, Nil)

      kv += (k -> v)
  }

  out.println(ans)
  kv.foreach {
    case (_, vs) =>
      out.println(s"${vs.length} ${vs.mkString(" ")}")
  }
  out.flush()

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

object D extends App {

  private def greater(mn: List[Int], k: Int): List[Int] = {
    @scala.annotation.tailrec
    def go(mn: List[Int], i: Int, gk: List[Int]): List[Int] =
      if (i == 0) gk
      else {
        val mm = mn.dropWhile(_ >= i)
        val g  = gk.head + (mn.length - mm.length)

        go(mm, i - 1, g :: gk)
      }

    go(mn, k, List(0))
  }

  private def boxes(ck: Seq[Int], gk: Seq[Int]): Int = {
    @scala.annotation.tailrec
    def go(ck: Seq[Int], gk: Seq[Int], b: Int): Int =
      ck match {
        case Seq() => b
        case _     => go(ck.tail, gk.tail, b.max(math.ceil(gk.head.toDouble / ck.head).toInt))
      }

    go(ck, gk, 0)
  }

  private def put(mn: List[Int], b: Int): collection.mutable.Map[Int, List[Int]] = {
    val kv = collection.mutable.Map.empty[Int, List[Int]]

    mn.zipWithIndex.foreach {
      case (m, i) =>
        val k = i % b
        val v = m :: kv.getOrElse(k, Nil)

        kv += (k -> v)
    }

    kv
  }

  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val mn          = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse).toList
  val ck          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val gk = greater(mn, k)

  println(s"gk: ${gk.mkString(" ")}")
  println(s"ck: ${ck.mkString(" ")}")

  val b = boxes(ck, gk)

  val ans = put(mn, b).values.toList

  println(ans.length)
  ans.foreach(t => println(s"${t.length} ${t.mkString(" ")}"))
}

object D {
  import InOut._

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

  val n, k = nextInt
  val mn   = nextInts(n)
  val ck   = nextInts(k)

  val ans = ck.reverse.zipWithIndex
    .foldLeft((mn, 0d, 0)) {
      case ((mn, g, b), (c, i)) =>
        val mm = mn.dropWhile(_ >= (k - i))
        val t  = g + mn.length - mm.length

        (mm, t, b.max(math.ceil(t / c.toInt).toInt))
    }
    ._3

  val kv = collection.mutable.Map.empty[Int, List[Int]]

  mn.zipWithIndex.foreach {
    case (m, i) =>
      val k = i % ans
      val v = m :: kv.getOrElse(k, Nil)

      kv += (k -> v)
  }

  out.println(ans)
  kv.foreach {
    case (_, vs) =>
      out.println(s"${vs.length} ${vs.mkString(" ")}")
  }
  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
  }
}


You have n devices that you want to use simultaneously.The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.

The first line contains two integers, n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 109) — the number of devices and the power of the charger. This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1 ≤ ai, bi ≤ 100 000) — the power of the device and the amount of power stored in the device in the beginning.

If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4. 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 sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough power to last this time without being charged.In sample test 2, you can use the device indefinitely.In sample test 3, we can charge the third device for 2 / 5 of a second, then switch to charge the second device for a 1 / 10 of a second.

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

  val Array(n, p) = readInts(2)
  val as, bs = Array.ofDim[Long](n)

  for (i <- 0 until n) {
    val Array(a, b) = readLongs(2)
    as(i) = a
    bs(i) = b
  }

  val aSum = as.sum

  def can(t: Double): Boolean = {
    var i = 0
    var sum = 0d
    while (i < n) {
      sum += Math.min(as(i) * t, bs(i))
      i += 1
    }
    (aSum - p) * t <= sum
  }

  @annotation.tailrec
  def binSearchD(lo: Double, hi: Double, depth: Int): Double = {
    val mid = (lo + hi) / 2
    if (depth > 130) mid
    else {
      if (can(mid)) binSearchD(mid, hi, depth + 1)
      else binSearchD(lo, mid, depth + 1)
    }
  }

  if (aSum <= p) println(-1)
  else {
    val res = binSearchD(0, Long.MaxValue, 0)

    println(res)
  }
}

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

  val Array(n, p) = readInts(2)
  val as, bs = Array.ofDim[Long](n)

  for (i <- 0 until n) {
    val Array(a, b) = readLongs(2)
    as(i) = a
    bs(i) = b
  }

  val aSum = as.sum

  def can(t: Double): Boolean = {
    var need = aSum * t
    var i = 0
    while (i < n) {
      need -= Math.min(as(i) * t, bs(i))
      i += 1
    }
    need <= t * p
  }

  @annotation.tailrec
  def binSearchD(lo: Double, hi: Double, depth: Int): Double = {
    val mid = (lo + hi) / 2
    if (hi - lo < 0.0001d) mid
    else {
      if (can(mid)) binSearchD(mid, hi, depth + 1)
      else binSearchD(lo, mid, depth + 1)
    }
  }

  if (aSum <= p) println(-1)
  else {
    val res = binSearchD(0, Long.MaxValue, 0)

    println(res)
  }
}

object A 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, p) = readInts(2)
  val as, bs = Array.ofDim[Long](n)

  for (i <- 0 until n) {
    val Array(a, b) = readLongs(2)
    as(i) = a
    bs(i) = b
  }

  val aSum = as.sum

  def can(t: Double): Boolean = {
    var need = aSum * t
    var i = 0
    while (i < n) {
      need -= Math.min(as(i) * t, bs(i))
      i += 1
    }
    need <= t * p
  }

  @annotation.tailrec
  def binSearchD(lo: Double, hi: Double, depth: Int): Double = {
    val mid = (lo + hi) / 2
    if (depth > 200) mid
    else {
      if (can(mid)) binSearchD(mid, hi, depth + 1)
      else binSearchD(lo, mid, depth + 1)
    }
  }

  if (aSum <= p) println(-1)
  else {
    val res = binSearchD(0, Long.MaxValue, 0)

    println(res)
  }
}


Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm  ×  h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.Leonid offers to divide the labor — he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?

The first line contains three integers w, h, n (2 ≤ w, h ≤ 200 000, 1 ≤ n ≤ 200 000). Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≤ y ≤ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≤ x ≤ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.

After each cut print on a single line the area of the maximum available glass fragment in mm2.

NotePicture for the first sample test:    Picture for the second sample test:

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

object C {

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val w = nextInt
    val h = nextInt
    val n = nextInt
    val hor = new TreeSet[Int]()
    val vert = new TreeSet[Int]()
    val hCuts = new MultiTreeSet[Integer]
    val vCuts = new MultiTreeSet[Integer]
    hCuts.add(h)
    vCuts.add(w)
    hor.add(0)
    hor.add(h)
    vert.add(0)
    vert.add(w)
    for (i <- 0 until n) {
      val dir = next.toCharArray.apply(0)
      if (dir == 'H') {
        val pos = h - nextInt
        val lo = hor.lower(pos)
        val hi = hor.higher(pos)
        hCuts.remove(hi - lo)
        hCuts.add(hi - pos)
        hCuts.add(pos - lo)
        hor.add(pos)
      } else {
        val pos = nextInt
        val lo = vert.lower(pos)
        val hi = vert.higher(pos)
        vCuts.remove(hi - lo)
        vCuts.add(hi - pos)
        vCuts.add(pos - lo)
        vert.add(pos)
      }
      out.println(vCuts.last().toLong * hCuts.last().toLong)
    }
    return 1
  }

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

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

object C {

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val w = nextInt
    val h = nextInt
    val n = nextInt
    val hor = new TreeSet[Int]()
    val vert = new TreeSet[Int]()
    val hCuts = new MultiTreeSet[Integer]
    val vCuts = new MultiTreeSet[Integer]
    hCuts.add(h)
    vCuts.add(w)
    hor.add(0)
    hor.add(h)
    vert.add(0)
    vert.add(w)
    for (i <- 0 until n) {
      val dir = next.toCharArray.apply(0)
      if (dir == 'H') {
        val pos = h - nextInt
        val lo = hor.lower(pos)
        val hi = hor.higher(pos)
        hCuts.remove(hi - lo)
        hCuts.add(hi - pos)
        hCuts.add(pos - lo)
        hor.add(pos)
      } else {
        val pos = nextInt
        val lo = vert.lower(pos)
        val hi = vert.higher(pos)
        vCuts.remove(hi - lo)
        vCuts.add(hi - pos)
        vCuts.add(pos - lo)
        vert.add(pos)
      }
      out.println(vCuts.last() * hCuts.last())
    }
    return 1
  }

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


You are given a set of $$$2n+1$$$ integer points on a Cartesian plane. Points are numbered from $$$0$$$ to $$$2n$$$ inclusive. Let $$$P_i$$$ be the $$$i$$$-th point. The $$$x$$$-coordinate of the point $$$P_i$$$ equals $$$i$$$. The $$$y$$$-coordinate of the point $$$P_i$$$ equals zero (initially). Thus, initially $$$P_i=(i,0)$$$.The given points are vertices of a plot of a piecewise function. The $$$j$$$-th piece of the function is the segment $$$P_{j}P_{j + 1}$$$.In one move you can increase the $$$y$$$-coordinate of any point with odd $$$x$$$-coordinate (i.e. such points are $$$P_1, P_3, \dots, P_{2n-1}$$$) by $$$1$$$. Note that the corresponding segments also change.For example, the following plot shows a function for $$$n=3$$$ (i.e. number of points is $$$2\cdot3+1=7$$$) in which we increased the $$$y$$$-coordinate of the point $$$P_1$$$ three times and $$$y$$$-coordinate of the point $$$P_5$$$ one time:  Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum $$$y$$$-coordinate among all initial points in the plot (i.e. points $$$P_0, P_1, \dots, P_{2n}$$$). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of $$$2n+1$$$ vertices and having an area equal to $$$k$$$. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^{18}$$$) — the number of vertices in a plot of a piecewise function and the area we need to obtain.

Print one integer — the minimum possible height of a plot consisting of $$$2n+1$$$ vertices and with an area equals $$$k$$$. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.

NoteOne of the possible answers to the first example:  The area of this plot is 3, the height of this plot is 1.There is only one possible answer to the second example:  The area of this plot is 12, the height of this plot is 3.

import scala.io.StdIn

object Problem1036a {
  def main(args: Array[String]): Unit = {
    val vals = StdIn.readLine().split(" ").map(_.toLong)
    val n = vals(0)
    val k = vals(1)

    println(solve(n, k))
  }

  def solve(n: Long, k: Long): Long = {
    (k - 1) / n + 1
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = nl()
    val x = (K - 1) / N + 1

    out.println(x)
  }

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

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

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

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

object Main {
import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = ins.nextLong
        val k = ins.nextLong
        println((k + n - 1)/n)
    }

  }

}

import scala.io.StdIn

object Problem1036a {
  def main(args: Array[String]): Unit = {
    val vals = StdIn.readLine().split(" ").map(_.toInt)
    val n = vals(0)
    val k = vals(1)
    println(k / n)
  }
}


Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.  There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.  Masculine adjectives end with -lios, and feminine adjectives end with -liala.  Masculine nouns end with -etr, and feminime nouns end with -etra.  Masculine verbs end with -initis, and feminime verbs end with -inites.  Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.  It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.  There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.  A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.  All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.

The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.

If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).

petr
etis atis animatis etis atis amatis
nataliala kataliala vetra feinites

import scala.util.parsing.combinator._

object CF114B extends RegexParsers {
  def maleStatement = rep(maleAdj) ~> maleNoun <~ rep(maleVerb)
  def femaleStatement = rep(femaleAdj) ~> femaleNoun <~ rep(femaleVerb)

  def word = maleAdj | maleNoun | maleVerb | femaleAdj | femaleNoun | femaleVerb
  def maleAdj = """\w*lios""".r
  def maleNoun = """\w*etr""".r
  def maleVerb = """\w*initis""".r
  def femaleAdj = """\w*liala""".r
  def femaleNoun = """\w*etra""".r
  def femaleVerb = """\w*inites""".r

  def main(args: Array[String]) {
    val s = readLine
    val success = List(maleStatement, femaleStatement, word) exists (rule => parseAll(rule, s).successful)
    println(if (success) "YES" else "NO")
  }
}

import scala.util.parsing.combinator._

object CF114B extends RegexParsers {
  def maleStatement = rep(maleAdj) ~> maleNoun <~ rep(maleVerb)
  def femaleStatement = rep(femaleAdj) ~> femaleNoun <~ rep(femaleVerb)

  def word = maleAdj | maleNoun | maleVerb | femaleAdj | femaleNoun | femaleVerb
  def maleAdj = ".*lios".r
  def maleNoun = ".*etr".r
  def maleVerb = ".*initis".r
  def femaleAdj = ".*liala".r
  def femaleNoun = ".*etra".r
  def femaleVerb = ".*inites".r

  def main(args: Array[String]) {
    val s = readLine
    val success = List(maleStatement, femaleStatement, word) exists (rule => parseAll(rule, s).successful)
    println(if (success) "YES" else "NO")
  }
}

import scala.util.parsing.combinator._

object CF114B extends RegexParsers {
  def maleStatement = rep(maleAdj) ~> maleNoun <~ rep(maleVerb)
  def femaleStatement = rep(femaleAdj) ~> femaleNoun <~ rep(femaleVerb)

  def maleAdj = ".*lios".r
  def maleNoun = ".*etr".r
  def maleVerb = ".*initis".r
  def femaleAdj = ".*liala".r
  def femaleNoun = ".*etra".r
  def femaleVerb = ".*inites".r

  def main(args: Array[String]) {
    val s = readLine
    val success = parseAll(maleStatement, s).successful || parseAll(femaleStatement, s).successful
    println(if (success) "YES" else "NO")
  }
}


Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps:  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \le h_C \le 10^{15}$$$; $$$1 \le d_C \le 10^9$$$) — the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \le h_M \le 10^{15}$$$; $$$1 \le d_M \le 10^9$$$) — the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \le k \le 2 \cdot 10^5$$$; $$$0 \le w \le 10^4$$$; $$$0 \le a \le 10^{10}$$$) — the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.

NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor.

object KillTheMonsters extends App {
def count(hc: Long, dc: Long, hm: Long, dm: Long, k: Long, w: Long, a: Long): String =
    if ((0L to k).exists{ na => (1.0 * hm / (dc + na * w)).ceil <= (1.0 * (hc + (k - na) * a) / dm).ceil }) "YES" else "NO"

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach{_ =>
    val fl = lines.next.split(" ")
    val hc = fl(0).toLong
    val dc = fl(1).toLong
    val sl = lines.next.split(" ")
    val hm = sl(0).toLong
    val dm = sl(1).toLong
    val tl = lines.next.split(" ")
    val k = tl(0).toLong
    val w = tl(1).toLong
    val a = tl(2).toLong
    println(count(hc, dc, hm, dm, k, w, a))
  }
}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.math._, BigDecimal._

object cf1633c {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var Array(hC, dC) = readLine.split(" ").map(BigInt(_))
      var Array(hM, dM) = readLine.split(" ").map(BigInt(_))
      var Array(k, w, a) = readLine.split(" ").map(BigInt(_))
      var possible = false
      for(K <- BigInt(0) to k) {
        if(check(hC + K * a, dC + (k - K) * w, hM, dM)) {
          possible = true
        }
      }
      if(possible == true) {
        println("YES")
      }
      else {
        println("NO")
      }
    }
  }

  def check(hC: BigInt, dC: BigInt, hM: BigInt, dM: BigInt): Boolean = {
    var req_t = (BigDecimal(hM) / BigDecimal(dC)).setScale(0, RoundingMode.CEILING)
    if(BigDecimal(hC) > BigDecimal(dM) * (req_t - 1)) {
      return true
    }
    return false
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(characterHealth, characterDamage) = readLongs().map(BigInt(_))
    val Array(monsterHealth, monsterDamage) = readLongs().map(BigInt(_))
    val Array(coins, weaponBonus, armourBonus) = readLongs().map(BigInt(_))

    def remainingLifeWithBonuses(weaponCoins: BigInt): BigInt =
      remainingLife(
        characterHealth + (coins - weaponCoins) * armourBonus,
        characterDamage + weaponCoins * weaponBonus
      )

    def remainingLife(characterHealth: BigInt, characterDamage: BigInt): BigInt = {
      val roundNumber = (monsterHealth-1) / characterDamage + 1
      val answer = characterHealth - (roundNumber - 1) * monsterDamage
      answer
    }

    val answer = 0.to(coins.toInt).map(c => remainingLifeWithBonuses(c) > 0).reduce(_ || _)
    if (answer) println("YES") else println("NO")

  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

object KillTheMonsters extends App {
  def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =
    if ((0 to k).exists(na => hm / (dc + na * w) - 1 < (hc + (k - na) * a) / dm)) "YES" else "NO"

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach{_ =>
    val fl = lines.next.split(" ")
    val hc = fl(0).toInt
    val dc = fl(1).toInt
    val sl = lines.next.split(" ")
    val hm = sl(0).toInt
    val dm = sl(1).toInt
    val tl = lines.next.split(" ")
    val k = tl(0).toInt
    val w = tl(1).toInt
    val a = tl(2).toInt
    println(count(hc, dc, hm, dm, k, w, a))
  }
}

object KillTheMonsters extends App {
  def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =
    if ((0 to k).exists(na => hm / (dc + na * w) < 1 + (hc + (k - na) * a) / dm)) "YES" else "NO"

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach{_ =>
    val fl = lines.next.split(" ")
    val hc = fl(0).toInt
    val dc = fl(1).toInt
    val sl = lines.next.split(" ")
    val hm = sl(0).toInt
    val dm = sl(1).toInt
    val tl = lines.next.split(" ")
    val k = tl(0).toInt
    val w = tl(1).toInt
    val a = tl(2).toInt
    println(count(hc, dc, hm, dm, k, w, a))
  }
}

object KillTheMonsters extends App {
  def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =
    if ((0 to k).exists(na => hm / (dc + na * w) + 1 <= (hc + (k - na) * a) / dm)) "YES" else "NO"

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach{_ =>
    val fl = lines.next.split(" ")
    val hc = fl(0).toInt
    val dc = fl(1).toInt
    val sl = lines.next.split(" ")
    val hm = sl(0).toInt
    val dm = sl(1).toInt
    val tl = lines.next.split(" ")
    val k = tl(0).toInt
    val w = tl(1).toInt
    val a = tl(2).toInt
    println(count(hc, dc, hm, dm, k, w, a))
  }
}

object KillTheMonsters extends App {
  def count(hc: Int, dc: Int, hm: Int, dm: Int, k: Int, w: Int, a: Int): String =
    if ((0 to k).exists(na => hm / (dc + na * w) <= (hc + (k - na) * a) / dm)) "YES" else "NO"

  val lines = io.Source.stdin.getLines
  val t = lines.next.toInt
  (1 to t).foreach{_ =>
    val fl = lines.next.split(" ")
    val hc = fl(0).toInt
    val dc = fl(1).toInt
    val sl = lines.next.split(" ")
    val hm = sl(0).toInt
    val dm = sl(1).toInt
    val tl = lines.next.split(" ")
    val k = tl(0).toInt
    val w = tl(1).toInt
    val a = tl(2).toInt
    println(count(hc, dc, hm, dm, k, w, a))
  }
}

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

object cf1633c {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    while(t > 0) {
      t -= 1
      var Array(hC, dC) = readLine.split(" ").map(BigInt(_))
      var Array(hM, dM) = readLine.split(" ").map(BigInt(_))
      var Array(k, w, a) = readLine.split(" ").map(BigInt(_))
      var possible = false
      for(K <- BigInt(0) to k) {
        if(check(hC + K * a, dC + (k - K) * w, hM, dM)) {
          possible = true
        }
      }
      if(possible == true) {
        println("YES")
      }
      else {
        println("NO")
      }
    }
  }

  def check(hC: BigInt, dC: BigInt, hM: BigInt, dM: BigInt): Boolean = {
    var req_t = (hM.toFloat / dC.toFloat).ceil
    if(hC.toFloat > dM.toFloat * (req_t - 1)) {
      return true
    }
    return false
  }
}

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

object cf1633c {
  def main(args: Array[String]): Unit = {
    var t = readInt()
    println(t)
    while(t > 0) {
      t -= 1
      var Array(hC, dC) = readLine().split(" ").map(_.toInt)
      var Array(hM, dM) = readLine().split(" ").map(_.toInt)
      var Array(k, w, a) = readLine().split(" ").map(_.toInt)
      var possible = false
      for(K <- 0 to k) {
        println(K)
        if(check(hC + K * a, dC + (k - K) * w, hM, dM)) {
          possible = true
        }
      }
      if(possible == true) {
        println("YES")
      }
      else {
        println("NO")
      }

    }
  }

  def check(hC: Int, dC: Int, hM: Int, dM: Int): Boolean = {
    var req_t = (hM*1.0 / dC).ceil
    if(hC > dM * (req_t - 1)) {
      return true
    }
    return false
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(characterHealth, characterDamage) = readLongs().map(BigInt(_))
    val Array(monsterHealth, monsterDamage) = readLongs().map(BigInt(_))
    val Array(coins, weaponBonus, armourBonus) = readLongs().map(BigInt(_))

    def remainingLifeWithBonuses(weaponCoins: BigInt): BigInt =
      remainingLife(
        characterHealth + (coins - weaponCoins) * armourBonus,
        characterDamage + weaponCoins * weaponBonus
      )

    def remainingLife(characterHealth: BigInt, characterDamage: BigInt): BigInt = {
      val roundNumber = (monsterHealth-1) / characterDamage + 1
      val answer = characterHealth - (roundNumber - 1) * monsterDamage
      answer
    }

    def search(l: BigInt, r: BigInt): Boolean =
      if (r - l <= 1) remainingLifeWithBonuses(l) > 0 || remainingLifeWithBonuses(r) > 0
      else {
        val medium = (r + l) / 2
        if (remainingLifeWithBonuses(medium - 1) > remainingLifeWithBonuses(medium + 1)) {
          search(l, medium)
        } else {
          search(medium, r)
        }
      }

    val answer = search(0, coins)
    if (answer) println("YES") else println("NO")

  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(characterHealth, characterDamage) = readLongs()
    val Array(monsterHealth, monsterDamage) = readLongs()
    val Array(coins, weaponBonus, armourBonus) = readLongs()

    def remainingLifeWithBonuses(weaponCoins: Long): Long =
      remainingLife(
        characterHealth + (coins - weaponCoins) * armourBonus,
        characterDamage + weaponCoins * weaponBonus
      )

    def remainingLife(characterHealth: Long, characterDamage: Long): Long = {
      val roundNumber = (monsterHealth-1) / characterDamage + 1
      val answer = characterHealth - (roundNumber - 1) * monsterDamage
      answer
    }

    def search(l: Long, r: Long): Boolean =
      if (r - l <= 1) remainingLifeWithBonuses(l) > 0 || remainingLifeWithBonuses(r) > 0
      else {
        val medium = (r + l) / 2
        if (remainingLifeWithBonuses(medium - 1) > remainingLifeWithBonuses(medium + 1)) {
          search(l, medium)
        } else {
          search(medium, r)
        }
      }

    val answer = search(0, coins)
    if (answer) println("YES") else println("NO")

  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.

The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.

If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).

NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.

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

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CVK17A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 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
  }
}

class CVK17A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()

    g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int]())

    REP(m) { _ =>
      val u = ni()
      val v = ni()

      g(u-1) += v-1
      g(v-1) += u-1
    }

    marked = Array.fill[Int](n)(-1)
    var id = 0
    var yes = true
    var prev = 0
    REP(n) { i =>
     if(marked(i) == -1) {
       marked(i) = id
       counter +=1
       val x = countEdges(i)
       val y = (counter - prev).toLong
//       out.println(i + " " + x + " " + y + " " + i + " " + (y * (y-1)))
       yes = yes & (x == (y * (y-1)))
       id += 1
       prev = counter
     }
    }
    if(yes) {
      out.println("YES")
    } else out.println("NO")
  }

  var g: Array[ListBuffer[Int]] = _
  var marked: Array[Int] = _
  var counter = 0

  def countEdges(u: Int): Long = {
    var stack = List.empty[Int]
    stack = u :: stack
    var count = 0L
    while (stack.nonEmpty) {
      val v = stack.head
      stack = stack.drop(1)
      count += g(v).size
      g(v).foreach { f =>
        if (marked(f) == -1) {
          marked(f) = marked(v)
          counter += 1
          stack = f :: stack
        }
      }
    }
    count
  }
}

//package solutions

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

import scala.util.control.Breaks

/**
  * @author traff
  */

object SolTaskB extends App {
  override def main(args: Array[String]): Unit = {
    val out = new PrintWriter(System.out)

    run(new Scanner(System.in), out)

    out.close()
  }

  def run(s: Scanner, out: PrintWriter): Unit = {
    val n = s.nextInt()
    val m = s.nextInt()

    var t: Array[Int] = (0 until n).toArray

    var rank: Array[Int] = Array.fill(n)(1)

    def find(i: Int): Int = {
      if (i == t(i)) {
        i
      } else {
        t(i) = find(t(i))
        t(i)
      }
    }

    def union(i: Int, j: Int): Unit = {
      if (rank(i) > rank(j)) {
        t(i) = t(j)
        rank(i) += rank(j)
      } else {
        t(j) = t(i)
        rank(j) += rank(i)
      }
    }

    val c = Array.fill(n + 1)(0)

    for (i <- 1 to m) {
      var a = s.nextInt()
      var b = s.nextInt()

      if (b > a) {
        val t = a
        a = b
        b = t
      }

      if (find(a - 1) != find(b - 1)) {
        union(find(a - 1), find(b - 1))
      }

      c(a) += 1
      c(b) += 1
    }

    var cnt = Array.fill(n)(0)

    for (i <- 1 to n) {
      cnt(find(i-1)) += 1
    }

    Breaks.breakable {
      for (i <- 1 to n) {
        if (c(i) != (cnt(find(i-1)) - 1)) {
          out.write("NO")
          Breaks.break()
        }
      }

      out.write("YES")
    }
  }
}

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

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CVK17A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 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
  }
}

class CVK17A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()

    g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int]())

    REP(m) { _ =>
      val u = ni()
      val v = ni()

      g(u-1) += v-1
      g(v-1) += u-1
    }

    marked = Array.fill[Int](n)(-1)
    var id = 0
    var yes = true
    var prev = 0
    REP(n) { i =>
     if(marked(i) == -1) {
       marked(i) = id
       counter +=1
       val x = countEdges(i)
       val y = (counter - prev).toLong
//       out.println(x + " " + y + " " + i + " " + (y * (y-1)))
       yes = yes & (x == (y * (y-1)))
       id += 1
       prev = counter
     }
    }
    if(yes) {
      out.println("YES")
    } else out.println("NO")
  }

  var g: Array[ListBuffer[Int]] = _
  var marked: Array[Int] = _
  var counter = 0

  def countEdges(u: Int): Long = {
    var stack = List.empty[Int]
    stack = u :: stack
    var count = 0L
    while (stack.nonEmpty) {
      val v = stack.head
      stack = stack.drop(1)
      count += g(u).size
      g(v).foreach { f =>
        if (marked(f) == -1) {
          marked(f) = marked(v)
          counter += 1
          stack = f :: stack
        }
      }
    }
    count
  }
}

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

import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CVK17A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 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
  }
}

class CVK17A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()

    g = Array.fill[ListBuffer[Int]](n)(new ListBuffer[Int]())

    REP(m) { _ =>
      val u = ni()
      val v = ni()

      g(u-1) += v-1
      g(v-1) += u-1
    }

    marked = Array.fill[Int](n)(-1)
    var id = 0
    var yes = true
    var prev = 0
    REP(n) { i =>
     if(marked(i) == -1) {
       marked(i) = id
       counter +=1
       val x = countEdges(i)
       val y = counter - prev
//       out.println(x + " " + y + " " + i + " " + (y * (y-1)))
       yes = yes & (x == (y * (y-1)))
       id += 1
       prev = counter
     }
    }
    if(yes) {
      out.println("YES")
    } else out.println("NO")
  }

  var g: Array[ListBuffer[Int]] = _
  var marked: Array[Int] = _
  var counter = 0

  def countEdges(u: Int): Int = {
    var count = g(u).size
    g(u).foreach { f =>
      if(marked(f) == -1) {
        counter += 1
        marked(f) = marked(u)
       count += countEdges(f)
      }
    }
    count
  }
}


Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string $$$s$$$, you have to delete minimum number of characters from this string so that it becomes good.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

In the first line, print one integer $$$k$$$ ($$$0 \le k \le n$$$) — the minimum number of characters you have to delete from $$$s$$$ to make it good. In the second line, print the resulting string $$$s$$$. If it is empty, you may leave the second line blank, or not print it at all.

import java.util.Scanner

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

object Ctask560 extends App {
  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()

  line = new Scanner(StdIn.readLine())
  val word = line.next.chars().toArray

  var click = 1
  var amount = 0
  var result = new ArrayBuffer[Char]()
  for (i <- 0 until n) {
    if ((i + click) % 2 == 1) {
      if (i + 1 != n && word(i) != word(i + 1)) {
        result.append(word(i).toChar)
      } else {
        amount += 1
        click += 1
      }
    } else {
      result.append(word(i).toChar)
    }
  }
  if (result.length() % 2 == 1) {
    result.remove(result.length() - 1)
    amount += 1
  }
  println(amount)
  println(result.mkString(""))
}

import java.util.Scanner

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

object Ctask560 extends App {
  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()

  line = new Scanner(StdIn.readLine())
  val word = line.next.chars().toArray

  var click = 1
  var amount = 0
  var result = new ArrayBuffer[Char]()
  for (i <- 0 until n) {
    if (i + click % 2 == 1) {
      if (i + 1 != n && word(i) != word(i + 1)) {
        result.append(word(i).toChar)
      } else {
        amount += 1
        click += 1
      }
    } else {
      result.append(word(i).toChar)
    }
  }
  if (result.length() % 2 == 1) {
    result.remove(result.length() - 1)
    amount += 1
  }
  println(amount)
  println(result.mkString(""))
}