A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.

The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'.  It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.

For each test case given in the input print the answer in the following format:   If it is impossible to create a beautiful string, print "-1" (without quotes);  Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.

NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".

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

  override def solve(io: IO) = io.repeat {
    val s = ('?' + io.read[String] + '?').toCharArray

    for (i <- 1 until s.length-1 if s(i) == '?') {
      s(i) = "abc".find(c => c != s(i-1) && c != s(i+1)).head
    }
    val ans = s.tail.init.mkString

    if (ans.sliding(2).exists(s => s.length == 2 && s.head == s.last))
      io.write(-1)
    else
      io.write(s.tail.init.mkString)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn

object A_1265 extends App {

  def isGood(line: Array[Char]): String = {
    line.indices foreach { i =>
      if (line(i) != '?') {
        val prev = if (i > 0) Some(line(i - 1)) else None
        if (prev.nonEmpty && prev.get == line(i)) return ""
      }
      else {
        val prev = if (i > 0) Some(line(i - 1)) else None
        val next = if (i < line.length - 1) Some(line(i + 1)) else None
        val good = List('a', 'b', 'c').filterNot(x => List(prev.getOrElse('?'), next.getOrElse('?')).contains(x))
        line(i) = good.head
      }
    }

    line.mkString
  }

  val n = StdIn.readInt()
  1 to n foreach { _ =>
    val line = StdIn.readLine().toCharArray
    val answer = isGood(line)
    if (answer == "") println(-1) else println(answer)
  }
}


One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y ≤ 2·x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.

The first line contains integer n (2 ≤ n ≤ 105) — the number of measurements Vasya made. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 5000) — the results of the measurements. The numbers on the second line are separated by single spaces.

Print a single integer — the minimum number of results Vasya will have to remove.

NoteIn the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will be 4.

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
	//val in=new Scanner(System.in)
    //val out=new PrintWriter(System.out)
    val n=in.nextLine.toInt
    val a=in.nextLine.split(" ").map(_.toInt)

    val dp=new Array[Int](5001)
	a.foreach{i=> dp(i)+=1}
	var min=Int.MaxValue
	1 to 5000 foreach{i=>
		var sum=0
		1 to 5000 foreach{j=>
			if(j<i || j>2*i) sum+=dp(j)
		}
		min=Math.min(min,sum)
	}

	out.println(min)
    out.close
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
    val n=in.nextLine.toInt
    val a=in.nextLine.split(" ").map(_.toInt)

    val (min,max)=(a.min,a.max)
    out.println(math.min(a.count(_*2<max), a.count(_>2*min)))
    out.close
}

import java.io.PrintWriter
import java.io.File
import java.util.Scanner
import collection.mutable.ArrayBuffer

object test2 extends App {
	val in=new Scanner(new File("input.txt"))
	val out=new PrintWriter("output.txt")
    val n=in.nextInt
    val a=in.next.split(" ").map(_.toInt)

    val (min,max)=(a.min,a.max)
    out.println(math.min(a.count(_*2<max), a.count(_>2*min)))
    out.close
}


Timur has a stairway with $$$n$$$ steps. The $$$i$$$-th step is $$$a_i$$$ meters higher than its predecessor. The first step is $$$a_1$$$ meters higher than the ground, and the ground starts at $$$0$$$ meters.   The stairs for the first test case. Timur has $$$q$$$ questions, each denoted by an integer $$$k_1, \dots, k_q$$$. For each question $$$k_i$$$, you have to print the maximum possible height Timur can achieve by climbing the steps if his legs are of length $$$k_i$$$. Timur can only climb the $$$j$$$-th step if his legs are of length at least $$$a_j$$$. In other words, $$$k_i \geq a_j$$$ for each step $$$j$$$ climbed.Note that you should answer each question independently.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n, q$$$ ($$$1 \leq n, q \leq 2\cdot10^5$$$) — the number of steps and the number of questions, respectively. The second line of each test case contains $$$n$$$ integers ($$$1 \leq a_i \leq 10^9$$$) — the height of the steps. The third line of each test case contains $$$q$$$ integers ($$$0 \leq k_i \leq 10^9$$$) — the numbers for each question. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2\cdot10^5$$$, and the sum of $$$q$$$ does not exceed $$$2\cdot10^5$$$.

For each test case, output a single line containing $$$q$$$ integers, the answer for each question. Please note, that the answer for some questions won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

NoteConsider the first test case, pictured in the statement.   If Timur's legs have length $$$1$$$, then he can only climb stair $$$1$$$, so the highest he can reach is $$$1$$$ meter.  If Timur's legs have length $$$2$$$ or $$$4$$$, then he can only climb stairs $$$1$$$, $$$2$$$, and $$$3$$$, so the highest he can reach is $$$1+2+1=4$$$ meters.  If Timur's legs have length $$$9$$$ or $$$10$$$, then he can climb the whole staircase, so the highest he can reach is $$$1+2+1+5=9$$$ meters.  In the first question of the second test case, Timur has no legs, so he cannot go up even a single step. :(

object Scuza {

    def upperBound(lst: Array[Long], x: Long): Int = {
        def upperBoundHelp (lst: Array[Long], x: Long, begin: Int, end: Int): Int = {
            // printf("%d %d %d\n", x, begin, end)
            if (begin == end) return begin
            if (lst(begin) > x) return begin
            var mid = (end-begin+1)/2+begin
            // printf ("!%d %d %d\n", mid, lst(mid), x)
            if (lst(mid)<=x) upperBoundHelp(lst, x, mid+1, end)
            else upperBoundHelp(lst, x, begin+1, mid)
        }
        upperBoundHelp(lst, x, 0, lst.length-1)
    }

    def solve_test() = {
        val Array(n, q) = scala.io.StdIn.readLine().split(' ').map(_.toInt)
        var steps = scala.io.StdIn.readLine().split(' ').map(_.toLong) :+ 1000000010L
        var questions = scala.io.StdIn.readLine().split(' ').map(_.toLong)
        var steps_heights = steps.foldLeft(List(0L))((acc, x) => x.max(acc.head) :: acc).reverse.toArray
        var steps_sum = steps.foldLeft(List(0L))((acc, x) => (x + acc.head) :: acc).reverse.toArray
        // for (i <- steps_heights) printf ("%d ", i)
        // printf ("\n")
        var lst = questions.map(x => upperBound(steps_heights, x)).map(x => steps_sum(x-1))
        for (i <- lst) printf ("%d ", i)
        printf ("\n")

    }

    def main(args: Array[String]): Unit = {
        val test = scala.io.StdIn.readInt()
        for (i <- 0 until test) solve_test()
    }
}


JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.First, he splits the Banh-mi into $$$n$$$ parts, places them on a row and numbers them from $$$1$$$ through $$$n$$$. For each part $$$i$$$, he defines the deliciousness of the part as $$$x_i \in \{0, 1\}$$$. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the $$$i$$$-th part then his enjoyment of the Banh-mi will increase by $$$x_i$$$ and the deliciousness of all the remaining parts will also increase by $$$x_i$$$. The initial enjoyment of JATC is equal to $$$0$$$.For example, suppose the deliciousness of $$$3$$$ parts are $$$[0, 1, 0]$$$. If JATC eats the second part then his enjoyment will become $$$1$$$ and the deliciousness of remaining parts will become $$$[1, \_, 1]$$$. Next, if he eats the first part then his enjoyment will become $$$2$$$ and the remaining parts will become $$$[\_, \_, 2]$$$. After eating the last part, JATC's enjoyment will become $$$4$$$.However, JATC doesn't want to eat all the parts but to save some for later. He gives you $$$q$$$ queries, each of them consisting of two integers $$$l_i$$$ and $$$r_i$$$. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range $$$[l_i, r_i]$$$ in some order.All the queries are independent of each other. Since the answer to the query could be very large, print it modulo $$$10^9+7$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 100\,000$$$). The second line contains a string of $$$n$$$ characters, each character is either '0' or '1'. The $$$i$$$-th character defines the deliciousness of the $$$i$$$-th part. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the segment of the corresponding query.

