You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.

If it is impossible to reorder $$$n$$$ given strings in required order, print "NO" (without quotes). Otherwise print "YES" (without quotes) and $$$n$$$ given strings in required order.

NoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".

/**
  * @author ShankarShastri
  *         Algorithm: CF_486_DIV3_B (http://codeforces.com/contest/988/problem/B)
  */

import scala.io.StdIn._
import scala.annotation.tailrec

object CF_486_DIV3_B {

  @tailrec
  def subStringVerifier(list: List[String]): Boolean = {
    if(list.length == 0 || list.length == 1) true
    else if(list.length == 2) {
        if(list.last.contains(list.head)) true
        else false
      } else {
      list match {
        case head :: tail if tail.head.contains(head)=> subStringVerifier(tail)
        case _ => false
      }
    }
  }

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

    val list = (1 to n).map{ _ =>
      readLine
    }.toList
    val createdList = list.sortBy(_.length)
    if(subStringVerifier(createdList)) {
      println("YES")
      createdList.map(println)
    } else {
      println("NO")
    }
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine.toInt
    val a = (0 until n).map(_ => StdIn.readLine)
    val b = a.sortWith((x, y) => x.length < y.length)
    val result = !(1 until n).exists(i => !b(i).contains(b(i-1)))
    if (result) {
      println("YES")
      b.foreach(println(_))
    } else {
      println("NO")
    }
  }
}

object problemA {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable
    import scala.util.control.Breaks._
    import scala.collection.JavaConverters._

    val source = System.in
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(n) = readArray().map(_.toInt)
        var a = new Array[String](n)
        for (i <- 0 until n) a(i) = readString()

        a = a.sortWith((p1, p2) => p1.length < p2.length)
        for (i <- 0 until n - 1) {
            if (!a(i + 1).contains(a(i))) {
                print("NO")
                return
            }
        }

        println("YES")
        a.foreach(println(_))
    }
}


Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.

The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).

If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).

NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.

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

