First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction —  it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.

The only line contains a string s (5 ≤ |s| ≤ 104) consisting of lowercase English letters.

On the first line print integer k — a number of distinct possible suffixes. On the next k lines print suffixes.  Print suffixes in lexicographical (alphabetical) order.

NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._

object _667C extends CodeForcesApp {
  override def apply(io: IO) = {
    val s = io[String]
    val ans = mutable.Set.empty[String]
    val seen = mutable.Set.empty[(Int, String)]

    def solve(l: Int, last: String): Unit = {
      val key = l -> last
      if (!(seen contains key)){
        def check(length: Int) = {
          val w = s.substring(l - length, l)
          if (last != w) {
            ans += w
            solve(l - length, w)
          }
        }
        if(l >= 7) check(2)
        if(l >= 8) check(3)
        val _ = seen += key
      }
    }
    solve(s.length, null)
    (io += ans.size).appendNewLine(ans.toSeq.sorted mkString "\n")
  }
}

/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline 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)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, java.awt._

object _667C extends CodeForcesApp {
  override def apply(io: IO) = {
    val s = io[String]
    val ans = mutable.Set.empty[String]
    val seen = mutable.Set.empty[Int]

    def solve(l: Int, last: String): Unit = if (!(seen contains l)){
      def check(length: Int) = {
        val w = s.substring(l - length, l)
        if (last != w) {
          ans += w
          solve(l - length, w)
        }
      }
      if(l >= 7) check(2)
      if(l >= 8) check(3)
      val _ = seen += l
    }
    solve(s.length, null)
    (io += ans.size).appendNewLine(ans.toSeq.sorted mkString "\n")
  }
}

/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline 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)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}


Polycarp wrote on the board a string $$$s$$$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.After that, he erased some letters from the string $$$s$$$, and he rewrote the remaining letters in any order. As a result, he got some new string $$$t$$$. You have to find it with some additional information.Suppose that the string $$$t$$$ has length $$$m$$$ and the characters are numbered from left to right from $$$1$$$ to $$$m$$$. You are given a sequence of $$$m$$$ integers: $$$b_1, b_2, \ldots, b_m$$$, where $$$b_i$$$ is the sum of the distances $$$|i-j|$$$ from the index $$$i$$$ to all such indices $$$j$$$ that $$$t_j > t_i$$$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $$$b_i$$$, Polycarp finds all such indices $$$j$$$ that the index $$$j$$$ contains a letter that is later in the alphabet than $$$t_i$$$ and sums all the values $$$|i-j|$$$.For example, if $$$t$$$ = "abzb", then:  since $$$t_1$$$='a', all other indices contain letters which are later in the alphabet, that is: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$;  since $$$t_2$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_2=|2-3|=1$$$;  since $$$t_3$$$='z', then there are no indexes $$$j$$$ such that $$$t_j>t_i$$$, thus $$$b_3=0$$$;  since $$$t_4$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_4=|4-3|=1$$$. Thus, if $$$t$$$ = "abzb", then $$$b=[6,1,0,1]$$$.Given the string $$$s$$$ and the array $$$b$$$, find any possible string $$$t$$$ for which the following two requirements are fulfilled simultaneously:  $$$t$$$ is obtained from $$$s$$$ by erasing some letters (possibly zero) and then writing the rest in any order;  the array, constructed from the string $$$t$$$ according to the rules above, equals to the array $$$b$$$ specified in the input data.

The first line contains an integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases in the test. Then $$$q$$$ test cases follow. Each test case consists of three lines:   the first line contains string $$$s$$$, which has a length from $$$1$$$ to $$$50$$$ and consists of lowercase English letters;  the second line contains positive integer $$$m$$$ ($$$1 \le m \le |s|$$$), where $$$|s|$$$ is the length of the string $$$s$$$, and $$$m$$$ is the length of the array $$$b$$$;  the third line contains the integers $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_i \le 1225$$$).  It is guaranteed that in each test case an answer exists.

Output $$$q$$$ lines: the $$$k$$$-th of them should contain the answer (string $$$t$$$) to the $$$k$$$-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.

NoteIn the first test case, such strings $$$t$$$ are suitable: "aac', "aab".In the second test case, such trings $$$t$$$ are suitable: "a", "b", "c".In the third test case, only the string $$$t$$$ equals to "aba" is suitable, but the character 'b' can be from the second or third position.

//package codeforces.contests._1367

object _4 {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val chars: List[(Char, Int)] = {
        val freq = new Array[Int](26)
        io.StdIn.readLine.foreach { c => freq(c - 'a') += 1 }

        freq.indices.map(i => ('a' + i).toChar -> freq(i)).reverse.toList
      }

      val m = io.StdIn.readInt

      val result = new Array[Char](m)

      val ms: Array[Int] = io.StdIn.readLine.split(" ").map(_.toInt)