Print $$$q$$$ lines, where $$$i$$$-th of them contains a single integer — the answer to the $$$i$$$-th query modulo $$$10^9 + 7$$$.

NoteIn the first example:   For query $$$1$$$: One of the best ways for JATC to eats those parts is in this order: $$$1$$$, $$$4$$$, $$$3$$$, $$$2$$$.  For query $$$2$$$: Both $$$3$$$, $$$4$$$ and $$$4$$$, $$$3$$$ ordering give the same answer. In the second example, any order of eating parts leads to the same answer.

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)

  val pow2 = Array.ofDim[Long](100010)
  pow2(0) = 1
  rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)

  def solve(): Unit = {
    val N, Q = ni()
    val A = ns(N) map (_ - '0')
    val cum = cumSum(A)

    def calc(n: Int, ones: Int): Long = {
      if (ones == 0) 0
      else {
        val a = (MOD + pow2(ones) - 1) % MOD
        (a + a * (MOD + pow2(n - ones) - 1)) % MOD
      }
    }

    rep(Q) { _ =>
      val l, r = ni()
      val ans = calc(r - l + 1, cum(r) - cum(l - 1))
      out.println(ans)
    }
  }

  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, 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 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]) = {
    val cum = Array.ofDim[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.

The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100).

Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.

import java.util.Scanner

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

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

  val x = numbers.zipWithIndex.filter(_._2 % 3 == 0).map(_._1).toList.foldLeft(0)(_ + _)
  val y = numbers.zipWithIndex.filter(_._2 % 3 == 1).map(_._1).toList.foldLeft(0)(_ + _)
  val z = numbers.zipWithIndex.filter(_._2 % 3 == 2).map(_._1).toList.foldLeft(0)(_ + _)

  println(if (x == 0 && y == 0 && z == 0) "YES" else "NO" )
  }
}

object YoungPhysicist extends App {

    val nInput = scala.io.StdIn.readInt()
    var sumX = 0
    var sumY = 0
    var sumZ = 0

    for (i <- 1 to nInput) {
        val forces = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        sumX += forces(0)
        sumY += forces(1)
        sumZ += forces(2)
    }

    if (sumX == 0 && sumY == 0 && sumZ == 0) println("YES")
    else println("NO")
}

object CF0069A extends App {

  val n = readInt()

  var x = 0
  var y = 0
  var z = 0

  (1 to n).foreach(n => {
    var Array(x1, y1, z1) =readLine().split(" ").map(_.toInt)
    x = x + x1
    y += y1
    z += z1
  })

  if(x == 0 && y == 0 && z == 0) {
    println("YES")
  } else {
    println("NO")
  }

}

import scala.io.StdIn

object Task {

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

    val n: Int = StdIn.readInt()
    var v3: Vector3 = new Vector3(0, 0, 0)
    for (i <- 1 to n) {
      var xyz: Array[Int] = StdIn.readLine().split(" ").map(_.toInt)
      v3.add(xyz(0), xyz(1), xyz(2))
    }
    if (v3.isZero()) {
      println("YES")
    }
    else {
      println("NO")
    }

  }

}

class Vector3(val xc: Int, val yc: Int, val zc: Int) {
  var x: Int = xc
  var y: Int = yc
  var z: Int = zc

  def add(xa: Int, ya: Int, za: Int): Unit = {
    x += xa
    y += ya
    z += za
  }

  def isZero(): Boolean = {
    if (x == 0 && y == 0 && z == 0) {
      return true
    }
  return false
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).foldLeft(List(0, 0, 0)){
    case(List(a, b, c), _) =>
    val dd = in.next().split(" ").map(_.toInt)
    List(a + dd(0), b + dd(1), c + dd(2))
  }.forall(_ == 0)
  if (data) println("YES")
  else println("NO")
}

object Main {

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

    val n = std.readLine().toInt

    val v = Array[Int](0,0,0)
    for (i <- 0 until n) {
      val value = std.readLine().split(' ').map(_.toInt)
      for (j <- 0 until 3) {
        v(j) += value(j)
      }
    }

    if (v.exists(x => x != 0)) {
      println("NO")
    }
    else {
      println("YES")
    }
  }
}

object A69 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(3))
    val res = input.foldLeft(Array(0, 0, 0)){case (arr1, arr2) =>
      arr1.zip(arr2).map{case (a, b) => a+b}
    }
    if(res.sameElements(Array(0, 0, 0))) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

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

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

  val N = sc.nextInt
  val coordinates = Array.fill(N, 3)(sc.nextInt)

  val isEquilibrium = (0 until 3).forall { i =>
    { for (j <- 0 until N) yield coordinates(j)(i) }.sum == 0
  }

  val answer = if (isEquilibrium) "YES" else "NO"

  out.println(answer)
  out.close
}

object  YoungPhysicist {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
		var accX = 0;
		var accY = 0;
		var accZ = 0;
		for (i <- 1 to n) {
			val x = scanner.nextInt();
			val y = scanner.nextInt();
			val z = scanner.nextInt();
			accX += x;
			accY += y;
			accZ += z
		}
		if (accX == 0 && accY == 0 && accZ == 0) {
		  println("YES")
		}
		else {
		  println("NO")
		}
		System.exit(0)
	}
}

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

  val n = readInt()
  val force = (0 until n).foldLeft((0, 0, 0)) {
    case ((sx, sy, sz), _) =>
      val Array(x, y, z) = readLine().split(" ").map(_.toInt)
      (sx + x, sy + y, sz + z)
  }

  val ans = force match {
    case (0, 0, 0) => "YES"
    case _         => "NO"
  }

  println(ans)
}

import java.io._
import scala.annotation.tailrec

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

  def ans = (for(_ <- 1 to readInt) yield readInts).transpose.map(_.sum).forall(_ == 0)

  def main(a: Array[String]) {
    println(if(ans) "YES" else "NO")
  }
}

import scala.Predef._

object Main {
  case class Vector(x: Int, y: Int, z: Int) {
    def + (that: Vector) = Vector(this.x + that.x, this.y + that.y, this.z + that.z)
    def isZero = (x == 0) & (y == 0) & (z == 0)
  }

  object Vector {
    def read() = {
      val a = readLine().split(" ").map(_.toInt)
      Vector(a(0), a(1), a(2))
    }
  }

  def main(args: Array[String]) {
    val num = readInt
    val r = (1 to num).foldLeft(Vector(0, 0, 0)) { (acc, unused) => acc + Vector.read() }
    if (r.isZero) println("YES")
    else println("NO")
  }
}

import scala.io.StdIn._

object A_69 extends App {
  val n = readInt()
  val A = Array.ofDim[Int](n, 3)

  0 until n foreach { i =>
    A(i) = readLine().split(" ").map(_.toInt)
  }

  def hasEqulibrium(): Boolean = {
    0 until 3 foreach { col =>
      var counter = 0
      0 until n foreach { row =>
        counter += A(row)(col)
      }
      if (counter != 0) return false
    }

    true
  }

  if (hasEqulibrium()) println("YES")
  else println("NO")

}

import java.util.Scanner

object HelloWorldMain {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    var x1 = 0
    var x2 = 0
    var x3 = 0
    for(i <- 1 to n){
      x1 += sc.nextInt()
      x2 += sc.nextInt()
      x3 += sc.nextInt()
    }

    if(x1==0 && x2 ==0 && x3==0) println("YES")
    else println("NO")
  }
}

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

object YoungPhyscist {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)
   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }

   def main(args: Array[String]) {
     val n = readInt
     val forces = for {
       i <- 1 to n
       force = readTriple
     } yield force
     forces.foldLeft((0,0,0)){ case ((x1,y1,z1),(x2,y2,z2)) => (x1+x2,y1+y2,z1+z2)} match {
       case (0,0,0) => println("YES")
       case _       => println("NO")
     }

   }

}

import java.util.Scanner

object TEST extends App{
    val sc = new Scanner(System.in)
    val n = sc.nextInt
    val a = List.fill(n,3)(sc.nextInt)
    val isEq = (0 to 2).forall(i => (for (j <- 0 to n-1) yield a(j)(i)).sum == 0)
    val ans = if(isEq) "YES" else "NO"
    print (ans)
}