/**
 * Created by arseny on 07.09.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 p = nextInt
    val s = nextString
    val as = "qwertyuiopasdfghjklzxcvbnm".sorted.take(p)
    if(p == 1) {
      out.print("NO")
    } else {
      def getCandidates(s: String, start: Char) = s.length match {
        case 0 => as.dropWhile(_ < start)
        case 1 => as.dropWhile(_ < start).filterNot(c => c == s(0))
        case n => as.dropWhile(_ < start).filterNot(c => c == s(n - 1) || c == s(n - 2))
      }
      def tryFill(s: String, start: Char, size: Int): (String, Boolean) = {
        if(size == 0) {
          (s, true)
        } else {
          val cs = getCandidates(s, start)
          if(cs.isEmpty) {
            ("", false)
          } else {
            var found = false
            var res = ("", false)
            for(i <- 0 until cs.length if(!found)) {
              val trySuffix = tryFill(s + cs(i), 'a', size - 1)
              if(trySuffix._2 == true) {
                found = true
                res = trySuffix
              }
            }
            res
          }
        }
      }
      var found = false
      var res = ("NO", false)
      for(i <- n - 2 to -1 by(-1) if(!found)) {
        val start = (s(i + 1).toInt + 1).toChar
        val trySuffix = tryFill(s.take(i + 1), start, n - i - 1)
        if(trySuffix._2 == true) {
          found = true
          res = trySuffix
        }
      }
      out.print(res._1)
    }
  }

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  val str = in.next()
  if (n == 1) {
    val candidate = (str.head + 1).toChar
    if (candidate - 'a' >= p)
      println("NO")
    else
      println(candidate)
  } else if (n == 2) {
    println((str.last + 1 until ('a' + p)).find(i => i != str.head) match {
      case Some(x) => str.head.toString + x
      case None if str.head + 1 < 'a' + p => (str.head + 1).toChar.toString + 'a'
      case None => "NO"
    })
  } else {
    println(str.indices.reverse.find{
      case (index) =>
        (str(index) + 1 until ('a' + p)).exists(i => index == 0 ||
          (str(index - 1) != i && (index == 1 || str(index - 2) != i)))
    } match {
      case None => "NO"
      case Some(index) =>
        val l = (str(index) + 1 until ('a' + p)).find(i => index == 0 ||
          (str(index - 1) != i && (index == 1 || str(index - 2) != i))).map(_.toChar).get
        val prefix = l :: str.toCharArray.take(index).toList.reverse
        (index + 1 until n).foldLeft(prefix) {
          case (pref, i) => ('a' to ('a' + p).toChar).find(i => !pref.take(2).contains(i)).get :: pref
        }.reverse.mkString
    })
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  val str = in.next()
  if (n == 1) {
    val candidate = (str.head + 1).toChar
    if (candidate - 'a' >= p)
      println("NO")
    else
      println(candidate)
  } else if (n == 2) {
    println((str.last + 1 until ('a' + p)).find(i => i != str.head) match {
      case Some(x) => str.head.toString + x
      case None if str.head + 1 < 'a' + p => (str.head + 1).toChar.toString + 'a'
      case None => "NO"
    })
  } else {
    println(str.reverse.sliding(3).zipWithIndex.find{
      case (str, index) =>
        (str.head + 1 until ('a' + p)).exists(i => i != str(1) && i != str(2))
    } match {
      case None => "NO"
      case Some((_, index)) =>
        val l = (str(index) + 1 until ('a' + p)).find(i => i != str(1) && i != str(2)).map(_.toChar).get
        val prefix = l :: str.toCharArray.take(n - index - 1).toList.reverse
        (0 until index).foldLeft(prefix) {
          case (pref, i) => ('a' to ('a' + p).toChar).find(i => !pref.take(2).contains(i)).get :: pref
        }.reverse.mkString
    })
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, p) = in.next().split(' ').map(_.toInt)
  val str = in.next()
  if (n == 1) {
    val candidate = (str.head + 1).toChar
    if (candidate - 'a' >= p)
      println("NO")
    else
      println(candidate)
  } else if (n == 2) {
    println((str.last + 1 until ('a' + p)).find(i => i != str.head) match {
      case Some(x) => str.head.toString + x
      case None if str.head + 1 < 'a' + p => (str.head + 1).toChar.toString + 'a'
      case None => "NO"
    })
  } else {
    println(str.indices.reverse.find{
      case (index) =>
        (str(index) + 1 until ('a' + p)).exists(i => index == 0 ||
          ((str(index - 1) != i) && (index == 1 || str(index - 2) != i)))
    } match {
      case None => "NO"
      case Some(index) =>
        val l = (str(index) + 1 until ('a' + p)).find(i => index == 0 ||
          ((index == 1 || str(index - 1) != i) && (index == 2 || str(index - 2) != i))).map(_.toChar).get
        val prefix = l :: str.toCharArray.take(index).toList.reverse
        (index + 1 until n).foldLeft(prefix) {
          case (pref, i) => ('a' to ('a' + p).toChar).find(i => !pref.take(2).contains(i)).get :: pref
        }.reverse.mkString
    })
  }

}


You are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).

The first line contains two integers n and k (1 ≤ n ≤ 3·105, 0 ≤ k ≤ n) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 1) — the elements of a.

On the first line print a non-negative integer z — the maximal value of f(a) after no more than k changes of zeroes to ones. On the second line print n integers aj — the elements of the array a after the changes. If there are multiple answers, you can print any one of them.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().filter(_ != ' ')
  val res = data.indices.foldLeft((0, 0, k, 0, (0, 0))) {
    case (acc@(max, soFar, leftover, start, maxPair), i) =>
//      println(acc)
      if (data(i) == '1' || leftover > 0) {
        val nLeftover = if (data(i) == '0') leftover - 1 else leftover
        if (max < soFar + 1)
          (soFar + 1, soFar + 1, nLeftover, start, (start, i))
        else
          (max, soFar + 1, nLeftover, start, maxPair)
      }
      else {
        val nStart = (start to i).find(i => data(i) == '0').get + 1
        (max, soFar + start - nStart + 1, 0, nStart, maxPair)
      }
  }
  println(res._1)
  println(data.indices.map{ i =>
    if (k > 0 && i >= res._5._1 && i <= res._5._2)
      '1'
    else
      data(i)
  }.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().filter(_ != ' ')
  val res = data.indices.foldLeft((0, 0, k, 0, (0, 0))) {
    case (acc@(max, soFar, leftover, start, maxPair), i) =>
//      println(acc)
      if (data(i) == '1' || leftover > 0) {
        val nLeftover = if (data(i) == '0') leftover - 1 else leftover
        if (max < soFar + 1)
          (soFar + 1, soFar + 1, nLeftover, start, (start, i))
        else
          (max, soFar + 1, nLeftover, start, maxPair)
      }
      else {
        val nStart = (start to i).find(i => data(i) == '0').get
//        println("nStart = " + nStart)
        (max, soFar + start - nStart, Math.max(0, nStart - start - 1), nStart + 1, maxPair)
      }
  }
//  println(res)
  println(res._1)
  println(data.indices.map{ i =>
    if (k > 0 && i >= res._5._1 && i <= res._5._2)
      '1'
    else
      data(i)
  }.mkString(" "))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().filter(_ != ' ')
  val res = data.indices.foldLeft((0, 0, k, 0, (0, 0))) {
    case (acc@(max, soFar, leftover, start, maxPair), i) =>
//      println(acc)
      if (data(i) == '1' || leftover > 0) {
        val nLeftover = if (data(i) == '0') leftover - 1 else leftover
        if (max < soFar + 1)
          (soFar + 1, soFar + 1, nLeftover, start, (start, i))
        else
          (max, soFar + 1, nLeftover, start, maxPair)
      }
      else {
        val nStart = (start to i).find(i => data(i) == '0').get
//        println("nStart = " + nStart)
        (max, soFar + start - nStart, Math.max(0, nStart - start - 1), nStart + 1, maxPair)
      }
  }
//  println(res)
  println(res._1)
  println(data.indices.map{ i =>
    if (i >= res._5._1 && i <= res._5._2)
      '1'
    else
      data(i)
  }.mkString(" "))
}


Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \times 3$$$ square.  What is the maximum side length of the square Ujan can get?

The first line of input contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$), the lengths of the planks.

For each of the test cases, output a single integer, the maximum possible side length of the square.

NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \times 4$$$ square.In the third sample, the maximum possible square is $$$1 \times 1$$$ and can be taken simply as any of the planks.

import scala.io.StdIn
import scala.util.control.Breaks

object Main extends App{

    val k = StdIn.readLine.toInt
    for (i <- 0 until k) {
        val n = StdIn.readLine.toInt
        val arr = StdIn.readLine.split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

        var res = 0
        var key = true
        var j = 0
        while (key && j < n) {
            if ( j < arr(j) )
                res += 1
            else
                key = false
            j += 1
        }

//        arr.foreach(it => print(s"$it "))
        println(res)
    }

}

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

  override def solve(io: IO) = io.repeat {
    val plans = io.read[Vector[Int]].sorted(desc[Int])

    val ans = plans.zipWithIndex map {
      case (l, i) => l min (i + 1)
    }

    io.write(ans.max)
  }
}
/****************************[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 = {printer.print(obj); this}
  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 = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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

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

object A {
  def main(args: Array[String]): Unit = {
    val k = scala.io.StdIn.readInt()
    val result = for (i <- 1 to k) yield {
      val test = new A
      test.solution
    }
    println(result.mkString("\n"))
  }
}

class A {

  def solution(): Int = {
    val n = scala.io.StdIn.readInt()
    val numbers = scala.io.StdIn.readLine().split(" ")
    val planks = for (number <- numbers) yield number.toInt
    maxSquare(planks.sortWith(_ < _), 0)
  }

  private def maxSquare(planks: Array[Int], i: Int): Int = {
    if (i >= planks.length) 0
    else (planks.length - i).min(planks(i)).max(maxSquare(planks, i + 1))
  }

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_599_A {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    //runTest(Test.sa1)
    //debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val k = readLine.int

    for(i <- 1 to k) {
      val n = readLine.int
      val planks = new Array[Int](n)
      val lp = readLine
      for (p <- 0 until n) {
        planks(p) = lp.int
      }

      val st = planks.sorted.reverse
      var res = 0
      var min = st(0)
      for(p <- 0 until st.size) {
        if (st(p) < min) min = st(p)
        if (min >= (p+1)) res = p+1
      }
      outLn(res)
    }

//    debug("n = " + n)

    //---------------------------- parameters reading :end

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
4
5
4 3 1 4 5
4
4 4 4 4
3
1 1 1
5
5 5 1 1 5
"""

val sa2 = """
101
"""

val sa3 = """
10100
"""
 }
}


Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (li, ri) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n - 1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.

The first line contains a positive integer n (1 ≤ n ≤ 100). The (i + 1)-th line contains integers li and ri (0 ≤ li < ri ≤ 100) — the endpoints of the corresponding segment for the i-th student.

On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.

NoteNote that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments.In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1.In the second test sample Alexey may dry his clothes on segments (0, 1) and (5, 7). Overall length of these segments is 3.

object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val in = Array.fill(n)((sc.nextInt(), sc.nextInt()))
  var t = Array.fill(100)(false)
  for (r <- in.tail) {
    for (i <- r._1 until r._2) {
      t(i) = true;
    }
  }
  println(t.slice(in.head._1, in.head._2).count(_ == false));
}


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

In the first line of input there is one integer $$$n$$$ ($$$0 \le n \le 6$$$) — the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

In the first line output one integer $$$m$$$ ($$$0 \le m \le 6$$$) — the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six.

object tanya extends App{
var a = readInt
var sum = 7
val stones = scala.collection.mutable.Map("purple" -> "Power", "green" -> "Time", "blue" -> "Space", "orange" -> "Soul", "red" -> "Reality", "yellow" -> "Mind")

for(i <- 0 to a){
    val stone = readLine
    stones -= stone
    sum = sum - 1
}
println(sum)
stones.values.map(println(_))
}

/**
  * @author ShankarShastri
  *         Algorithm: CF_485_DIV_2_1 (http://codeforces.com/contest/987/problem/A)
  */