      @scala.annotation.tailrec
      def loop(chars: List[(Char, Int)]): Unit = {
        val zeroIndexes = ms.indices.filter(ms(_) == 0)

        if (zeroIndexes.nonEmpty) {
          val (c, count) :: tail = chars

          if (count >= zeroIndexes.length) {

            zeroIndexes.foreach { i => ms(i) = -1; result(i) = c }

            zeroIndexes.foreach { z =>
              (z + 1 until m).foreach { r =>
                if (ms(r) > 0) {
                  ms(r) -= r - z
                }
              }

              (z - 1 to 0 by -1).foreach { l =>
                if (ms(l) > 0) {
                  ms(l) -= z - l
                }
              }
            }
          }
          loop(tail)
        }
      }

      loop(chars)

      println(result.mkString(""))
    }
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val a = readLine().toCharArray
      val m = readLine()
      val b = readIntLine()
      handle(a, b.toArray)
    }
  }

  def handle(arr: Array[Char], list: Array[Int]): Unit = {
    def findLetter(length: Int, list: List[(Char, Int)]): (Char, List[(Char, Int)]) = list match {
      case Nil => throw new IllegalStateException()
      case (c, r) :: rest => if (r >= length) (c, rest) else findLetter(length, rest)
    }

    var gr = arr.groupBy(i => i).map(tup => (tup._1, tup._2.length)).toList.sortBy(tup => tup._1).reverse

    var containsZero = true
    val t = Array.ofDim[Char](list.length)

    while (containsZero) {
      containsZero = false
      var l = List[Int]()
      for (i <- list.indices) {
        if (list(i) == 0)
          l = i :: l
      }
      if (l.nonEmpty) {
        containsZero = true
        val tup = findLetter(l.length, gr)
        val letter = tup._1
        gr = tup._2
        l.foreach(i => t(i) = letter)
        l.foreach(j => {
          list(j) = list(j) - 1
          for (i <- list.indices) {
            list(i) = list(i) - Math.abs(i - j)
          }
        })
      }
    }

    t.foreach(print)
    println()
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}

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

  val q = readInt()

  (0 until q).foreach { _ =>
    val s  = readLine()
    val m  = readInt()
    val bm = readLine().split(" ").map(_.toInt)

    var t = Array.ofDim[Char](m)

    val o = s.distinct.sorted(Ordering.Char.reverse).map(c => (c, s.count(c == _)))

    (0 until m).foldLeft((bm, 0)) {
      case ((bm, shift), k) =>
        val is = bm.zipWithIndex.collect { case (b, i) if b == 0 => i }

        val tfihs = o.indexWhere({ case (c, l) => l >= is.length }, shift)
        is.foreach(i => t(i) = o(tfihs)._1)

        (bm.zipWithIndex.map {
          case (0, _) | (-1, _) => -1
          case (b, j)           => is.foldLeft(b)((b, i) => b - (i - j).abs)
        }, tfihs + 1)
    }

    println(t.mkString)
  }
}

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

  val q = readInt()

  (0 until q).foreach { _ =>
    val s  = readLine()
    val m  = readInt()
    var bm = readLine().split(" ").map(_.toInt)

    var t  = Array.ofDim[Char](m)
    val o  = s.distinct.sorted(Ordering.Char.reverse).map(c => (c, s.count(c == _)))

    (0 until m).foldLeft(0) {
      case (prev, _) =>
        val is   = bm.zipWithIndex.collect { case (b, i) if b == 0 => i }
        val curr = o.indexWhere(_._2 >= is.length, prev)

        is.foreach(t(_) = o(curr)._1)

        (0 until m).foreach { j =>
          bm(j) = bm(j) match {
            case 0 | -1 => -1
            case b      => is.foldLeft(b)((b, i) => b - (i - j).abs)
          }
        }

        curr + 1
    }

    println(t.mkString)
  }
}

object Main extends App {
  val r = new FastScanner(java.lang.System.in)
  val o = new java.io.PrintWriter(java.lang.System.out)
  for(_ <- 1 to r.nextInt()) {
    val s = r.nextToken()
    val m = r.nextInt()
    val b = Array.fill(m)(r.nextInt())
    val c = Array.ofDim[Int](26)
    //val x = Array.ofDim[Int](m)
    for(k <- 0 until s.length) c(s(k).toInt - 97) += 1
    val used = Array.fill[Int](m)(-1)
    def loop(k: Int): Unit = {
      if(used.count { _ >= 0 } != m) {
        val l = (for(j <- 0 until m if (used(j) < 0) && b(j) == 0) yield j).toList
        for(j <- 0 until m if (used(j) < 0 && b(j) > 0); i <- l) {
          b(j) -= (j - i).abs
          require(b(j) >= 0)
        }
        for(i <- l) {
          used(i) = k
        }
        loop(k + 1)
      }
    }
    loop(0)
    val d = Array.ofDim[Int](m)
    for(i <- used) d(i) += 1
    val x = Array.ofDim[Char](m)
    var j = 25
    for(i <- 0 until m if (d(i) > 0)) {
      while(j >= 0 && c(j) < d(i)) j -= 1
      for(o <- 0 until m if used(o) == i) x(o) = (j + 97).toChar
      j -= 1
    }
    for(i <- x) o.print(i)
    o.println()
  }
  o.close()
}

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

object FastScanner {
  val zero = 0.toByte
  val cr = '\r'.toByte
  val nl = '\n'.toByte
  val BUFFER_SIZE = 0x10000
}