import scala.io.StdIn._

object Task extends App{
  val N = readLine.split(" ") map {_.toInt} head
  val vecs = for(i <- 1 to N)
	  yield readLine.split(" ") map {_.toLong}

	val sum = vecs.foldLeft(Array.fill(N)(0l))( (l,r) =>
	  l.zip(r).map{ case(a,b) => a + b }
	)

	val z = sum.zip(Array.fill(N)(0l))

	if(z.filter{case (a,b) => a != b}.isEmpty)
	  println("YES")
	else
	  println("NO")
}

import scala.io.StdIn._

object YoungPhysicist {
  def main(args: Array[String]): Unit = {
    val t = readLine.toInt
    var a, b, c = 0
    for (tt <- 1 to t) {
      val Array(aa, bb, cc) = readLine.split(" ").map(_.toInt)
      a += aa
      b += bb
      c += cc
    }
    println(if (a==0 && b==0 && c==0) "YES" else "NO")
  }
}

object YoungPhysicist extends App {

    //sommare le forze di ogni singolo array. Se la somma è 0 è in equilibrio

    val nInput = scala.io.StdIn.readInt()
    var somma = 0

    for (i <- 1 to nInput) {
        val forces = scala.io.StdIn.readLine().split(" ").map(_.toInt).sum
        somma += forces
    }

    if (somma == 0) println("YES")
    else println("NO")
}

object YoungPhysicist extends App {

    //sommare le forze di ogni singolo array. Se la somma è 0 è in equilibrio

    val nInput = scala.io.StdIn.readInt()
    var somma = 0

    for (i <- 1 to nInput) {
        val forces = scala.io.StdIn.readLine().split(" ").map(_.toInt).sum
        somma = somma + forces
    }

    if (somma == 0) println("YES")
    else println("NO")
}

object Main {

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

    val n = std.readLine().toInt

    val v = Array[Int](0,0,0)
    for (i <- 0 until n) {
      val value = std.readLine().split(' ').map(_.toInt)
      for (j <- 0 until 3) {
        v(j) += value(j)
      }
    }

    if (v.distinct.length > 1) {
      println("NO")
    }
    else {
      println("YES")
    }
  }
}


A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?

The first line of the input contains two integer numbers n and d (2 ≤ n ≤ 2000, 1 ≤ d ≤ 106). The second line contains space separated sequence b0, b1, ..., bn - 1 (1 ≤ bi ≤ 106).

Output the minimal number of moves needed to make the sequence increasing.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val res = data.tail.foldLeft((0, data.head)) {
    case ((soFar, prev), i) if i > prev =>
//      println(1)
//      println((soFar, prev), i)
      (soFar, i)
    case ((soFar, prev), i) =>
//      println(4)
//      println((soFar, prev), i)
//      24 - 13 = 11
//      11 + 3 * 3 + 3
//      println(prev)
//      if (i % d == 0)
//        (soFar + (prev - i) / d, prev + d)
//      else
      (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d)
  }
//  println(res)
  println(res._1)
}

//10 24 25 28

import java.util.Scanner

object Sequence extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()
  val d = s.nextInt()

  val arr = (0 until n).map(_ => s.nextInt()).toArray

  val x = for {
    i <- 1 until n
  } yield {
      if (arr(i) < arr(i - 1)) {
        val f = math.ceil((arr(i - 1).toDouble - arr(i)) / d.toDouble).toInt
        arr(i) += f * d
        if (arr(i) == arr(i - 1)) {
          arr(i) += d
          f + 1
        } else {
          f
        }
      } else if (arr(i) == arr(i - 1)) {
        arr(i) += d
        1
      } else 0
    }

  println(x.sum)

}

object A11 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, d) = readInts(2)
    val in = readInts(n)
    var res = 0L
    for(i <- 1 until n) {
      if(in(i) <= in(i-1)) {
        val delta = (in(i-1)-in(i)+d)/d
        res += delta
        in(i) += delta*d
      }
    }
    println(res)
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import java.io.PrintWriter
import scala.io.Source
import java.io.File
import scala.collection.immutable.List

object Increasing extends App {
  lazy val writer = System.out   // new PrintWriter(new File("output.txt"))
  val it = Source.stdin.getLines
  val ss = (it.next).split(" ")
  val li = ss map (_.toInt)
  val n = li(0)
  val d = li(1)

  def needD(cur: Long, o: List[Long], cnt: Long): Long = o match {
    case Nil => cnt
    case h :: t => {
      var nd = if (cur < h) 0 else ((cur-h) / d + 1)
      val nc = h + nd*d
      // println("cur,h,nd,nc = "+cur+" "+h+" "+nd+" "+nc)
      needD(nc, t, cnt+nd)
    }
  }

  val b: List[Long] = (it.next.split(" ").toList) map (_.toLong)
  val nd = needD(b(0), b.tail, 0)
  writer.println(nd)
  writer.close()
}

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    var count = 0
    val tr = a.scanLeft(0) { (prev, cur) =>
      if (prev >= cur) {
        val step = (prev - cur) / d + 1
        count += step
        cur + d * step
      } else {
        cur
      }
    }
    println(count)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val res = data.tail.foldLeft((0, data.head)) {
    case ((soFar, prev), i) if i > prev =>
//      println((soFar, prev), i)
      (soFar, i)
    case ((soFar, prev), i) if i == prev =>
//      println((soFar, prev), i)
      (soFar + 1, i + d)
    case ((soFar, prev), i) if (prev - i) % d == 0 =>
//      println((soFar, prev), i)
      (soFar + (prev - i) / d + 1, i + d)
    case ((soFar, prev), i) =>
//      println((soFar, prev), i)
      (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d - (prev - i) % d)
  }
  println(res._1)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val res = data.tail.foldLeft((0, data.head)) {
    case ((soFar, prev), i) if i > prev =>
//      println(1)
//      println((soFar, prev), i)
      (soFar, i)
    case ((soFar, prev), i) if i == prev =>
//      println((soFar, prev), i)
//      println(2)
      (soFar + 1, i + d)
    case ((soFar, prev), i) if (prev - i) % d == 0 =>
//      println((soFar, prev), i)
//      println(3)
      (soFar + (prev - i) / d + 1, i + d)
    case ((soFar, prev), i) =>
//      println((soFar, prev), i)
//      println(4)
//      println(prev)
      (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d)
  }
  println(res._1)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, d) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val res = data.tail.foldLeft((0, data.head)) {
    case ((soFar, prev), i) if i > prev =>
//      println((soFar, prev), i)
      (soFar, i)
    case ((soFar, prev), i) if i == prev =>
//      println((soFar, prev), i)
      (soFar + 1, i + d)
    case ((soFar, prev), i) if (prev - i) % d == 0 =>
//      println((soFar, prev), i)
      (soFar + (prev - i) / d, i)
    case ((soFar, prev), i) =>
//      println((soFar, prev), i)
      (soFar + (prev - i) / d + 1, i + (prev - i) / d * d + d - (prev - i) % d)
  }
  println(res._1)
}

import java.util.Scanner

object Sequence extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()
  val d = s.nextInt()

  val arr = (0 until n).map(_ => s.nextInt()).toArray

  val x = for {
    i <- 1 until n
  } yield {
    if (arr(i) < arr(i - 1)) {
      val f = math.ceil((arr(i - 1).toDouble - arr(i)) / d.toDouble).toInt
      arr(i) += f * d
      f
    } else if (arr(i) == arr(i - 1)) {
      arr(i) += d
      1
    } else 0
  }

  println(x.sum)

}


Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1 ≤ i ≤ n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.

The first line contains two space-separated integers s and n (1 ≤ s ≤ 104, 1 ≤ n ≤ 103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1 ≤ xi ≤ 104, 0 ≤ yi ≤ 104) — the i-th dragon's strength and the bonus for defeating it.

On a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't.