//package programming

import scala.io.StdIn._
import scala.annotation.tailrec

object CF_485_DIV_2_1 {

//  the Power Gem of purple color,
//  the Time Gem of green color,
//  the Space Gem of blue color,
//  the Soul Gem of orange color,
//  the Reality Gem of red color,
//  the Mind Gem of yellow color.

  def main(args: Array[String]): Unit = {
    val n = readInt
    val thanosMap = Map[String, String](("purple", "Power"), ("green", "Time"), ("blue", "Space"),
      ("orange", "Soul"), ("red", "Reality"), ("yellow","Mind"))
    if(n == 0) {
      println(thanosMap.size)
      thanosMap.values.map(println(_))
    } else {
      val mapResult = (0 until n).foldLeft(thanosMap)((a,b) => {
        val k = readLine
        a - k
      })
      println(mapResult.size)
      mapResult.values.map(println(_))
    }
  }
}

object A extends App {
  val l = List(
    "purple" -> "Power",
    "green" -> "Time",
    "blue" -> "Space",
    "orange" -> "Soul",
    "red" -> "Reality",
    "yellow" -> "Mind"
  )

  val n = scala.io.StdIn.readInt()
  val cs = (0 until n).foldLeft(List.empty[String])((cs, _) => scala.io.StdIn.readLine() :: cs)

  val m = l.foldLeft(List.empty[String]) { case (rs, (c, r)) =>
      if (cs.contains(c)) rs
      else r :: rs
  }

  println(m.length)
  println(m.mkString("\n"))
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val dist = Map("purple" -> "Power", "green" -> "Time", "blue" -> "Space",
      "orange" -> "Soul", "red" -> "Reality", "yellow" -> "Mind")
    val m = StdIn.readLine.toInt
    val noNeed = (0 until m).map(_ => StdIn.readLine).map(dist(_))
    val all = dist.values
    val need = all.map(item => if (noNeed.contains(item)) None else Some(item))
    println(need.count(_.isDefined))
    need.foreach(_.foreach(println(_)))
  }
}

/**
  * @author ShankarShastri
  *         Algorithm: CF_485_DIV_2_1 (http://codeforces.com/contest/987/problem/A)
  */

//package programming

import scala.io.StdIn._
import scala.annotation.tailrec

object CF_485_DIV_2_1 {

//  the Power Gem of purple color,
//  the Time Gem of green color,
//  the Space Gem of blue color,
//  the Soul Gem of orange color,
//  the Reality Gem of red color,
//  the Mind Gem of yellow color.

  def main(args: Array[String]): Unit = {
    val n = readInt
    val thanosMap = Map[String, String](("purple", "Power"), ("green", "Time"), ("blue", "Space"),
      ("orange", "Soul"), ("red", "Reality"), ("yellow","Mind"))
    if(n == 0) {
      println(thanosMap.size)
      thanosMap.values.map(println(_))
    } else {
      val mapResult = (0 until n).foldLeft(thanosMap)((a,b) => {
        val k = readLine
        println(a - k)
        a - k
      })
      println(mapResult.size)
      mapResult.values.map(println(_))
    }
  }
}


Consider a simplified penalty phase at the end of a football match.A penalty phase consists of at most $$$10$$$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $$$7$$$-th kick the first team has scored $$$1$$$ goal, and the second team has scored $$$3$$$ goals, the penalty phase ends — the first team cannot reach $$$3$$$ goals.You know which player will be taking each kick, so you have your predictions for each of the $$$10$$$ kicks. These predictions are represented by a string $$$s$$$ consisting of $$$10$$$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way:  if $$$s_i$$$ is 1, then the $$$i$$$-th kick will definitely score a goal;  if $$$s_i$$$ is 0, then the $$$i$$$-th kick definitely won't score a goal;  if $$$s_i$$$ is ?, then the $$$i$$$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase — you may know that some kick will/won't be scored, but the referee doesn't.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1\,000$$$) — the number of test cases. Each test case is represented by one line containing the string $$$s$$$, consisting of exactly $$$10$$$ characters. Each character is either 1, 0, or ?.