class FastScanner(private val input: java.io.InputStream) {
  private val b = new Array[Byte](FastScanner.BUFFER_SIZE)
  private var n = 0
  private var pos = 0
  private var eof = false
  private def read ():Boolean = {
    if (eof) {
      return false
    }
    pos = 0
    n = input.read(b)
    if (n < 0) {
      eof = true
    }
    n > 0
  }
  private def nextByte(): Byte = {
    if (pos >= n && !read ()) {
      0
    } else {
      val r = b(pos)
      pos += 1
      r
    }
  }
  def nextToken(k: Int = -1): String = {
    val sb = if(k >= 0) new StringBuilder(k) else new StringBuilder()
    var b = skipBlanks()
    assert(b > 0)
    while(b > 32) {
      sb.append(b.toChar)
      b = nextByte()
    }
    sb.toString
  }
  @tailrec
  private def skipBlanks(): Byte = {
    val b = nextByte()
    if(b > 32 || b < 1) b else skipBlanks()
  }
  def nextInt():Int = {
    val b = skipBlanks()
    @tailrec
    def f(t: Int): Int = {
      val b = nextByte ()
      if (b <= 32) t else f(10 * t + (b - 48))
    }
    require(b > 0)
    if (b < 48) -f(0) else f(b - 48)
  }
}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val a = readLine().toCharArray
      val m = readLine()
      val b = readIntLine()
      handle(a, b.toArray)
    }
  }

  def handle(arr: Array[Char], list: Array[Int]): Unit = {
    def findLetter(length: Int, list: List[(Char, Int)]): (Char, List[(Char, Int)]) = list match {
      case Nil => throw new IllegalStateException()
      case (c, r) :: rest => if (r >= length) (c, rest) else findLetter(length, rest)
    }

    var gr = arr.groupBy(i => i).map(tup => (tup._1, tup._2.length)).toList.sortBy(tup => tup._1).reverse

    var containsZero = true
    val t = Array.ofDim[Char](list.length)

    while (containsZero) {
      containsZero = false
      var l = List[Int]()
      for (i <- list.indices) {
        if (list(i) == 0)
          l = i :: l
      }
      if (l.nonEmpty) {
        containsZero = true
        val tup = findLetter(l.length, gr)
        val letter = tup._1
        gr = tup._2
        l.foreach(i => t(i) = letter)
        l.foreach(j => {
          list(j) = list(j) - 1
          for (i <- list.indices) {
            list(i) = list(i) - Math.abs(i - j)
          }
        })
      }
    }

    printArray(t)
  }

  def readIntLine(): List[Int] = {
    readLine().split(" ").map(_.toInt).toList
  }

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

  def readLongLine(): List[Long] = {
    readLine().split(" ").map(_.toLong).toList
  }

}


Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem. You are given four positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, such that $$$a \leq b \leq c \leq d$$$. Your task is to find three integers $$$x$$$, $$$y$$$, $$$z$$$, satisfying the following conditions: $$$a \leq x \leq b$$$. $$$b \leq y \leq c$$$. $$$c \leq z \leq d$$$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $$$x$$$, $$$y$$$, and $$$z$$$.Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given as four space-separated integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$1 \leq a \leq b \leq c \leq d \leq 10^9$$$).

For each test case, print three integers $$$x$$$, $$$y$$$, $$$z$$$  — the integers you found satisfying the conditions given in the statement. It is guaranteed that the answer always exists. If there are multiple answers, print any.

NoteOne of the possible solutions to the first test case:One of the possible solutions to the second test case:

import scala.io.StdIn

object Solution_A extends App {
  val T = StdIn.readInt()
  for (t <- 1 to T) {
    val input = StdIn.readLine().split(' ').map{_.toInt}
    println(s"${input(1)} ${input(2)} ${input(2)}")
  }
}


A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.

The first line of the input data contains numbers n and m (1 ≤ n, m ≤ 50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square.

Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val res = (1 to n)
    .map(_ => in.next())
    .dropWhile(!_.contains('*'))
    .reverse
    .dropWhile(!_.contains('*'))
    .reverse
  val (left, right) = res.foldLeft(m - 1, 0) {
    case (acc, line) if !line.contains('*') => acc
    case ((l, r), line) => (Math.min(l, line.indexOf('*')), Math.max(r, line.lastIndexOf('*')))
  }

  println(res.map(_.substring(left, right + 1)).mkString("\n"))
}

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

object ALetter extends App {

  val in = new InputReader(System.in)
  val n = in.nextInt
  val m = in.nextInt
  var arr = Array.ofDim[Char](n, m)
  var (minx, miny) = (Integer.MAX_VALUE, Integer.MAX_VALUE)
  var (maxx, maxy) = (-1, -1)
  for {
    i <- (0 until n)
    s = in.next
    j <- (0 until m)
  } {
    val cur = s(j)
    arr(i)(j) = cur
    if (cur == '.') {

    } else {
      if (i < miny) {
        miny = i
      }
      if (i >= maxy) {
        maxy = i
      }
      if (j < minx) {
        minx = j
      }
      if (j >= maxx) {
        maxx = j;
      }
    }

  }