NoteIn the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2 + 99 = 101. Now he can defeat the second dragon and move on to the next level.In the second sample Kirito's strength is too small to defeat the only dragon and win.

import scala.io.StdIn._

object Main extends App {
  case class Dragon(power: Int, bonus: Int) extends Ordered[Dragon] {
    def compare(other: Dragon): Int = this.power - other.power
  }
  val Array(s, n) = readLine().split(" ").map(_.toInt)
  val a = for {
    _ <- (0 until n).toArray
    Array(power, bonus) = readLine().split(" ").map(_.toInt)
  } yield Dragon(power, bonus)
  val dragons = a.sorted
  val (_, ans) = dragons.foldLeft((s, true)) { (current, d) =>
    val (sum, state) = current
    if (sum <= d.power) (sum, false)
    else (sum + d.bonus, true)
  }
  println(if (ans) "YES" else "NO")
}

import scala.io.StdIn._

object Main extends App {
  case class Dragon(power: Int, bonus: Int) extends Ordered[Dragon] {
    def compare(other: Dragon): Int = this.power - other.power
  }
  val Array(s, n) = readLine().split(" ").map(_.toInt)
  val a = for {
    _ <- 0 until n
    Array(power, bonus) = readLine().split(" ").map(_.toInt)
  } yield Dragon(power, bonus)
  val dragons = a.sorted
  val (_, ans) = dragons.foldLeft((s, true)) { (current, d) =>
    val (sum, state) = current
    if (sum <= d.power) (sum, false)
    else (sum + d.bonus, true)
  }
  println(if (ans) "YES" else "NO")
}

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

object CodeForces extends App{

  val array = StdIn.readLine().split(" ").map(_.toInt)
  val s = array(0)
  val n = array(1)

  var sorted = (1 to n).map({_ =>
    val temp = StdIn.readLine().split(" ").map(_.toInt)
    temp(0) -> temp(1)
  }).sortBy(_._1).toList

  @tailrec def check(list: List[(Int,Int)], currentS: Int): String = list match {
    case List() => "YES"
    case (x,y) :: xs =>
      if (x >= currentS) "NO"
      else check(xs,currentS + y)
  }

  println(check(sorted,s))

}

import scala.io.StdIn._

object GCD extends App {

  val str = readLine()
  val arr = str.split(" ")

  val s = arr(0).toInt
  val n = arr(1).toInt

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

  def fillDragonsNums(n: Int, seq: Seq[DragonsNums]): Seq[DragonsNums] =
    if (n == 0) seq
    else {
      val str = readLine()
      val arr = str.split(" ")

      val x = arr(0).toInt
      val y = arr(1).toInt
      fillDragonsNums(n - 1, seq :+ DragonsNums(x, y))
    }

  def battleOutcomes(s: Int, seq: Seq[DragonsNums], results: Seq[Boolean]): Seq[Boolean] = {
    if (seq.isEmpty) results
    else battleOutcomes(s + seq.head.y, seq.tail, results :+ (s > seq.head.x))
  }

  if (battleOutcomes(s, fillDragonsNums(n, Seq()).sortBy(_.x), Seq()).forall(identity)) println("YES")
  else println("NO")
}

object Dragons_230A extends App{
  var firstRow = readLine().split(" ").toList
  val kiritoPower = firstRow(0).toInt
  val amountDragons = firstRow(1).toInt
  var dragons = List.empty[(Int, Int)]
  for (i <- 0 until amountDragons) {
    var dragonss = readLine().split(" ").toList
    var tuple = (dragonss.head.toInt, dragonss.last.toInt)
    dragons = dragons :+ tuple
  }
  dragons = dragons.sortWith(_._1 < _._1)

  def game (kirito: Int, dragonsss: List[(Int, Int)]): Unit = dragonsss match {
    case Nil => println("YES")
    case (dragonsPower: Int, bonus: Int) :: xs if kirito > dragonsPower => game(kirito + bonus, xs)
    case (dragonsPower: Int, bonus: Int) :: xs if kirito <= dragonsPower => println("NO")
  }
  game(kiritoPower, dragons)
}

import java.util.StringTokenizer

object _230A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next.toInt
  val n = next.toInt
  val a = (1 to n).map(i => (next.toInt, next.toInt)).sortBy(u => u._1).toList
  def doit(a: List[(Int, Int)], s: Int): String =
    if (a == Nil) "YES"
    else if (a.head._1 >= s) "NO"
    else doit(a.tail, s + a.head._2)
  println(doit(a, s))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(s, n) = in.next().split(" ").map(_.toInt)
  val data = Range(0, n).map(_ => in.next().split(" ").map(_.toInt)).sortBy(_.head).foldLeft((s, true)) {
    case ((s, false), x) => (s, false)
    case ((s, true), x) if x.head >= s => (s, false)
    case ((s, true), x) => (s + x.last, true)
  }._2
  if (data) println("YES") else println("NO")
}

import scala.collection.mutable

object A230 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    var Array(s, n) = readInts(2)
    val input = Array.fill(n)(readInts(2))

    val pq = mutable.PriorityQueue[(Int, Int)]()
    input.foreach(arr => pq += ((arr(1), arr(0))))

    var break = false
    var size = pq.length
    while(!break && pq.nonEmpty) {
      var top = pq.dequeue()
      if(s > top._2) { //win
        s += top._1
      } else { //loose, requeue at end
        var requeue = Array.empty[(Int, Int)]
        while(pq.nonEmpty && top._2 >= s) {
          requeue ++= Array(top)
          top = pq.dequeue()
        }
        if(top._2 < s) { //win
          s += top._1
        } else { //loose, requeue at end
          requeue ++= Array(top)
        }
        requeue.foreach(x => pq += x)
      }
      if(pq.length == size) {
        break = true
      }
      size = pq.length
    }

    if(break && pq.nonEmpty) {
      println("NO")
    } else {
      println("YES")
    }
  }
}

object Main {

  class Dragon(val x:Int, val y:Int) extends Ordered[Dragon] {
    def compare(other : Dragon) = {
      this.y.compare(other.y)
    }
    override def toString(): String = "x: " + x + ", y: " + y
  }

  def main(args: Array[String]): Unit = {
    var Array(s, n) = io.StdIn.readLine.split(" ").map(_.toInt)

    var d = new collection.mutable.PriorityQueue[Dragon]()

    for (i<-0 until n) {
      val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
      d.enqueue(new Dragon(x,y))
    }

    var tmp = new collection.mutable.ArrayBuffer[Dragon]()

    while (!d.isEmpty) {
      val top = d.dequeue
      if (s > top.x) {
        s += top.y
        if (!tmp.isEmpty) {
          tmp.foreach(d.enqueue(_))
          tmp.clear()
        }
      }
      else tmp += top
    }
    if (tmp.isEmpty) println("YES")
    else println("NO")

  }
}

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

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

  val s0, N = sc.nextInt
  val d = Array.fill(N, 2)(sc.nextInt).sortBy(_(0))

  def solve: String = {
    @tailrec
    def loop(s: Int, i: Int): String =
      if (i == N) "YES"
      else if (s > d(i)(0)) loop(s + d(i)(1), i + 1)
      else "NO"
    loop(s0, 0)
  }

  out.println(solve)
  out.close
}

import java.io._
import scala.annotation.tailrec

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

  val Array(s, n) = readInts
  val dragons = (for(_ <- 1 to n) yield readInts).sortBy(_(0)).toList

  @tailrec
  def win(s: Int, d: List[Array[Int]]): Boolean = d match {
    case Nil => true
    case Array(ds, b) :: tail => if(ds >= s) false else win(s + b, tail)
  }

  def main(a: Array[String]) {
    println(if(win(s, dragons)) "YES" else "NO")
  }
}

object Main {
  def main(args: Array[String]) {
    val sn = readLine().split(" ").map(_.toInt)
    val data = (1 to sn(1)).map{ _ =>
      readLine().split(" ").map(_.toInt)
    }
    val sorted = data.sortBy(_(0))
    val r = sorted.foldLeft((sn(0), 0)) { (t, e) =>
      if (t._1 > e(0)) (t._1 + e(1), t._2 + 1)
      else t
    }
    if (r._2 == sn(1)) println("YES")
    else println("NO")
  }
}