For each test case, print one integer — the minimum possible number of kicks in the penalty phase.

NoteConsider the example test:In the first test case, consider the situation when the $$$1$$$-st, $$$5$$$-th and $$$7$$$-th kicks score goals, and kicks $$$2$$$, $$$3$$$, $$$4$$$ and $$$6$$$ are unsuccessful. Then the current number of goals for the first team is $$$3$$$, for the second team is $$$0$$$, and the referee sees that the second team can score at most $$$2$$$ goals in the remaining kicks. So the penalty phase can be stopped after the $$$7$$$-th kick.In the second test case, the penalty phase won't be stopped until all $$$10$$$ kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the $$$6$$$-th kick, the first team has scored $$$0$$$ goals and the second team has scored $$$3$$$ goals, and the referee sees that the first team can score at most $$$2$$$ goals in the remaining kicks. So, the penalty phase can be stopped after the $$$6$$$-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the $$$9$$$-th kick.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    def definitely(pf: PartialFunction[(Char, Int), Int]): Seq[Int] = s.zipWithIndex.collect(pf)

    val first =
      definitely {
        case ('0' | '?', i) if i % 2 == 1 => i
        case ('1' | '?', i) if i % 2 == 0 => i
      } applyOrElse (5, (_: Int) => 9)

    val second =
      definitely {
        case ('0' | '?', i) if i % 2 == 0 => i
        case ('1' | '?', i) if i % 2 == 1 => i
      } applyOrElse (5, (_: Int) => 9)

    val answer = (first min second) + 1

    println(answer)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    val a = s.zipWithIndex.collect {
      case ('0' | '?', i) if i % 2 == 1 => i
      case ('1' | '?', i) if i % 2 == 0 => i
    }
    val b = s.zipWithIndex.collect {
      case ('0' | '?', i) if i % 2 == 0 => i
      case ('1' | '?', i) if i % 2 == 1 => i
    }

    val ans = (a.applyOrElse(5, (_: Int) => 9) min b.applyOrElse(5, (_: Int) => 9)) + 1

    println(ans)
  }
}


Amugae has a sentence consisting of $$$n$$$ words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of the words in Amugae's sentence. The second line contains $$$n$$$ words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits ('A', 'B', ..., 'Z', 'a', 'b', ..., 'z', '0', '1', ..., '9'). The total length of the words does not exceed $$$10^6$$$.

In the only line output the compressed word after the merging process ends as described in the problem.