  var i = miny;
  while (i <= maxy) {
    var j = minx;
    while (j <= maxx) {
      print(arr(i)(j))
      j += 1
    }
    println()
    i += 1
  }

  class InputReader {
    var reader: BufferedReader = null
    var tokenizer: StringTokenizer = null

    def this(stream: InputStream) {
      this()
      reader = new BufferedReader(new InputStreamReader(stream), 32768)
      tokenizer = null
    }

    def next: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens) {
        try {
          tokenizer = new StringTokenizer(reader.readLine)
        }
        catch {
          case e: IOException => {
            throw new RuntimeException(e)
          }
        }
      }
      return tokenizer.nextToken
    }

    def nextInt: Int = {
      return next.toInt
    }
  }

}

object A14 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val in = Array.fill(n)(read)
    val x1 = in.indexWhere(_.contains('*'))
    val x2 = in.lastIndexWhere(_.contains('*'))
    val y1 = in.map(_.indexWhere(_ == '*')).filter(_ != -1).min
    val y2 = in.map(_.lastIndexWhere(_ == '*')).filter(_ != -1).max

    for(i <- x1 to x2) {
      val buff = cu.ArrayBuffer.empty[Char]
      for(j <- y1 to y2) {
        buff.append(in(i)(j))
      }
      println(buff.mkString(""))
    }
  }

  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.util._
import java.lang._
import java.io._

object A {

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

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

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

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

  def solve = {
    val n = nextInt
    val m = nextInt
    val f = new Array[Array[Char]](n)
    for (i <- 0 until n) {
      f(i) = new Array[Char](m)
      f(i) = next.toCharArray
    }
    var left1 = (-1, -1)
    var right1 = (-1, -1)
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (f(i)(j) == '*' && left1._1 == -1) {
          left1 = (i, j)
        }
        if (f(i)(j) == '*') {
          right1 = (i, j)
        }
      }
    }
    var left2 = (-1, -1)
    var right2 = (-1, -1)
    for (j <- 0 until m) {
      for (i <- 0 until n) {
        if (f(i)(j) == '*' && left2._1 == -1) {
          left2 = (i, j)
        }
        if (f(i)(j) == '*') {
          right2 = (i, j)
        }
      }
    }
    for (i <- Math.min(left1._1, left2._1) to Math.max(right1._1, right2._1)) {
      for (j <- Math.min(left1._2, left2._2) to Math.max(right1._2, right2._2)) {
        out.print(f(i)(j))
      }
      out.println
    }
  }

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

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val res = (1 to n)
    .map(_ => in.next())
    .dropWhile(!_.contains('*'))
    .reverse
    .dropWhile(!_.contains('*'))
    .reverse
  val (left, right) = res.foldLeft(n - 1, 0) {
    case (acc, line) if !line.contains('*') => acc
    case ((l, r), line) => (Math.min(l, line.indexOf('*')), Math.max(r, line.lastIndexOf('*')))
  }

  println(res.map(_.substring(left, right + 1)).mkString("\n"))
}

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

object ALetter extends App {

  val in = new InputReader(System.in)
  val n = in.nextInt
  val m = in.nextInt
  var arr = Array.ofDim[Char](n, m)
  var min = (Integer.MAX_VALUE, Integer.MAX_VALUE)
  var max = (-1, -1)
  for {
    i <- (0 until n)
    s = in.next
    j <- (0 until m)
  } {
    val cur = s(j)
    arr(i)(j) = cur
    if (cur == '.') {

    } else {
      if (i < min._1 && j < min._2) {
        min = (i, j)
      }
      if (i >= max._1 && j >= max._2) {
        max = (i, j)
      }
    }

  }

  for {
    i <- ((min._1) to (max._1)).iterator.map { x => println(); x }
    j <- (min._2) to (max._2)
  } {
    print(arr(i)(j))
  }

  class InputReader {
    var reader: BufferedReader = null
    var tokenizer: StringTokenizer = null

    def this(stream: InputStream) {
      this()
      reader = new BufferedReader(new InputStreamReader(stream), 32768)
      tokenizer = null
    }

    def next: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens) {
        try {
          tokenizer = new StringTokenizer(reader.readLine)
        }
        catch {
          case e: IOException => {
            throw new RuntimeException(e)
          }
        }
      }
      return tokenizer.nextToken
    }

    def nextInt: Int = {
      return next.toInt
    }
  }

}

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

object ALetter extends App {

  val in = new InputReader(System.in)
  val n = in.nextInt
  val m = in.nextInt
  var arr = Array.ofDim[Char](n, m)
  var min = (Integer.MAX_VALUE, Integer.MAX_VALUE)
  var max = (-1, -1)
  for {
    i <- (0 until n)
    s = in.next
    j <- (0 until m)
  } {
    val cur = s(j)
    arr(i)(j) = cur
    if (cur == '.') {

    } else {
      if (i < min._1 && j < min._2) {
        min = (i, j)
      }
      if (i >= max._1 && j >= max._2) {
        max = (i, j)
      }
    }

  }

  var i = min._1;
  while (i <= max._1) {
    var j = min._2;
    while (j <= max._2) {
      print(arr(i)(j))
      j += 1
    }
    println()
    i += 1
  }