import scala.io.StdIn._

object _230_A extends App {
  val Array(s, n) = readLine().split(" ").map(_.toInt)
  val dragons = new Array[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(strength, bonus) = readLine().split(" ").map(_.toInt)
    dragons(i) = (strength, bonus)
  }

  val currentDragons = dragons.sortBy(_._1).toBuffer

  def findMaxDragonIdx(currentStrength: Int) = {
    var maxIdx = -1
    var maxBonus = Integer.MIN_VALUE
    for (i <- currentDragons.indices) {
      val (s, b) = currentDragons(i)
      if (s < currentStrength && maxBonus < b) {
        maxIdx = i
        maxBonus = b
      }
    }

    maxIdx
  }

  var dragonToKill = 0
  var currentStrength = s
  do {
    dragonToKill = findMaxDragonIdx(currentStrength)
//    println("kill " + dragonToKill)
    if (dragonToKill > -1) {
      currentStrength += currentDragons(dragonToKill)._2
      currentDragons.remove(dragonToKill)
    }
  } while (dragonToKill != -1 && !currentDragons.isEmpty)

  println(if (currentDragons.isEmpty) "YES" else "NO")
}

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

object Dragons {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def canWin(s: Int, dragons : List[(Int,Int)]) : Boolean = dragons match {
     case Nil                   => true
     case (x,y) :: ds if x < s => canWin(s+y,ds)
     case _                     => false
   }

   def main(args: Array[String]) {
     val (s,n) = readTuple
     val dragons = for {
       i <- 1 to n
       (x,y) = readTuple
     } yield (x,y)
     if (canWin(s,dragons.sortBy(_._1).toList)) println("YES") else println("NO")

   }

}

object main extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  def solve(input: InputStream, output: PrintStream): Unit = {
   val sc = new Scanner(input)
    var s: Long = sc.nextInt()
    val ndragons = sc.nextInt()

    val dSB = (1 to ndragons).
              map( _ => (sc.nextInt(),sc.nextInt()))
              .sortBy{ case (ds,_) => ds}
    var isGood = true
    dSB.foreach{
      case (ds,db) => {
        isGood &= s > ds
        s += db
      }
    }
    output.println(if(isGood) "YES" else "NO")
  }
   solve(System.in,System.out)
}

object main extends App with fastIO {

  var (s, n) = (nextInt, nextInt)
  var a = Array.fill(n, 2)(nextInt) sortBy(_(0))
  a foreach { it => if (it(0) < s) s += it(1) }
  println(if (a.map(_(0)).max < s) "YES" else "NO")
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

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

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

object CodeForces extends App{

  val array = StdIn.readLine().split(" ").map(_.toInt)
  val s = array(0)
  val n = array(1)

  var sorted = (1 to n).map({_ =>
    val temp = StdIn.readLine().split(" ").map(_.toInt)
    temp(0) -> temp(1)
  }).sortBy(_._1).toList

  @tailrec def check(list: List[(Int,Int)], currentS: Int): String = list match {
    case List() => "YES"
    case (x,y) :: xs =>
      if (x > currentS) "NO"
      else check(xs,currentS + y)
  }

  println(check(sorted,s))

}

import scala.io.StdIn._

object GCD extends App {

  val str = readLine()
  val arr = str.split(" ")

  val s = arr(0).toInt
  val n = arr(1).toInt

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

  def fillDragonsNums(n: Int, seq: Seq[DragonsNums]): Seq[DragonsNums] =
    if (n == 0) seq
    else {
      val str = readLine()
      val arr = str.split(" ")

      val x = arr(0).toInt
      val y = arr(1).toInt
      fillDragonsNums(n - 1, seq :+ DragonsNums(x, y))
    }

  def battleOutcomes(s: Int, seq: Seq[DragonsNums], results: Seq[Boolean]): Seq[Boolean] = {
    if (seq.isEmpty) results
    else battleOutcomes(s + seq.head.y, seq.tail, results :+ (s >= seq.head.x))
  }

  if (battleOutcomes(s, fillDragonsNums(n, Seq()).sortBy(_.x), Seq()).forall(identity)) println("YES")
  else println("NO")
}

object Dragons_230A extends App{

  var firstRow = readLine().split(" ").toList
  val kiritoPower = firstRow(0).toInt
  val amountDragons = firstRow(1).toInt
  var dragons = List.empty[(Int, Int)]

  for(i <- 0 until amountDragons){
    var dragonss = readLine().split(" ").toList
    var tuple = (dragonss.head.toInt, dragonss.last.toInt)
    dragons = dragons :+ tuple
  }
  def game(kirito: Int, dragonsss: List[(Int, Int)]): Unit = dragonsss match {
    case Nil => println("YES")
    case (dragonsPower: Int, bonus: Int) :: xs if kirito > dragonsPower => game(kirito + bonus, xs)
    case (dragonsPower: Int, bonus: Int) :: xs if kirito < dragonsPower => println("NO")

  }
  game(kiritoPower, dragons)

}

import java.util.StringTokenizer

object _230A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next.toInt
  val n = next.toInt
  val a = (1 to n).map(i => (next.toInt, next.toInt)).sortBy(u => u._1).toList
  def doit(a: List[(Int, Int)], s: Int): String =
    if (a == Nil) "YES"
    else if (a.head._1 > s) "NO"
    else doit(a.tail, s + a.head._2)
  println(doit(a, s))
}

object Main {

  class Dragon(val x:Int, val y:Int) extends Ordered[Dragon] {
    def compare(other : Dragon) = {
      this.y.compare(other.y)
    }
    override def toString(): String = "x: " + x + ", y: " + y
  }

  def main(args: Array[String]): Unit = {
    var Array(s, n) = io.StdIn.readLine.split(" ").map(_.toInt)

    var d = new collection.mutable.PriorityQueue[Dragon]()

    for (i<-0 until n) {
      val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
      d.enqueue(new Dragon(x,y))
    }

    var tmp = new collection.mutable.ArrayBuffer[Dragon]()

    while (!d.isEmpty) {
      val top = d.dequeue
      if (s > top.x) {
        s += top.y
        if (!tmp.isEmpty) {
          tmp.foreach(d.enqueue(_))
          tmp.clear()
        }
      }
      else tmp += top
      println(d)
    }
    if (tmp.isEmpty) println("YES")
    else println("NO")

  }
}

import scala.io.StdIn._

object _230_A extends App {
  val Array(s, n) = readLine().split(" ").map(_.toInt)
  val dragons = new Array[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(strength, bonus) = readLine().split(" ").map(_.toInt)
    dragons(i) = (strength, bonus)
  }

  val currentDragons = dragons.sortBy(_._1).toBuffer

  def findMaxDragonIdx(currentStrength: Int) = {
    var maxIdx = -1
    var maxBonus = Integer.MIN_VALUE
    for (i <- currentDragons.indices) {
      val (s, b) = currentDragons(i)
      if (s <= currentStrength && maxBonus < b) {
        maxIdx = i
        maxBonus = b
      }
    }

    maxIdx
  }

  var dragonToKill = 0
  var currentStrength = s
  do {
    dragonToKill = findMaxDragonIdx(currentStrength)
//    println("kill " + dragonToKill)
    if (dragonToKill > -1) {
      currentStrength -= dragons(dragonToKill)._1
      currentStrength += dragons(dragonToKill)._2
      currentDragons.remove(dragonToKill)
    }
  } while (dragonToKill != -1 && !currentDragons.isEmpty)

  println(if (currentDragons.isEmpty) "YES" else "NO")
}

import scala.io.StdIn._

object _230_A extends App {
  val Array(s, n) = readLine().split(" ").map(_.toInt)
  val dragons = new Array[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(strength, bonus) = readLine().split(" ").map(_.toInt)
    dragons(i) = (strength, bonus)
  }

  val currentDragons = dragons.sortBy(_._1).toBuffer