object E extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(n) = readInts(1)

  val PRIME = 1303L
  val MOD = 1000000007L
  var pmul = 1L

  val ps, pinvs = Array.ofDim[Long](1000001)
  val hs, hs2 = Array.ofDim[Long](1000001)

  def modInverse(a: Long, m: Long): Long = {

    def modInv(a: Long, m: Long, x: Long, y: Long): Long =
      if (m == 0) x else modInv(m, a % m, y, x - y * (a / m))

    val inv = modInv(a, m, 1, 0)
    if (inv < 0) inv + m else inv
  }

  for (i <- ps.indices) {
    ps(i) = pmul
    pinvs(i) = modInverse(pmul, MOD)
    pmul = pmul * PRIME % MOD
  }

  def hash(from: Int, until: Int) = (hs(until) - hs(from) + MOD) * pinvs(from) % MOD

  def hash2(from: Int, until: Int) = (hs2(until) - hs2(from) + MOD) * pinvs(from) % MOD

  val ws = readLine.split(' ')

  val w0 = ws.head
  var h = 0L
  for (i <- 0 to w0.length) {
    hs(i) = h
    if (i < w0.length) h = (h + w0(i) * ps(i)) % MOD
  }

  val resBuilder = new StringBuilder(w0)

  def can(i: Int): Boolean = {
    hash(resBuilder.size - i, resBuilder.size) == hash2(0, i)
  }

  for (wi <- 1 until n) {
    val w = ws(wi)

    var h2 = 0L
    for (i <- 0 to w.length) {
      hs2(i) = h2
      if (i < w.length) h2 = (h2 + w(i) * ps(i)) % MOD
    }
    var prefLen = 0
    var drop = 0
    while (prefLen <= w.length && prefLen <= resBuilder.size) {
      if (can(prefLen)) drop = prefLen
      prefLen += 1
    }
    for (i <- drop until w.length) {
      val c = w(i)
      resBuilder += c
      h = (h + c * ps(resBuilder.size - 1)) % MOD
      hs(resBuilder.size) = h
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(resBuilder.result())

  Console.flush
}


It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds.Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?

The first line contains three integers n, m, k (1 ≤ n, m ≤ 105, 1 ≤ k ≤ 109) — the number of fish caught by Alice and Bob respectively, and the number of fish species. The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob. Note that one may have caught more than one fish for a same species.

Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise.

NoteIn the first sample, if w1 = 1, w2 = 2, w3 = 2.5,  then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5.In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish.

object Main {
  def main(args: Array[String]) = {
    val line1 = readLine().split(" ").map(_.toInt)
    val n = line1(0)
    val m = line1(1)
    val k = line1(2)

    val alice = readLine().split(" ").map(_.toInt).sorted.reverse
    val bob = readLine().split(" ").map(_.toInt).sorted.reverse.filter(_ >= alice.last)

    val possible = alice.size > bob.size ||
      alice.zip(bob).exists((x: (Int, Int)) => x._1 > x._2)

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

object Main {
  def main(args: Array[String]) = {
    val line1 = readLine().split(" ").map(_.toInt)
    val n = line1(0)
    val m = line1(1)
    val k = line1(2)

    val alice = readLine().split(" ").map(_.toInt).sorted
    val bob = readLine().split(" ").map(_.toInt).sorted.filter(_ >= alice(0))

    val possible = alice.size > bob.size ||
      alice.zip(bob).contains((x: (Int, Int)) => x._1 > x._2)

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

object Main {
  def main(args: Array[String]) = {
    val line1 = readLine().split(" ").map(_.toInt)
    val n = line1(0)
    val m = line1(1)
    val k = line1(2)

    val alice = readLine().split(" ").map(_.toInt).sorted
    val bob = readLine().split(" ").map(_.toInt).sorted.filter(_ >= alice(0))

    val possible = alice.size > bob.size ||
      alice.zip(bob).exists((x: (Int, Int)) => x._1 > x._2)

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


Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit.   For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \leq x_1, y_1, x_2, y_2 \leq 10^9)$$$, describing the next test case.

For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.

NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds.

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

    for (_ <- 1 to nextInt) {
      val x1, y1, x2, y2 = nextLong
      val dx = Math.abs(x1 - x2)
      val dy = Math.abs(y1 - y2)
      val n = if (dx == 0) dy
      else if (dy == 0) dx
      else dx + dy + 2

      out.println(n)
    }

    out.flush()
  }

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

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x1, y1, x2, y2) = readLine().split(" ").map(_.toInt)

    val t1 = (x2 - x1).abs
    val t2 = (y2 - y1).abs

    val ans = t1 + t2 + (if (t1 == 0 || t2 == 0) 0 else 2)

    println(ans)
  }
}


You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!   Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — the description of the $$$i$$$-th blow.

For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.  If Zmei Gorynuch cannot be defeated print $$$-1$$$.

NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?

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 = {
    REP(ni()) { _ =>
      val N, X = ni()
      var lastBlow, eachHit = -1e9.toInt
      REP(N) { _ =>
        val d, h = ni()
        lastBlow = max(d, lastBlow)
        eachHit = max(eachHit, d - h)
      }
      debug(s"lastBlow:$lastBlow eachHit:$eachHit")
      if (eachHit <= 0 && X > lastBlow) out.println(-1)
      else {
        val remain = X - lastBlow
        if (remain > 0) {
          val ans = (remain + eachHit - 1) / eachHit + 1
          out.println(ans)
        } else {
          out.println(1)
        }
      }
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val input = new Scanner(System.in);
    val t = input.nextInt()
    for (_ <- 0 until t) {
      val n = input.nextInt()
      val x = input.nextInt()
      val d = new Array[Int](n)
      val h = new Array[Int](n)

      for (i <- 0 until n) {
        d(i) = input.nextInt()
        h(i) = input.nextInt()
      }
      var max = Int.MinValue;
      for (i <- 0 until n) {
        max = Math.max(max, d(i))
      }
      var max2 = Int.MinValue;
      for (i <- 0 until n) {
        max2 = Math.max(max2, d(i) - h(i))
      }
      var ans = 0
      if(max >= x){
        ans = 1
      }else /* max < x */{
        if(max2 <= 0){
          ans = -1;
        }else{
          val rem = x - max;
          ans = 1
          ans += (rem + max2 -1)/max2
        }
      }

      System.out.println(ans)

    }
  }
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer

  import scala.io.Codec
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
     * Unlike Java's scanner which returns till end of current line, this actually returns the next line
     *
     * @see line() if you want the Java behaviour
     */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

object B {

  def main(args: Array[String]): Unit = {}
  @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)) }

  val Array(t) = readInts(1)

  for (_ <- 1 to t) {
    val Array(n, x) = readInts(2)
    val blows = Array.fill(n) {
      readLongs(2)
    }
    val maxD = blows.map(_.head).max
    val maxKill = blows.map(b => b(0) - b(1)).max
    val rem = x - maxD
    val res = if (rem <= 0) 1 else if (maxKill <= 0) -1 else 1 + (rem + maxKill - 1) / maxKill
    println(res)
  }
}

import scala.annotation.tailrec
import scala.collection.mutable

object Main extends App {
  import scala.io.StdIn._
  val t = readInt()
  for (_ ← 0 until t) {
    val Array(n, x) = readLine.trim.split(' ').map(_.toInt)
    val blows = Array.fill(n){
      val Array(d, h) = readLine.trim.split(' ').map(_.toInt)
      Blow(d, h)
    }
    val fatal = blows.maxBy{_.damage}.damage
    if (x > fatal) {
      blows.filter(b ⇒ b.damage > b.heal) match {
        case e if e.nonEmpty ⇒
          val efficient = e.maxBy(_.pureDamage)
          println((x - fatal + efficient.pureDamage - 1) / efficient.pureDamage + 1)
        case _ ⇒ println(-1)
      }
    }else {
      println(1)
    }
  }
}
case class Blow(damage: Long, heal: Long) {
  def pureDamage: Long = damage - heal
}


A subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.