  class InputReader {
    var reader: BufferedReader = null
    var tokenizer: StringTokenizer = null

    def this(stream: InputStream) {
      this()
      reader = new BufferedReader(new InputStreamReader(stream), 32768)
      tokenizer = null
    }

    def next: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens) {
        try {
          tokenizer = new StringTokenizer(reader.readLine)
        }
        catch {
          case e: IOException => {
            throw new RuntimeException(e)
          }
        }
      }
      return tokenizer.nextToken
    }

    def nextInt: Int = {
      return next.toInt
    }
  }

}

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

object A {

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

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

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

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

  def solve = {
    val n = nextInt
    val m = nextInt
    val f = new Array[Array[Char]](n)
    for (i <- 0 until n) {
      f(i) = new Array[Char](m)
      f(i) = next.toCharArray
    }
    var left = (-1, -1)
    var right = (-1, -1)
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (f(i)(j) == '*' && left._1 == -1) {
          left = (i, j)
        }
        if (f(i)(j) == '*') {
          right = (i, j)
        }
      }
    }
    for (i <- left._1 to right._1) {
      for (j <- left._2 to right._2) {
        out.print(f(i)(j))
      }
      out.println
    }
  }

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


You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding.  On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.

NoteIn the first test case, there are the following $$$2$$$ ways to fill the area:  In the second test case, there is a unique way to fill the area:

import scala.io.StdIn.readInt

object Example extends App {
  val t = readInt()

  for (i <- 1 to t) {
    val n = readInt()
    println(n)
  }
}

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

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()

    println(n)
  }
}

import scala.io.StdIn

object Solution {

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 1 to t) {
      val n = StdIn.readLong()
      println(n)
    }
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m = in.nextInt()
      println(m)
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(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(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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

import scala.io.StdIn

object Solution {

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 1 to t) {
      val n = StdIn.readInt()
      val result= math.pow(2, n-1).toLong
      println(s"$result")
      Console.flush()
    }
  }
}

import scala.io.StdIn

object Solution {

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 1 to t) {
      val n = StdIn.readInt()
      val result= math.pow(2, n-1).toLong
      println(s"$result")
    }
  }
}

import scala.io.StdIn

object Solution {

  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 1 to t) {
      val n = StdIn.readInt()
      val result= math.pow(2, n-1)
      println(s"$result")
      Console.flush()
    }
  }
}


You are given an array $$$a$$$ of length $$$n$$$, and an integer $$$x$$$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $$$[3, 6, 9]$$$, in a single operation one can replace the last two elements by their sum, yielding an array $$$[3, 15]$$$, or replace the first two elements to get an array $$$[9, 9]$$$. Note that the size of the array decreases after each operation.The beauty of an array $$$b=[b_1, \ldots, b_k]$$$ is defined as $$$\sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil$$$, which means that we divide each element by $$$x$$$, round it up to the nearest integer, and sum up the resulting values. For example, if $$$x = 3$$$, and the array is $$$[4, 11, 6]$$$, the beauty of the array is equal to $$$\left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8$$$.Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.

The first input line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 1000$$$). The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq x \leq 10^9$$$). The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$), the elements of the array $$$a$$$.  It is guaranteed that the sum of values of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output two integers — the minimal and the maximal possible beauty.

NoteIn the first test case the beauty of the array does not change if we perform any operations.In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements $$$4$$$ and $$$11$$$ with their sum, yielding an array $$$[6, 15]$$$, which has its beauty equal to $$$7$$$.

//package bScalaAdvanced.exercises.codeForces.contest694

import scala.io.StdIn._
import math.ceil

object taskA extends App{

val sets = readInt()
  (1 to sets).foreach(set =>{
    val x = readLine().split(" ")(1).toDouble
    val arr = readLine.split(" ").map(_.toDouble)
    val sumMax:Long  = {
      var subSum:Long = 0
      arr.foreach(n => subSum+= ceil(n / x).toLong)
      subSum
    }

    val sumMin:Long = {
      var subSum:Double = 0
      arr.foreach(n => subSum += n)
      ceil(subSum/x).toLong
    }

    println(sumMin + " " + sumMax)
  })
}

//package bScalaAdvanced.exercises.codeForces.contest694

import scala.io.StdIn._
import math.ceil

object taskA extends App{

val sets = readInt()
  (1 to sets).foreach(set =>{
    val x = readLine().split(" ")(1).toDouble
    val arr = readLine.split(" ").map(_.toDouble)
    val sumMax:Long  = {
      var subSum:Long = 0
      arr.foreach(n => subSum+= ceil(n / x).toInt)
      subSum
    }

    val sumMin:Long = {
      var subSum:Double = 0
      arr.foreach(n => subSum += n)
      ceil(subSum/x).toInt
    }

    println(sumMin + " " + sumMax)
  })
}

//package bScalaAdvanced.exercises.codeForces.contest694

import scala.io.StdIn._
import math.ceil