  def findMaxDragonIdx(currentStrength: Int) = {
    var maxIdx = -1
    var maxBonus = Integer.MIN_VALUE
    for (i <- currentDragons.indices) {
      val (s, b) = currentDragons(i)
      if (s < currentStrength && maxBonus < b) {
        maxIdx = i
        maxBonus = b
      }
    }

    maxIdx
  }

  var dragonToKill = 0
  var currentStrength = s
  do {
    dragonToKill = findMaxDragonIdx(currentStrength)
//    println("kill " + dragonToKill)
    if (dragonToKill > -1) {
      currentStrength += dragons(dragonToKill)._2
      currentDragons.remove(dragonToKill)
    }
  } while (dragonToKill != -1 && !currentDragons.isEmpty)

  println(if (currentDragons.isEmpty) "YES" else "NO")
}

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

object Dragons {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def canWin(s: Int, dragons : List[(Int,Int)]) : Boolean = dragons match {
     case Nil                   => true
     case (x,y) :: ds if x <= s => canWin(s+y,ds)
     case _                     => false
   }

   def main(args: Array[String]) {
     val (s,n) = readTuple
     val dragons = for {
       i <- 1 to n
       (x,y) = readTuple
     } yield (x,y)
     if (canWin(s,dragons.sortBy(_._1).toList)) println("YES") else println("NO")

   }

}

object main extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  def solve(input: InputStream, output: PrintStream): Unit = {
   val sc = new Scanner(input)
    var s: Long = sc.nextInt()
    val ndragons = sc.nextInt()
    val dragonsStrength = (1 to ndragons).map( _ => sc.nextInt())
    val dragonsBonus = (1 to ndragons).map( _ => sc.nextInt())
    val dSB = dragonsStrength.zip(dragonsBonus).sortBy{ case (ds,_) => ds}
    var isGood = true
    dSB.foreach{
      case (ds,db) => {
        isGood &= s > ds
        s += db
      }
    }
    output.println(if(isGood) "YES" else "NO")
  }
   solve(System.in,System.out)
}

object main extends App with fastIO {

  var (s, n) = (nextInt, nextInt)
  var a = Array.fill(n, 2)(nextInt) sortBy(_(0))
  a foreach { it => if (it(0) <= s) s += it(1) }
  println(if (a.map(_(0)).max <= s) "YES" else "NO")
  flush
}

trait fastIO {
  import java.io._

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

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

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

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

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

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


The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered. Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.

The input data consists of three lines, each of them describes the position of one stadium. The lines have the format x,  y,  r, where (x, y) are the coordinates of the stadium's center ( -  103 ≤ x,  y ≤ 103), and r (1 ≤ r  ≤ 103) is its radius. All the numbers in the input data are integer, stadiums do not have common points, and their centers are not on the same line.

Print the coordinates of the required point with five digits after the decimal point. If there is no answer meeting the conditions, the program shouldn't print anything. The output data should be left blank.

object P2C {
    import Math._

    def main(args : Array[String]) {
        val Array(x1, y1, r1) = readLine split " " map {_.toDouble}
        val Array(x2, y2, r2) = readLine split " " map {_.toDouble}
        val Array(x3, y3, r3) = readLine split " " map {_.toDouble}
        val (x12, y12) = (x1 - x2, y1 - y2)
        val (x13, y13) = (x1 - x3, y1 - y3)
        val d12 = x12 * x12 + y12 * y12
        val d13 = x13 * x13 + y13 * y13
        val e = x12 * y13 - x13 * y12
        val (rr1, rr2, rr3) = (r1 * r1, r2 * r2, r3 * r3)
        val (rr21, rr31) = (rr2 - rr1, rr3 - rr1)
        val ry = rr21 * y13 - rr31 * y12
        val rx = x12 * rr31 - x13 * rr21
        val dy = d12 * y13 - d13 * y12
        val dx = x12 * d13 - x13 * d12
        val r = rx * rx + ry * ry
        val d = dx * dx + dy * dy
        val t = dx * rx + dy * ry + e * e * rr1 * 2.0
        val s = if (r == 0.0) {
            Array(d / (t * 2.0))
        } else {
            val delta = t * t - r * d
            if (delta < 0.0) {
                Array[Double]()
            } else {
                val sD = sqrt(delta)
                val s1 = (t + sD) / r
                val s2 = (t - sD) / r
                Array(s1, s2).filter{_ > 1.0}
            }
        }
        def diff(p1 : Double, p2 : Double) = {
            val d = abs(p1 - p2)
            if (d <= PI) d else 2 * PI - d
        }
        val p = for {
            si <- s
            x = x1 + (si * ry - dy) / (e * 2.0)
            y = y1 + (si * rx - dx) / (e * 2.0)
            p1 = atan2(y1 - y, x1 - x)
            p2 = atan2(y2 - y, x2 - x)
            p3 = atan2(y3 - y, x3 - x)
            b = asin(1.0 / si) * 2.0
            if (diff(p1, p2) >= b)
            if (diff(p1, p3) >= b)
            if (diff(p2, p3) >= b)
        } yield (si, x, y)
        if (p.isEmpty) return
        val (_, x, y) = p.minBy{_._1}
        println(x.formatted("%.5f") + " " + y.formatted("%.5f"))
    }
}


Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.Consider the painting as a n × m rectangular grid. At the beginning an x × y rectangular brush is placed somewhere in the frame, with edges parallel to the frame, (1 ≤ x ≤ n, 1 ≤ y ≤ m). Then the brush is moved several times. Each time the brush is moved one unit right or down. The brush has been strictly inside the frame during the painting. The brush alters every cell it has covered at some moment.You have found one of the old Kamal-ol-molk's paintings. You want to know if it's possible that it has been altered in described manner. If yes, you also want to know minimum possible area of the brush.

The first line of input contains two integers n and m, (1 ≤ n, m ≤ 1000), denoting the height and width of the painting. The next n lines contain the painting. Each line has m characters. Character 'X' denotes an altered cell, otherwise it's showed by '.'. There will be at least one altered cell in the painting.

Print the minimum area of the brush in a line, if the painting is possibly altered, otherwise print  - 1.

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

/**
 * Created by arseny on 05.10.14.
 */
object C extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextInt
    val m = nextInt
    val gs = Array.fill(n, m)(true)
    for (i <- 0 until n) {
      gs(i) = nextString.toCharArray.map(_ == 'X')
    }

//    for (i <- 0 until n) {
//      for (j <- 0 until m) {
//        out.print(gs(i)(j))
//        out.print(" ")
//      }
//      out.print("\n")
//    }

    def tryPaint(gs: Array[Array[Boolean]], n: Int, m: Int): Int = {
      var lux = 0
      var luy = 0
      var found  = false
      for (i <- 0 until n) {
        for (j <- 0 until m) {
          if (!found && gs(i)(j)) {
            found = true
            lux = i
            luy = j
          }
        }
      }
      //out.println(lux, luy)

      var maxY = 1
      var foundMaxY = false
      for (i <- luy + 1 until m) {
        if (!foundMaxY && gs(lux)(i) == false) {
          foundMaxY = true
          maxY = i - luy
        }
      }
      if (!foundMaxY) {
        maxY = m - luy
      }
      //out.println(maxY)

      var x = 1

      var foundX = false
      for (i <- lux + 1 until n) {
        if (!foundX && gs(i)(luy) == false) {
          foundX = true
          x = i - lux
        }
      }
      if (!foundX) {
        x = n - lux
      }

      var y = 1
      if (lux + x < n) {
        var foundY = false
        for (j <- luy + 1 until luy + maxY) {
          if(!foundY && gs(lux + x)(j) == true) {
            foundY = true
            y = luy + maxY - j
          }
        }
        if (!foundY) {
          y = 1
        }
      }

      //out.println(x, y)

      val ps = Array.fill(n, m)(false)

      for (i <- lux until lux + x) {
        for (j <- luy until luy + y) {
          ps(i)(j) = true
        }
      }

      def paintRight(x: Int, y: Int, h: Int, w: Int): Boolean = {
        if (y + w == m) {
          false
        } else {
          for (i <- x until x + h) {
            ps(i)(y + w) = true
          }
          true
        }
      }

      def paintDown(x: Int, y: Int, h: Int, w: Int): Boolean = {
        if (x + h == n) {
          false
        } else {
          for (i <- y until y + w) {
            ps(x + h)(i) = true
          }
          true
        }
      }

      var curx = lux
      var cury = luy

      var painted = false
      while (!painted) {
        if (cury + y < m && gs(curx)(cury + y) == true) {
          paintRight(curx, cury, x, y)
          cury += 1
        } else if (curx + x < n && gs(curx + x)(cury) == true) {
          paintDown(curx, cury, x, y)
          curx += 1
        } else {
          painted = true
        }
      }

//      for (i <- 0 until n) {
//        for (j <- 0 until m) {
//          out.print(ps(i)(j))
//          out.print(" ")
//        }
//        out.print("\n")
//      }

      var canPaint = true
      for (i <- 0 until n) {
        for (j <- 0 until m) {
          if (ps(i)(j) != gs(i)(j)) {
            canPaint = false
          }
        }
      }

      if (canPaint) {
        x * y
      } else {
        -1
      }
    }