The first line contains an integer n (3 ≤ n ≤ 3000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi, yi (1 ≤ xi, yi ≤ n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi ≠ yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.

Print n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0.

import scala.io.StdIn

/**
 * @author chengyi
 */
object Subway {

  //vertice and neighbors
  var va:Array[List[Int]] = null
  var visited:Array[(Int,Boolean)] = null
  //
  var circleList:List[Int]=null
  //distance to ring
  var dist:Array[Int] = null

  //parent: 0 means root node
  def treeNeighbor(parent:Int, current:Int):List[Int]={
    if (parent== 0){
      //return all neighbor
      va(current-1)
    }else{
      //return neighbor except parent
      va(current-1) diff List(parent)
    }
  }

  def nonCircleNeighbor(parent:Int, current:Int):List[Int]={
    va(current-1).filter { x => !circleList.contains(x) && x!=parent }
  }

  def foundCircleStop(parent:Int, current:Int):Boolean={
    if (!circleList.isEmpty){
      return true
    }

    if (visited(current-1)._2){
      //output the circle list
      var p = parent
      circleList = List(current)
      while (p!=current){
        circleList = circleList:+ p
        p = visited(p-1)._1
      }

      true
    }else{
      false
    }
  }

  def neverStop(parent:Int, current:Int):Boolean={
    false
  }

  //
  def markDepthAction(parent:Int, visit:Int):Unit={
    if (parent==0){
      dist(visit-1) =0
    }else{
      dist(visit-1)=dist(parent-1)+1
    }
  }
  //
  def markVisitedAndParentAction(parent:Int, visit:Int):Unit={
    visited(visit-1)=(parent,true)
  }

  //
  def dfs(parent:Int, cur:Int, neigborFun:((Int,Int)=>List[Int]), stopFun:((Int,Int)=>Boolean), actionFun:((Int,Int)=>Unit)):Unit={
    actionFun(parent, cur)

    //println(visited.toList)

    val neighbors = neigborFun(parent, cur)

    //println("neighbors of cur:" + cur)
    //neighbors.map { x => print(x+",") }
    //println()

    var i =0;
    var fin=false
    while (i<neighbors.length && !fin){
      val x = neighbors(i)
      if (!stopFun(cur, x)){
        dfs(cur, x, neigborFun, stopFun, actionFun)
      }else{
        fin = true
      }
      i = i+1
    }
  }

  def distance(l:IndexedSeq[String]):String={
    val n = l.size

    va = Array.fill(n)(List())
    visited = Array.fill(n)((-1,false))
    dist = Array.fill(n)(0)
    circleList = List.empty

    l.map { x => {
        val ii = x.split(" ").map{y=>y.toInt}
        va(ii(0)-1) = va(ii(0)-1):+ii(1)
        va(ii(1)-1) = va(ii(1)-1):+ii(0)
      }
    }

    //dfs to detect ring, output to circle list

    dfs(0, 1, treeNeighbor, foundCircleStop, markVisitedAndParentAction)

    //println("circleList:" + circleList)

    //output to distance array
    circleList.map { x => {
        dfs(0, x, nonCircleNeighbor, neverStop, markDepthAction)
      }
    }

    dist.mkString(" ")
  }

  def main(args:Array[String]){
    //n>=3
    val n = StdIn.readLine().toInt
    val l = (1 to n).map{x=>StdIn.readLine()}
    println(distance(l))
  }

}


Phoenix has a string $$$s$$$ consisting of lowercase Latin letters. He wants to distribute all the letters of his string into $$$k$$$ non-empty strings $$$a_1, a_2, \dots, a_k$$$ such that every letter of $$$s$$$ goes to exactly one of the strings $$$a_i$$$. The strings $$$a_i$$$ do not need to be substrings of $$$s$$$. Phoenix can distribute letters of $$$s$$$ and rearrange the letters within each string $$$a_i$$$ however he wants.For example, if $$$s = $$$ baba and $$$k=2$$$, Phoenix may distribute the letters of his string in many ways, such as:   ba and ba  a and abb  ab and ab  aa and bb But these ways are invalid:   baa and ba  b and ba  baba and empty string ($$$a_i$$$ should be non-empty) Phoenix wants to distribute the letters of his string $$$s$$$ into $$$k$$$ strings $$$a_1, a_2, \dots, a_k$$$ to minimize the lexicographically maximum string among them, i. e. minimize $$$max(a_1, a_2, \dots, a_k)$$$. Help him find the optimal distribution and print the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$.String $$$x$$$ is lexicographically less than string $$$y$$$ if either $$$x$$$ is a prefix of $$$y$$$ and $$$x \ne y$$$, or there exists an index $$$i$$$ ($$$1 \le i \le min(|x|, |y|))$$$ such that $$$x_i$$$ < $$$y_i$$$ and for every $$$j$$$ $$$(1 \le j < i)$$$ $$$x_j = y_j$$$. Here $$$|x|$$$ denotes the length of the string $$$x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case consists of two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$) — the length of string $$$s$$$ and the number of non-empty strings, into which Phoenix wants to distribute letters of $$$s$$$, respectively. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases is $$$\le 10^5$$$.

Print $$$t$$$ answers — one per test case. The $$$i$$$-th answer should be the minimal possible value of $$$max(a_1, a_2, \dots, a_k)$$$ in the $$$i$$$-th test case.

6
4 2
baba
5 2
baacb
5 3
baacb
5 3
aaaaa
6 4
aaxxzz
7 1
phoenix

NoteIn the first test case, one optimal solution is to distribute baba into ab and ab. In the second test case, one optimal solution is to distribute baacb into abbc and a.In the third test case, one optimal solution is to distribute baacb into ac, ab, and b.In the fourth test case, one optimal solution is to distribute aaaaa into aa, aa, and a.In the fifth test case, one optimal solution is to distribute aaxxzz into az, az, x, and x.In the sixth test case, one optimal solution is to distribute phoenix into ehinopx.

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

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s           = scala.io.StdIn.readLine().sorted

    val ans =
      if (s(0) != s(k - 1) || k == n) s(k - 1).toString
      else if (s(k) != s(n - 1)) s(0).toString + s.slice(k, n)
      else s(0) + s(k).toString * ((n - 1) / k)

    println(ans)
  }
}

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

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s           = scala.io.StdIn.readLine().sorted

    val (a, b)   = s.splitAt(k)
    val (ah, al) = (a.head.toString, a.last.toString)

    val ans =
      if (ah != al || b.isEmpty) al
      else {
        val (bh, bl) = (b.head.toString, b.last.toString)

        ah + (if (bh != bl) b else bh * ((n - 1) / k))
      }

    println(ans)
  }
}

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

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s           = scala.io.StdIn.readLine().sorted

    def lexical(str: String, pref: String = ""): String =
      if (str.isEmpty) pref
      else {
        val (l, r) = str.splitAt(k)

        lexical(r, pref + l.last)
      }

    val ans = lexical(s)

    println(ans)
  }
}


Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.

In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week).

Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.

NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25.

//package solutions

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

import scala.collection.mutable

/**
  * @author traff
  */

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

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

    out.close()
  }

  def run(s: Scanner, out: PrintWriter): Unit = {

    val n = s.nextInt()
    val k = s.nextInt()

    val a = new Array[Int](n)
    val b = new Array[Int](n)

    for (i <- a.indices) {
      a(i) = s.nextInt()
    }

    for (i <- b.indices) {
      b(i) = s.nextInt()
    }

    val d = a.zip(b).map(d => d._1 - d._2).zipWithIndex.sortWith((a, b) => a._1 < b._1)

    var res = 0
    d.take(k).foreach(t => {
      res += a(t._2)
      b(t._2) = Integer.MAX_VALUE
      a(t._2) = 0
    })

    res += a.zip(b).foldLeft(0)((s, b) => s + math.min(b._1, b._2))

    out.println(res)

  }

}