object taskA extends App{

val sets = readInt()
  (1 to sets).foreach(set =>{
    val x = readLine().split(" ")(1).toDouble
    val arr = readLine.split(" ").map(_.toDouble)
    val sumMax = {
      var subSum = 0
      arr.foreach(n => subSum+= ceil(n / x).toInt)
      subSum
    }

    val sumMin = {
      var subSum:Double = 0
      arr.foreach(n => subSum += n)
      ceil(subSum/x).toInt
    }

    println(sumMin + " " + sumMax)
  })
}


Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction  as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.

The single line contains single integer n (1 ≤ n ≤ 104).

If the answer exists, print 3 distinct numbers x, y and z (1 ≤ x, y, z ≤ 109, x ≠ y, x ≠ z, y ≠ z). Otherwise print -1. If there are multiple answers, print any of them.

import scala.annotation.tailrec

object C extends App {
  def readInts = readLine().split(" ").map(_.toInt)

  val n = readInt()

  if (n == 1) println("-1")
  else println(Seq(n, n+1, n*(n+1)).mkString(" "))
}

object C743 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readLongs(1)
    if(n == 1)
      println("-1")
    else {
      println(s"${n} ${n+1} ${n*(n+1)}")
    }
  }

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

}


Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the second test case:   The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$.  The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$  The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$.  The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$.  The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$.  The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.

import scala.io.Source

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Long]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toLong)
  }

  arrays.map(calc).foreach(println)

  def calc(arr: Array[Long]): Long = {
    val n = arr.length
    val scores = arr.map(x => if (x == 0) 2 else 1)
      .zipWithIndex.map(x => (x._2 + 1, x._1))
      .map(x => x._1 * (n - x._1 + 1) * x._2)

    scores.sum
  }
}

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val a = readInts()
    def findMax(i: Int, j: Int): Long = {
      val currentArray = a.slice(i, j + 1)
      currentArray.length + currentArray.count(_ == 0)
    }

    var answer: Long = 0
    0.until(size).foreach { i =>
      0.until(size).foreach { j =>
        if (i <= j) {
          answer += findMax(i, j)
        }
      }
    }

    println(answer)
  }

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

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


Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times:   take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$.    Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).

The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \leq n, m \leq 500$$$) — the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \leq A_{ij} \leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \leq B_{ij} \leq 10^{9}$$$).