    val gst = Array.fill(m, n)(true)
    for (i <- 0 until m) {
      for (j <- 0 until n) {
        gst(i)(j) = gs(j)(i)
      }
    }

    val ans1 = tryPaint(gs, n, m)
    val ans2 = tryPaint(gst, m, n)

    if (ans1 == -1 && ans2 == -1) {
      out.print(-1)
    } else {
      if (ans1 == -1) {
        out.print(ans2)
      }
      if (ans2 == -1) {
        out.print(ans1)
      }
      if (ans1 != -1 && ans2 != -1) {
        out.print(math.min(ans1, ans2))
      }
    }
  }

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

import scala.collection._

object C extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val ps = Array.fill(n){ readLine.toCharArray.map(_ == 'X') }
  val totalBad = ps.map(_.count(identity)).sum

  var startX, startY = 0
  while (startY < n && !ps(startY)(startX)) {
    while (startX < m && !ps(startY)(startX)) {
      startX += 1
    }
    if (startX == m) {
      startX = 0
      startY += 1
    }
  }

  val rightCnt = Array.fill(n, m)(0)
  val downCnt = Array.fill(n, m)(0)

  for (y <- n - 1 to 0 by -1) {
    for (x <- m - 1 to 0 by -1) {
      if (ps(y)(x)) {
        if (x + 1 < m) rightCnt(y)(x) = rightCnt(y)(x + 1) + 1
        else rightCnt(y)(x) = 1
        if (y + 1 < n) downCnt(y)(x) = downCnt(y + 1)(x) + 1
        else downCnt(y)(x) = 1
      }
    }
  }

  var minArea = Int.MaxValue
  for (bY <- 1 to n - startY) {
    for (bX <- 1 to m - startX ) {
      val area = bY * bX
      if (area < minArea && check(bX, bY)) {
        minArea = area
      }
    }
  }

  def check(bX: Int, bY : Int): Boolean = {
    var x0 = startX
    var y0 = startY
    var fixed = 0

    if (rightCnt(y0)(x0) > bX && downCnt(y0)(x0) > bY) return false
    if (rightCnt(y0)(x0) < bX && downCnt(y0)(x0) < bY) return false

    for (y <- y0 until y0 + bY) {
      if (rightCnt(y)(x0) < bX) return false
      fixed += bX
    }

    var moved = true
    while (moved) {
      if (x0 + bX < m && downCnt(y0)(x0 + bX) >= bY && !(y0 + bY < n && rightCnt(y0 + bY)(x0) > 0)) {
        fixed += bY
        x0 += 1
        moved = true
      } else if (y0 + bY < n && rightCnt(y0 + bY)(x0) >= bX && !(x0 + bX < m && downCnt(y0)(x0 + bX) > 0)) {
        y0 += 1
        fixed += bX
        moved = true
      } else moved = false
    }

    fixed == totalBad
  }

  println(if (minArea == Int.MaxValue) -1 else minArea)
}


For a collection of integers $$$S$$$, define $$$\operatorname{mex}(S)$$$ as the smallest non-negative integer that does not appear in $$$S$$$.NIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times.The universe can be represented as a 1-indexed array $$$a$$$ of length $$$n$$$. When NIT snaps his fingers, he does the following operation on the array:  He selects positive integers $$$l$$$ and $$$r$$$ such that $$$1\le l\le r\le n$$$. Let $$$w=\operatorname{mex}(\{a_l,a_{l+1},\dots,a_r\})$$$. Then, for all $$$l\le i\le r$$$, set $$$a_i$$$ to $$$w$$$. We say the universe is destroyed if and only if for all $$$1\le i\le n$$$, $$$a_i=0$$$ holds.Find the minimum number of times NIT needs to snap his fingers to destroy the universe. That is, find the minimum number of operations NIT needs to perform to make all elements in the array equal to $$$0$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1\le n\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$0\le a_i\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case, we do $$$0$$$ operations and all elements in the array are already equal to $$$0$$$.In the second test case, one optimal way is doing the operation with $$$l=2$$$, $$$r=5$$$.In the third test case, one optimal way is doing the operation twice, respectively with $$$l=4$$$, $$$r=4$$$ and $$$l=2$$$, $$$r=6$$$.In the fourth test case, one optimal way is doing the operation with $$$l=1$$$, $$$r=1$$$.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      var cou = 0
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = new Array[Long](n)
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 1 to n) {
        A(i - 1) = tokenizer.nextToken().toInt
      }
      val a = A.contains(0)
      val b = A.toList.count(_ > 0)
      if (b == 0) {
        println(0)
      }
      else if (!a){
        println(1)
      }
      else {
        cou = 0
        var s = 0
        for (i <- A) {
          if (i == 0) {
            s = 0
          }
          else {
            if (s == 0) {
              cou+=1
            }
            s+=1
          }
        }
        if (cou > 1){
          println(2)
        }
        else println(1)
      }
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      var cou = 0
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = new Array[Long](n)
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 1 to n) {
        A(i-1) = tokenizer.nextToken().toInt
      }
      var s = 0
      for (i <- A) {
        if (i > 0) {
          if (s == 0)
            {
             cou+=1
            }
          s+=1
        }
        if (i == 0) {
          s = 0
        }
      }
      println(cou)
    }
  }
}


You have a given picture with size $$$w \times h$$$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:  A "+" shape has one center nonempty cell.  There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.  All other cells are empty. Find out if the given picture has single "+" shape.

The first line contains two integers $$$h$$$ and $$$w$$$ ($$$1 \le h$$$, $$$w \le 500$$$) — the height and width of the picture. The $$$i$$$-th of the next $$$h$$$ lines contains string $$$s_{i}$$$ of length $$$w$$$ consisting "." and "*" where "." denotes the empty space and "*" denotes the non-empty space.

If the given picture satisfies all conditions, print "YES". Otherwise, print "NO". You can output each letter in any case (upper or lower).

NoteIn the first example, the given picture contains one "+".In the second example, two vertical branches are located in a different column.In the third example, there is a dot outside of the shape.In the fourth example, the width of the two vertical branches is $$$2$$$.In the fifth example, there are two shapes.In the sixth example, there is an empty space inside of the shape.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val H, W = ni()
    val g = nm_c(H, W)
    val D = Array(
      (-1, 0),
      (1, 0),
      (0, -1),
      (0, 1),
      (0, 0)
    )

    var found: (Int, Int) = null
    REP(H) { i =>
      REP(W) { j =>
        var ok = true
        REP(D.length) { k =>
          val ii = i+D(k)._1
          val jj = j+D(k)._2
          ok &&= ii >= 0 && ii < H && jj >= 0 && jj < W && g(ii)(jj) == '*'
        }
        if (ok && found == null) {
          debug("found")
          found = (i, j)
        } else if (ok && found != null) {
          debug("found twice")
          out.println("NO")
          return
        }
      }
    }

    if (found == null) {
      out.println("NO")
      return
    }

    val (i, j) = found
    def count(di: Int, dj: Int): Int = {
      var ii = i
      var jj = j
      var cnt = 0
      while(ii >= 0 && ii < H && jj >= 0 && jj < W && g(ii)(jj) == '*') {
        ii += di
        jj += dj
        cnt += 1
      }
      cnt
    }

    val cnt = count(-1, 0) +
      count(1, 0) +
      count(0, -1) +
      count(0, 1) +
      -3

    val sum = g.map(_.count(_ == '*')).sum
    if (sum == cnt) {
      out.println("YES")
    } else {
      out.println("NO")
    }
  }
}