import java.util.Scanner

/**
  * Created by huangdongfa on 17/3/7.
  */
object App {
    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val n = scanner.nextInt
        val k = scanner.nextInt
        val a = new Array[Int](n)
        val b = new Array[Int](n)
        for (i <- a.indices) a(i) = scanner.nextInt
        for (j <- b.indices) b(j) = scanner.nextInt

        val sum = a.zip(b).sortWith((a, b) => a._1 - a._2 < b._1 - b._2).zipWithIndex.foldLeft(0) {(s, c) => {
            if (c._2 < k || c._1._1 - c._1._2 < 0) {
                s + c._1._1
            }
            else {
                s + c._1._2
            }
        }}
        System.out.println(sum)
    }
}


Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.

The first line of the input contains integers n and m (1 ≤ n, m ≤ 100) — the number of buttons and the number of bulbs respectively.  Each of the next n lines contains xi (0 ≤ xi ≤ m) — the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 ≤ yij ≤ m) — the numbers of these bulbs.

If it's possible to turn on all m bulbs print "YES", otherwise print "NO".

NoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.

/*
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream
*/

object bulbs{
  val MAX_M = 105

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

    //System.setIn(new FileInputStream("src/bulbs.in"))
    //System.setOut(new PrintStream(new FileOutputStream("src/bulbs.out")))

    val Array(n, m) = readLine.split(" ").map(_.toInt)
    var open = Array.fill[Boolean](MAX_M)(false)
    for(i <- 1 to n) {
      val (Array(nb), bulbs) = readLine.split(" ").map(_.toInt).splitAt(1)
      for(j <- 0 until nb) {
        open(bulbs(j)) = true
      }
    }

    var close_all = "YES"
    for(i <- 1 to m) {
      if(!open(i)) {
        close_all = "NO"
      }
    }
    println(close_all)
  }
}

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

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
    val s = new mutable.BitSet()
    for (i <- 0 until n) {
      StdIn.readLine().split(" ").map(_.toInt - 1).drop(1).foreach(s.add(_))
    }
    println(if (s.size == m) "YES" else "NO")
  }
}

import scala.io.Source

object CF338A {
    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val b = new Array[Boolean](m)
        for (i <- 0 until n) {
            ss = r.readLine().split(" ")
            val k = ss(0).toInt
            for (j <- 1 until k + 1) {
                val index = ss(j).toInt
                b(index - 1) = true
            }
        }
        var result = "YES"
        for (i <- 0 until m) {
            if (!b(i)) {
                result = "NO"
            }
        }
        println(result)
    }
}

import scala.collection.mutable.ArrayBuffer

object Main extends App {
    val arr = Console.in.readLine().split(' ')
    val n = arr(0).toInt
    val q = arr(1).toInt
    val bulbsState = new Array[Boolean](q)
    for(i <- 0 until n){
      val arr = Console.in.readLine().split(' ')
      val c = arr(0).toInt
      for(j <- 1 to c){
        bulbsState(arr(j).toInt - 1) = true
      }
    }
    var flag = true
    for(b <- bulbsState if b == false) flag = false
    println(if(flag) "YES" else "NO")
}

import scala.collection.immutable.HashSet
import scala.io.StdIn

/**
  * Created by shvedchikov on 13.01.16.
  */
object Codeforces extends App {
    override def main(args: Array[String]) {
        lamps()
    }

    // http://codeforces.com/problemset/problem/615/A
    def lamps(): Unit = {
        val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
        (1 to n)
            .map(_ => StdIn.readLine().split(" ").map(_.toInt))
            .foldLeft(HashSet.empty[Int])((all, cur) => all ++ (cur match {
                case Array(xi: Int, rest @_*) if rest.length.equals(xi) => rest
                case _ => Seq.empty[Int]
            })).size match {
            case `m` => print("YES")
            case _ => print("NO")
        }
    }
}

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

/**
  * Created by hsleep on 2016. 1. 8..
  */
object ASolution extends App {
  val Array(numOfButtons, numberOfBulbs) = StdIn.readLine().split(' ').map(_.toInt)

  val setOfBulbs: mutable.Set[Int] = mutable.Set[Int]()
  for {
    i <- 0 until numOfButtons
    if setOfBulbs.size != numberOfBulbs
  } {
    setOfBulbs ++= StdIn.readLine().split(' ').map(_.toInt).tail
  }

  setOfBulbs.size == numberOfBulbs match {
    case true => println("YES")
    case _ => println("NO")
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val lamps = Array.ofDim[Boolean](m)
  (1 to n).foreach { _ =>
    in.next().split(' ').map(_.toInt - 1).tail.foreach(j => lamps(j) = true)
  }
  if (lamps.forall(_ == true))
    println("YES")
  else
    println("NO")
}

object A615 {
  @inline def read = scala.io.StdIn.readLine

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

  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, m) = readInts(2)
    val isOn = Array.fill(m)(false)
    for(i <- 0 until n) {
      val tl = tokenizeLine
      val number = tl.nextToken.toInt
      val input = Array.fill(number)(tl.nextToken.toInt)
      for(j <- input.indices) {
        isOn(input(j)-1) = true
      }
    }

    println(if(isOn.forall(identity)) "YES" else "NO")
  }
}

import scala.collection._

object A extends App {

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

  val Array(n, m) = readInts(2)

  val lamps = mutable.Set.empty[Int]

  for (_ <- 1 to n) {
    lamps ++= readLine.split(" ").map(_.toInt).drop(1)
  }

  println(if (lamps.size == m) "YES" else "NO")
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _615A extends CodeForcesApp {
  override type Result = Boolean

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, m) = (nextInt(), nextInt())
    val bulbs = ((1 to n) flatMap {i =>
      Seq.fill(nextInt())(nextInt())
    }).toSet
    (1 to m) forall bulbs.contains
  }

  override def format(result: Boolean) = if (result) "YES" else "NO"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