Print "YES" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 8\\ 3 & 6 & 9 \end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & \textbf{5} & \textbf{8}\\ 3 & \textbf{6} & \textbf{9} \end{bmatrix} $$$$$$So matrix becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 6\\ 3 & 8 & 9 \end{bmatrix} $$$$$$and it is $$$B$$$.

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val A = nm(N, M)
    val B = nm(N, M)

    def count(i: Int, mat: Array[Array[Int]]): mutable.Map[Int, Int] = {
      val cnt = mutable.Map[Int, Int]().withDefaultValue(0)
      var n = min(i, N - 1)
      var m = max(0, i - (N - 1))
      debug(s"$n $m")
      while(n >= 0 && m < M) {
        cnt(mat(n)(m)) = cnt(mat(n)(m)) + 1
        n -= 1
        m += 1
      }
      debug(cnt.mkString(" "))
      cnt
    }

    var ok = true
    REP(N + M - 1) { i =>
      ok &&= count(i, A) == count(i, B)
    }

    if (ok) out.println("YES")
    else out.println("NO")
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugNum(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 = 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[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.io.StdIn
import scala.math.min

object Solution {
  def printMatrix(matrix: Array[Array[Int]], n: Int, m: Int, i: Int, j: Int): Unit = {
    (i < n) match {
      case false => Unit
      case true => {
        (j < m) match {
          case false => {
            println("")
            printMatrix(matrix, n, m, (i + 1), 0)
          }
          case true => {
            print(matrix(i)(j) + " ")
            printMatrix(matrix, n, m, i, (j + 1))
          }
        }
      }
    }
  }
  def getDiagList(matrix: Array[Array[Int]], currInds: Tuple2[Int, Int], amount: Int): List[Int] = {
    amount match {
      case 0 => Nil
      case _ => matrix(currInds._1)(currInds._2) :: getDiagList(matrix, (currInds._1 - 1, currInds._2 + 1), amount - 1)
    }
  }
  def compareList(aList: List[Int], bList: List[Int]): Boolean = {
    aList match {
      case a :: aRest => {
        bList match {
          case b :: bRest => (a == b) && compareList(aRest, bRest)
          case Nil => true
        }
      }
      case Nil => true
    }
  }
  def main(args: Array[String]): Unit = {
    val nM = StdIn.readLine().split(" ").map(x => x.toInt)
    val n = nM(0)
    val m = nM(1)

    val aMatrix = Array.range(0, n).map(x => StdIn.readLine().split(" ").map(y => y.toInt))
    val bMatrix = Array.range(0, n).map(x => StdIn.readLine().split(" ").map(y => y.toInt))

    val colStartInds = Array.range(0, n).map(x => (x, 0))
    val rowStartInds = Array.range(1, m).map(x => ((n - 1), x))

    val startInds = colStartInds ++ rowStartInds
    val aDiagLists = startInds.map(x => getDiagList(aMatrix, x, min(x._1 + 1, m - x._2)).sorted)
    val bDiagLists = startInds.map(x => getDiagList(bMatrix, x, min(x._1 + 1, m - x._2)).sorted)

    val res = Array.range(0, startInds.size).toList.foldLeft(true) { (acc, x) => acc && compareList(aDiagLists(x), bDiagLists(x)) }

    res match {
      case true => println("YES")
      case false => println("NO")
    }
  }
}


There is a chess board of size $$$n \times m$$$. The rows are numbered from $$$1$$$ to $$$n$$$, the columns are numbered from $$$1$$$ to $$$m$$$.Let's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular direction:   Find any isolated cell on the board. If there are no such cells, print any cell on the board.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 64$$$) — the number of testcases. The only line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 8$$$) — the number of rows and columns of the board.

For each testcase, print two integers — the row and the column of any isolated cell on the board. If there are no such cells, print any cell on the board.

NoteIn the first testcase, all cells are isolated. A knight can't move from any cell of the board to any other one. Thus, any cell on board is a correct answer.In the second testcase, there are no isolated cells. On a normal chess board, a knight has at least two moves from any cell. Thus, again, any cell is a correct answer.In the third testcase, only the middle cell of the board is isolated. The knight can move freely around the border of the board, but can't escape the middle.

object main {

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

    var t = io.StdIn.readInt()

    def loopts(ts: Int){
        if ( ts < t ){
            def solve() = {
                var Array(n, m) = io.StdIn.readLine().split(" ").map(_.toInt);
                if ( n < 2 || m < 2 )
                    Array(1, 1)
                else
                    if ( n <= 3 && m <= 3 )
                        Array(2, 2)
                    else
                        Array(1, 1)
            }
            var ans = solve()
            println( ans(0)+" "+ans(1) )
            loopts(ts+1)
        }
    }
    loopts(0)
  }

}


You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $$$n$$$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $$$i$$$ ($$$1 \leq i < n$$$) such that $$$h_i \leq h_{i+1}$$$ where $$$h_i$$$ is the height of the $$$i$$$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize $$$|h_1-h_n|$$$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.

The first line will contain a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of mountains. The second line of each test case contains $$$n$$$ integers $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th mountain. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers — the given heights in an order that maximizes the difficulty score among all orders that minimize $$$|h_1-h_n|$$$. If there are multiple orders that satisfy these requirements, you may output any.

NoteIn the first test case:The player begins at height $$$2$$$, next going up to height $$$4$$$ increasing the difficulty by $$$1$$$. After that he will go down to height $$$1$$$ and the difficulty doesn't change because he is going downhill. Finally the player will go up to height $$$2$$$ and the difficulty will increase by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$0$$$ and it's minimal. The difficulty is maximal.In the second test case:The player begins at height $$$1$$$, next going up to height $$$3$$$ increasing the difficulty by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$2$$$ and it's minimal as they are the only heights. The difficulty is maximal.

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

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted

    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index

    val heightsBeforeFirstPoint = heights.slice(0, skipIndex - 1).toList
    val heightsAfterFirstPoint = heights.slice(skipIndex + 1, mountainsNumber).toList

    val answer = heights(skipIndex - 1) +: (heightsAfterFirstPoint ++ heightsBeforeFirstPoint) :+ heights(skipIndex)

    println(answer.mkString(" "))
  }

}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted

    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index

    val heightsBeforeFirstPoint: ListBuffer[Int] = ListBuffer()
    for (i <- 0 until(skipIndex - 1)) {
      heightsBeforeFirstPoint.append(heights(i))
    }
    val heightsAfterFirstPoint: ListBuffer[Int] = ListBuffer()
    for (i <- (skipIndex + 1) until mountainsNumber) {
      heightsAfterFirstPoint.append(heights(i))
    }

    print(s"${heights(skipIndex - 1)} ")
    heightsAfterFirstPoint.foreach(h => print(s"$h "))
    heightsBeforeFirstPoint.foreach(h => print(s"$h "))
    println(s"${heights(skipIndex)} ")
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val hn = readLine().split(" ").map(_.toInt).sorted

    val i = (1 until (n - 1)).foldLeft(0) {
      case (i, j) if math.abs(hn(j) - hn(j + 1)) < math.abs(hn(i) - hn(i + 1)) => j
      case (i, _)                                                              => i
    }

    // h1 h2 h3 ... hi hi+1 ... hn
    //
    // The first variant (incorrect):
    //   hi+1 ... hn h1 h2 h3 ... hi
    //   Example:
    //     -> 1 3
    //     <- 3 1
    //
    // The second variant (correct):
    //  hi hi+2 ... hn h1 h2 ... hi+1
    //  Example
    //    -> 1 3
    //    <- 1 3

    val ans = hn(i) +: (((i + 2) until n).map(hn) ++ (0 until i).map(hn)) :+ hn(i + 1)

    println(ans.mkString(" "))
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted
    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index
    var remainingHeights: ListBuffer[Int] = ListBuffer()
    for (i <- 0 until(mountainsNumber)) {
      if (i != skipIndex - 1 && i != skipIndex) {
        val value = heights(i)
        remainingHeights.append(value)
      }
    }

    if (remainingHeights.size == 2 && (skipIndex == 2)) {
      remainingHeights = remainingHeights.reverse
    }

    print(s"${heights(skipIndex - 1)} ")
    remainingHeights.foreach(h => print(s"$h "))
    println(s"${heights(skipIndex)} ")
  }

}