import scala.io.StdIn._

object B_1182 extends App {
  val Array(h, w) = readLine().split(" ").map(_.toInt)
  val A           = Array.ofDim[Boolean](h, w)

  for (i <- 0 until h) {
    A(i) = readLine().map(_ != '.').toArray
  }

  def findCenter: Option[(Int, Int)] = {
    for {
      i <- 1 until h - 1
      j <- 1 until w - 1
    } {
      if (A(i)(j) && A(i - 1)(j) && A(i + 1)(j) && A(i)(j - 1) && A(i)(j + 1)) return Some((i, j))
    }

    None
  }

  def hasOnlyCross: Boolean = {
    findCenter match {
      case None =>
        false
      case Some((row, col)) =>
        for {
          i <- 0 until h
          j <- 0 until w
          if i != row && j != col
        } {
          if (A(i)(j)) return false
        }

        var left   = 0
        var right  = w - 1
        var top    = 0
        var bottom = h - 1

        while (!A(row)(left)) left += 1
        while (!A(row)(right)) right -= 1
        while (!A(top)(col)) top += 1
        while (!A(bottom)(col)) bottom -= 1

        for (i <- left to right) if (!A(row)(i)) return false
        for (j <- top to bottom) if (!A(j)(col)) return false

        true
    }

  }

  if (hasOnlyCross) println("YES")
  else println("NO")
}

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val H, W = ni()
    val g = nm_c(H, W)
    val L, R, T, D = Array.ofDim[Int](H, W)
    REP(H) { i =>
      REP(W) { j =>
        if (g(i)(j) == '*') {
          L(i)(j) += 1
          T(i)(j) += 1
          if (j > 0) L(i)(j) += L(i)(j - 1)
          if (i > 0) T(i)(j) += L(i - 1)(j)
        }
      }
    }

    REP_r(H) { i =>
      REP_r(W) { j =>
        if (g(i)(j) == '*') {
          R(i)(j) += 1
          D(i)(j) += 1
          if (j + 1 < W) R(i)(j) += R(i)(j + 1)
          if (i + 1 < H) D(i)(j) += D(i + 1)(j)
        }
      }
    }

    debug("L")
    debugDim(L)
    debug("R")
    debugDim(R)
    debug("T")
    debugDim(T)
    debug("D")
    debugDim(D)

    var found: (Int, Int) = null
    REP(H) { i =>
      REP(W) { j =>
        if (L(i)(j) > 1 && R(i)(j) > 1 && T(i)(j) > 1 && D(i)(j) > 1) {
          if (found != null) {
            debug(s"found2 $i $j")
            out.println("NO")
            return
          }
          found = (i, j)
        }
      }
    }

    def test: Boolean = {
      val P = mutable.Set[Point]()
      val (h, w) = found
      REP(L(h)(w)) { i =>
        P += Point(h, w - i)
      }
      REP(R(h)(w)) { i =>
        P += Point(h, w + i)
      }
      REP(T(h)(w)) { i =>
        P += Point(h - i, w)
      }
      REP(D(h)(w)) { i =>
        P += Point(h + i, w)
      }

      REP(H) { i =>
        REP(W) { j =>
          if (g(i)(j) == '*' && !P.contains(Point(i, j))) return false
        }
      }
      true
    }

    if (found != null && test) out.println("YES")
    else out.println("NO")
  }
}


Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $$$i$$$ ($$$1 \le i \le n-1$$$), this condition must be satisfied: $$$$$$\frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2$$$$$$For example, the arrays $$$[1, 2, 3, 4, 3]$$$, $$$[1, 1, 1]$$$ and $$$[5, 10]$$$ are dense. And the arrays $$$[5, 11]$$$, $$$[1, 4, 2]$$$, $$$[6, 6, 1]$$$ are not dense.You are given an array $$$a$$$ of $$$n$$$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.For example, if $$$a=[4,2,10,1]$$$, then the answer is $$$5$$$, and the array itself after inserting elements into it may look like this: $$$a=[4,2,\underline{\textbf{3}},\underline{\textbf{5}},10,\underline{\textbf{6}},\underline{\textbf{4}},\underline{\textbf{2}},1]$$$ (there are other ways to build such $$$a$$$).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 50$$$).

For each test case, output one integer — the minimum number of numbers that must be added to the array to make it dense.

NoteThe first test case is explained in the statements.In the second test case, you can insert one element, $$$a=[1,\underline{\textbf{2}},3]$$$.In the third test case, you can insert two elements, $$$a=[6,\underline{\textbf{4}},\underline{\textbf{2}},1]$$$.In the fourth test case, you can insert one element, $$$a=[1,\underline{\textbf{2}},4,2]$$$.In the fifth test case, the array $$$a$$$ is already dense.

import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val xs = readLine.split(' ').toList.map(x => x.toDouble)
    var sum = 0
    for ((x, i) <- xs.view.zipWithIndex) {
      if (i < xs.length - 1) {
        val y = xs(i + 1)
        val r = Math.max(x, y) / Math.min(x, y)
        if (r > 2) {
          val ratio = Math.log(r) / Math.log(2)
          val ratio_floor = (Math.log(r) / Math.log(2)).floor
          sum += (Math.log(r) / Math.log(2)).floor.toInt
          if ( ratio == ratio_floor) sum -= 1
        }
      }
    }
    println(sum)
  }
}

import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val xs = readLine.split(' ').toList.map(x => x.toDouble)
    var sum = 0
    for ((x, i) <- xs.view.zipWithIndex) {
      if (i < xs.length - 1) {
        val y = xs(i + 1)
        val r = Math.max(x, y) / Math.min(x, y)
        if (r > 2) sum += (Math.log(r) / Math.log(2)).floor.toInt
      }
    }
    println(sum)
  }
}


Alice and Bob received $$$n$$$ candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of candies that Alice and Bob received. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ — the weights of the candies. The weight of each candy is either $$$1$$$ or $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output on a separate line:    "YES", if all candies can be divided into two sets with the same weight;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteIn the first test case, Alice and Bob can each take one candy, then both will have a total weight of $$$1$$$.In the second test case, any division will be unfair.In the third test case, both Alice and Bob can take two candies, one of weight $$$1$$$ and one of weight $$$2$$$.In the fourth test case, it is impossible to divide three identical candies between two people.In the fifth test case, any division will also be unfair.

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

import scala.collection.mutable.ArrayBuffer

object Codeforces extends App {
  var debug = false
  var sc = new Scanner(System.in)
  if (new java.io.File("input.txt").exists) {
    debug = true
    sc = new Scanner(new FileInputStream("input.txt"))
  }

  val testCount = sc.nextInt
  /* if (debug) {
       testCount = sc.nextInt();
   }*/

  var n = 0
  var A = ArrayBuffer[Int]()
  for (t <- 1 to testCount) {
    if (debug) {
      println("Test Case: " + t)
    }
    A = ArrayBuffer[Int]()
    n = sc.nextInt()
    for (i <- 1 to n) {
      A += sc.nextInt()
    }
    val result = solveTestCase()
    println(result)
  }

  def solveTestCase(): Any = {
    var sum = 0
    var twos = 0
    for (x <- A) {
      sum += x
      if (x == 2) twos += 1
    }
    if (sum % 2 == 0) {
      if (n - twos > 0 || n % 2 == 0) {
        "YES"
      } else {
        "NO"
      }
    } else {
      "NO"
    }
  }
}