import java.util.Scanner

/**
  * Author: Svyatoslav Ilinskiy
  * Date: 08.01.16.
  */
object Problem1 {

  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val numButtons = sc.nextInt()
    val numBulbs = sc.nextInt()
    val bulbs = new Array[Boolean](numBulbs)
    (0 until numButtons).foreach { _ =>
      val numBulbsByThisButton = sc.nextInt()
      (0 until numBulbsByThisButton).foreach { _ =>
        bulbs.update(sc.nextInt() - 1, true)
      }
    }
    val res =
      if (bulbs.forall(b => b)) "YES"
      else "NO"
    println(res)
  }

}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val m = sc.nextInt()
    sc.nextLine()

    var bulb = new Array[Boolean](m+1)
    for(i <- 1 to n){
      val x = sc.nextInt()
      for(j <- 1 to x){
        val tmp = sc.nextInt()
        bulb(tmp) = true
      }
    }

    var flag = true
    for(i <- 1 to m)
      flag &= bulb(i)

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

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

/**
  * Created by hsleep on 2016. 1. 8..
  */
object ASolution extends App {
  val Array(numOfButtons, numberOfBulbs) = StdIn.readLine().split(' ').map(_.toInt)

  val setOfBulbs: mutable.Set[Int] = mutable.Set[Int]()
  for {
    i <- 0 until numOfButtons
    if setOfBulbs.size != numberOfBulbs
  } {
    setOfBulbs ++= StdIn.readLine().split(' ').map(_.toInt)
  }

  setOfBulbs.size == numberOfBulbs match {
    case true => println("YES")
    case _ => println("NO")
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val m = sc.nextInt()
    sc.nextLine()

    var bulb = new Array[Boolean](m+1)
    for(i <- 1 to n){
      val x = sc.nextLine().split(' ').map(_.toInt)

      for(e <- x)
        bulb(e) = true
    }

    var flag = true
    for(i <- 1 to m)
      flag &= bulb(i)

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

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val m = sc.nextInt()
    sc.nextLine()

    var bulb = new Array[Boolean](m+1)
    for(i <- 1 to n){
      try{
        val x = sc.nextLine().split(' ').map(_.toInt)
        for(e <- x)
          bulb(e) = true
      }
      catch{
        case e: NumberFormatException => ()
      }
    }

    var flag = true
    for(i <- 1 to m)
      flag &= bulb(i)

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


You are given an integer $$$n$$$. Check if $$$n$$$ has an odd divisor, greater than one (does there exist such a number $$$x$$$ ($$$x > 1$$$) that $$$n$$$ is divisible by $$$x$$$ and $$$x$$$ is odd).For example, if $$$n=6$$$, then there is $$$x=3$$$. If $$$n=4$$$, then such a number does not exist.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{14}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

For each test case, output on a separate line:    "YES" if $$$n$$$ has an odd divisor, greater than one;  "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).

import io.StdIn.readLine

object testing {
  def main(args: Array[String]): Unit = {
      val T = readLine().toInt
      for(_ <- 1 to T) {
        val N = readLine().toLong
        if((N & (N-1)) == 0){
          println("NO")
        }else{
          println("YES")
        }
      }
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    import io.StdIn.readLine

    val t = readLine().toInt
    for (_ <- 1 to t) {
      val n = readLine().toLong
      val answer =
        if ((n & (n - 1)) == 0)
          "NO"
        else
          "YES"
      println(answer)
    }
  }

}


There are $$$n$$$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.We want to plan a trip for every evening of $$$m$$$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:   Either this person does not go on the trip,  Or at least $$$k$$$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $$$a$$$ and $$$b$$$ are friends and $$$b$$$ and $$$c$$$ are friends, it does not necessarily imply that $$$a$$$ and $$$c$$$ are friends.For each day, find the maximum number of people that can go on the trip on that day.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$$$, $$$1 \le k < n$$$) — the number of people, the number of days and the number of friends each person on the trip should have in the group. The $$$i$$$-th ($$$1 \leq i \leq m$$$) of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1\leq x, y\leq n$$$, $$$x\ne y$$$), meaning that persons $$$x$$$ and $$$y$$$ become friends on the morning of day $$$i$$$. It is guaranteed that $$$x$$$ and $$$y$$$ were not friends before.

Print exactly $$$m$$$ lines, where the $$$i$$$-th of them ($$$1\leq i\leq m$$$) contains the maximum number of people that can go on the trip on the evening of the day $$$i$$$.

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

object E extends App {
  var input: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var output: BufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out))

  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(input.readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int() // people
  val m = int() // days
  val k = int() // friend limit

  val friends = Array.fill(n+1)(0)
  val days = new Array[(Int,Int)](m)
  val links = Array.fill(n+1)(new java.util.Stack[Int])

  for (i <- 0 until m) {
    read()
    val s = int()
    val f = int()
    days(i) = (s, f)
    links(s).add(f)
    links(f).add(s)
    friends(s) += 1
    friends(f) += 1
  }

  // friend counts at the end
  // days reversed

  val going = Array.fill(n+1)(true)
  var count = n
  val toRemove = new java.util.LinkedHashSet[Int]

  for (i <- 1 to n) {
    if (friends(i) < k)
      toRemove.add(i)
  }

  @inline
  final def reduce(i: Int) = {
    if (going(i)) {
      friends(i) -= 1
      if (friends(i) < k)
        toRemove.add(i)
    }
  }

  def update() = {
    while (!toRemove.isEmpty) {
      val r = toRemove.iterator().next()
      toRemove.remove(r)
      count -= 1
      going(r) = false
      links(r).forEach(reduce)
    }
  }

  val res: Array[Int] = days.reverse.map { case (s, f) =>
    update()
    links(s).pop()
    links(f).pop()
    if (going(s) && going(f)) {
      reduce(s)
      reduce(f)
    }
    count
  }
  res.reverse.foreach { c =>
    output.write(c.toString)
    output.newLine()
  }
  input.close()
  output.flush()
  output.close()
}