import scala.collection.mutable
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted
    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index
    print(s"${heights(skipIndex - 1)} ")
    for (i <- 0 until(mountainsNumber)) {
      if (i != skipIndex - 1 && i != skipIndex) print(s"${heights(i)} ")
    }
    println(s"${heights(skipIndex)} ")
  }

}


$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.

NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int, val p: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 998244353L
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[pair](n)
        val a = new Array[Int](n)
        val mx = new Array[Int](n+1)
        val ans = new Array[Boolean](n+1)
        for (i <- 0 until n)
            a(i) = readInt()
        for (i <- 0 until n)
            arr(i) = pair(readInt(), a(i), i+1)
        quickSort(arr)
        for (i <- (0 until n).reverse) {
            mx(i) = max(mx(i+1), arr(i).b)
        }
        var po = 0
        var best = 0
        while (po < n && po <= best) {
            ans(arr(po).p) = true
            best = max(best, bs(po, n, arr(po).b).toInt)
            po += 1
        }
        for (i <- 1 to n) {
            if(ans(i))
                writer.print("1")
            else
                writer.print("0")
        }
        writer.println()
        def check(kk: Long, num: Long): Boolean = {
            if (num < mx(kk.toInt))
                return true
            return false
        }
        def bs(st:Long, en:Long, num:Long): Long = {
            if (en - st <= 1L) {
                if (check(en, num))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2L
            if (check(mid, num))
                return bs(mid, en, num)
            else
                return bs(st, mid, num)
        }
    }
    writer.flush()
}


Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients.

The first line contains two integers n and d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) — the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1 ≤ a ≤ b ≤ 104) — the size of one low quality photo and of one high quality photo, correspondingly.  Next n lines describe the clients. The i-th line contains two integers xi and yi (0 ≤ xi, yi ≤ 105) — the number of low quality photos and high quality photos the i-th client wants, correspondingly.  All numbers on all lines are separated by single spaces.

On the first line print the answer to the problem — the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data.

import scala.io.Source
import scala.math._
import scala.collection.mutable.ListBuffer

object A extends App {
  def go = main(Array())
  val in = Source.stdin.getLines.toList

  val Array(n, d) = in.head.split(" ").map(_.toLong)
  val Array(a, b) = in.tail.head.split(" ").map(_.toLong)

  val req = in.tail.tail.map (s => {
    val Array (low, hi) = s.split(" ").map(_.toLong)

    low * a + hi * b
  }).zipWithIndex.sortBy (_._1)

  def solve: List[Int] = {
    val q = req.foldLeft ((List[Int](), 0l)) { case ((res, sum), (reqs, index)) => if (sum + reqs > d) return res else ((index+1)::res, sum+reqs)}

    q._1
  }

  val solution = solve

  println (solution.size)
  println (solution.mkString(" "))
}

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLineInt
    val prices@Array(a, b) = readLineInt
    val ar = (1L to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)
    val sort = ar.sortBy(_._2)
    val tr = sort.scanLeft((0L, 0L)){ (prev, t) => (t._1, prev._2 + t._2) }
    val taken = tr.takeWhile(_._2 <= d).drop(1)
    println(taken.size)
    println(taken.map(_._1).mkString(" "))
  }

  def readLineInt = readLine().split(" ").map(_.toLong)
}

import scala.io.Source
import scala.math._
import scala.collection.mutable.ListBuffer

object A extends App {
  def go = main(Array())
  val in = Source.stdin.getLines.toList

  val Array(n, d) = in.head.split(" ").map(_.toInt)
  val Array(a, b) = in.tail.head.split(" ").map(_.toInt)

  val req = in.tail.tail.map (s => {
    val Array (low, hi) = s.split(" ").map(_.toInt)

    low * a + hi * b
  }).zipWithIndex.sortBy (_._1)

  def solve: List[Int] = {
    val q = req.foldLeft ((List[Int](), 0)) { case ((res, sum), (reqs, index)) => if (sum + reqs > d) return res else ((index+1)::res, sum+reqs)}

    q._1
  }

  val solution = solve

  println (solution.size)
  println (solution.mkString(" "))
}

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLineInt
    val prices@Array(a, b) = readLineInt
    val ar = (1 to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)
    val sort = ar.sortBy(_._2)
    val tr = sort.scanLeft((0, 0)){ (prev, t) => (t._1, prev._2 + t._2) }
    val taken = tr.takeWhile(_._2 <= d)
    println(taken.size)
    println(taken.map(_._1).drop(1).mkString(" "))
  }

  def readLineInt = readLine().split(" ").map(_.toInt)
}

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLineInt
    val prices@Array(a, b) = readLineInt
    val ar = (1 to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)
    val sort = ar.sortBy(_._2)
    val tr = sort.scanLeft((0, 0)){ (prev, t) => (t._1, prev._2 + t._2) }
    val taken = tr.takeWhile(_._2 <= d).drop(1)
    println(taken.size)
    println(taken.map(_._1).mkString(" "))
  }

  def readLineInt = readLine().split(" ").map(_.toInt)
}