Timur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters.Today he wrote string $$$s$$$ of length $$$n$$$ consisting only of uppercase or lowercase Latin letters. He asks you to check if $$$s$$$ is the correct spelling of his name.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ $$$(1 \leq n \leq 10)$$$ — the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of only uppercase or lowercase Latin characters.

For each test case, output "YES" (without quotes) if $$$s$$$ satisfies the condition, and "NO" (without quotes) otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

10

5

Timur

5

miurT

5

Trumi

5

mriTu

5

timur

4

Timr

6

Timuur

10

codeforces

10

TimurTimur

5

TIMUR

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

  override def solve(io: IO) = {
    val timur = "Timur".sorted

    io.repeat {
      val (_, s) = io.read[(Int, String)]
      val ans = s.sorted == timur
      io.writeLine(ans.toEnglish)
    }
  }

  implicit class BooleanExtensions(x: Boolean) {
    def toEnglish = if (x) "YES" else "NO"
  }
}
/****************************[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 Utils]****************************************/
object Utils {
  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)

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse //e.g. students.sortBy(_.height)(desc)
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)

  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 _1722A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = {
    val timur = "Timur".sorted

    io.repeat {
      val (n, s) = io.read[(Int, String)]
      val ans = s.sorted == timur
      io.writeLine(ans.toEnglish)
    }
  }
}
/****************************[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)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  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 sumWith[B](f: A => B)(implicit n: Numeric[B]): B =
      t.foldLeft(n.zero)({case (c, x) => n.plus(c, f(x))})

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)

  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 _1722A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = {
    val timur = "Timur".sorted

    io.repeat {
      val (n, s) = io.read[(Int, String)]
      val ans = s.sorted == timur
      io.writeLine(ans.toEnglish.toUpperCase)
    }
  }
}
/****************************[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)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  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 sumWith[B](f: A => B)(implicit n: Numeric[B]): B =
      t.foldLeft(n.zero)({case (c, x) => n.plus(c, f(x))})

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)

  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 _1722A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = {
    val timur = "Timur".sorted

    io.repeat {
      val (n, s) = io.read[(Int, String)]
      val ans = n == timur.length && s.sorted == timur
      io.writeLine(ans.toEnglish.toUpperCase)
    }
  }
}
/****************************[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)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  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 sumWith[B](f: A => B)(implicit n: Numeric[B]): B =
      t.foldLeft(n.zero)({case (c, x) => n.plus(c, f(x))})

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int])(f)

  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 _1722A extends CodeForcesApp {
   import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

   override def solve(io: IO) = {
      val timur = "Timur".sorted

      io.repeat {
         val (n, s) = io.read[(Int, String)]
         val ans = n == timur.length && s.sorted == timur
         io.write(ans.toEnglish.toUpperCase)
      }
   }
}
/****************************[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)

   val charToInt: Char => Int = Character.getNumericValue
   val intToChar: Int => Char = Character.forDigit(_, 10)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.

The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices. The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).

Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .

NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.

object B 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) = readInts(1)
  val xs, ys = Array.ofDim[Double](n)

  for (i <- 0 until n) {
    val Array(a, b) = readLongs(2)
    xs(i) = a.toDouble
    ys(i) = b.toDouble
  }

  def sqr(x: Double) = x * x

  def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {
    Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /
      Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))
  }

  def dist(x1: Double, y1: Double, x2: Double, y2: Double) = {
    Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))
  }

  def pDistance(x: Double, y: Double, x1: Double, y1: Double, x2: Double, y2: Double) = {

    var A = x - x1;
    var B = y - y1;
    var C = x2 - x1;
    var D = y2 - y1;

    var dot = A * C + B * D;
    var len_sq = C * C + D * D;
    var param = -1d;
    if (len_sq != 0) //in case of 0 length line
      param = dot / len_sq;

    var xx, yy = 0d;

    if (param < 0) {
      xx = x1;
      yy = y1;
    }
    else if (param > 1) {
      xx = x2;
      yy = y2;
    }
    else {
      xx = x1 + param * C;
      yy = y1 + param * D;
    }

    var dx = x - xx;
    var dy = y - yy;
    Math.sqrt(dx * dx + dy * dy);
  }

  var min = Double.MaxValue

  for (i <- 0 until n) {
    val d = pDistance(
      xs((i + 1) % n), ys((i + 1) % n),
      xs(i), ys(i),
      xs((i + 2) % n), ys((i + 2) % n))
    //val d2 = dist(xs(i), ys(i), xs((i + 1) % n), ys((i + 1) % n))
    //val d3 = dist(xs((i + 2) % n), ys((i + 2) % n), xs((i + 1) % n), ys((i + 1) % n))
    //val d = d1 min d2 min d3
    if (d < min) min = d
  }

  println(min / 2)
}

object B extends App {

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

  val Array(n) = readInts(1)
  val xs, ys = Array.ofDim[Double](n)

  for (i <- 0 until n) {
    val Array(a, b) = readLongs(2)
    xs(i) = a.toDouble
    ys(i) = b.toDouble
  }

  def sqr(x: Double) = x * x

  def distance(x1: Double, y1: Double, x2: Double, y2: Double): Double =
    Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))

  def distPointToLineSegment(x: Double, y: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {

    val a = x - x1
    val b = y - y1
    val c = x2 - x1
    val d = y2 - y1

    val dot = a * c + b * d
    val lengthSquared = c * c + d * d
    val param = if (lengthSquared == 0) -1 else dot / lengthSquared

    if (param < 0) distance(x, y, x1, y1)
    else if (param > 1) distance(x, y, x2, y2)
    else distance(x, y, x1 + param * c, y1 + param * d)
  }

  var min = Double.MaxValue

  for (i <- 0 until n) {
    val d = distPointToLineSegment(
      xs((i + 1) % n), ys((i + 1) % n),
      xs(i), ys(i),
      xs((i + 2) % n), ys((i + 2) % n))
    if (d < min) min = d
  }

  println(min / 2)
}

object B 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) = readInts(1)
  val xs, ys = Array.ofDim[Double](n)

  for (i <- 0 until n) {
    val Array(a, b) = readLongs(2)
    xs(i) = a.toDouble
    ys(i) = b.toDouble
  }

  def sqr(x: Double) = x * x

  def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {
    Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /
      Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))
  }

  def dist(x1: Double, y1: Double, x2: Double, y2: Double) = {
    Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))
  }

  var min = Double.MaxValue

  for (i <- 0 until n) {
    val d1 = dist(
      xs((i + 1) % n), ys((i + 1) % n),
      xs(i), ys(i),
      xs((i + 2) % n), ys((i + 2) % n))
    val d2 = dist(xs(i), ys(i), xs((i + 1) % n), ys((i + 1) % n))
    val d3 = dist(xs((i + 2) % n), ys((i + 2) % n), xs((i + 1) % n), ys((i + 1) % n))
    val d = d1 min d2 min d3
    if (d < min) min = d
  }

  println(min / 2)
}

object B 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) = readInts(1)
  val xs, ys = Array.ofDim[Double](n)

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

  def sqr(x: Double) = x * x

  def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {
    Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /
      Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))
  }

  var min = Double.MaxValue

  for (i <- 0 until n) {
    val d = dist(
      xs((i + 1) % n), ys((i + 1) % n),
      xs(i), ys(i),
      xs((i + 2) % n), ys((i + 2) % n))
    if (d < min) min = d
  }

  println(min / 2)
}

object B 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) = readInts(1)
  val xs, ys = Array.ofDim[Double](n)

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

  def sqr(x: Double) = x * x

  def dist(x0: Double, y0: Double, x1: Double, y1: Double, x2: Double, y2: Double): Double = {
    Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) /
      Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))
  }

  def dist(x1: Double, y1: Double, x2: Double, y2: Double) = {
    Math.sqrt(sqr(y2 - y1) + sqr(x2 - x1))
  }

  var min = Double.MaxValue

  for (i <- 0 to n) {
    val d1 = dist(
      xs((i + 1) % n), ys((i + 1) % n),
      xs(i % n), ys(i % n),
      xs((i + 2) % n), ys((i + 2) % n))
    val d2 = dist(xs(i % n), ys(i % n), xs((i + 1) % n), ys((i + 1) % n))
    val d3 = dist(xs((i + 2) % n), ys((i + 2) % n), xs((i + 1) % n), ys((i + 1) % n))
    val d = d1 min d2 min d3
    if (d < min) min = d
  }

  println(min / 2)
}


A championship is held in Berland, in which $$$n$$$ players participate. The player with the number $$$i$$$ has $$$a_i$$$ ($$$a_i \ge 1$$$) tokens.The championship consists of $$$n-1$$$ games, which are played according to the following rules:  in each game, two random players with non-zero tokens are selected;  the player with more tokens is considered the winner of the game (in case of a tie, the winner is chosen randomly);  the winning player takes all of the loser's tokens; The last player with non-zero tokens is the winner of the championship.All random decisions that are made during the championship are made equally probable and independently.For example, if $$$n=4$$$, $$$a = [1, 2, 4, 3]$$$, then one of the options for the game (there could be other options) is:   during the first game, the first and fourth players were selected. The fourth player has more tokens, so he takes the first player's tokens. Now $$$a = [0, 2, 4, 4]$$$;  during the second game, the fourth and third players were selected. They have the same number of tokens, but in a random way, the third player is the winner. Now $$$a = [0, 2, 8, 0]$$$;  during the third game, the second and third players were selected. The third player has more tokens, so he takes the second player's tokens. Now $$$a = [0, 0, 10, 0]$$$;  the third player is declared the winner of the championship. Championship winners will receive personalized prizes. Therefore, the judges want to know in advance which players have a chance of winning, i.e have a non-zero probability of winning the championship. You have been asked to find all such players.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case consists of one positive integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of players in the championship. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the number of tokens the players have. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the number of players who have a nonzero probability of winning the championship. On the next line print the numbers of these players in increasing order. Players are numbered starting from one in the order in which they appear in the input.

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object AccidentalVictory extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val tokens = readLine.split(' ').toList.map(x => BigInt(x))
    val as = tokens.zip((1 to tokens.length).toList).sortBy(x => x._1)
    lazy val index = recursion(as, 0, 0, -1)
    lazy val non_zero_players = as.slice(Math.max(0, index), as.length).sortBy(x => x._2)
    println(non_zero_players.length)
    println(non_zero_players.map(x => x._2.toString()).mkString(" "))

    @tailrec
    def recursion(tokens: List[(BigInt, Int)], sum : BigInt, current_index : Int, last_zero_index : Int): Int = tokens match {
      case x :: xs =>
        if(x._1 > sum) {
          recursion(xs, sum + x._1, current_index + 1, current_index)
        } else {
          recursion(xs, sum + x._1, current_index + 1, last_zero_index)
        }
      case _ => last_zero_index
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object AccidentalVictory extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val tokens = readLine.split(' ').toList.map(x => x.toInt)
    val as = tokens.zip((1 to tokens.length).toList).sortBy(x => x._1)
    lazy val index = recursion(as, 0, 0, -1)
    lazy val non_zero_players = as.slice(Math.max(0, index), as.length).sortBy(x => x._2)
    println(non_zero_players.length)
    println(non_zero_players.map(x => x._2.toString()).mkString(" "))

    @tailrec
    def recursion(tokens: List[(Int, Int)], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {
      case x :: xs =>
        if(x._1 > sum) {
          recursion(xs, sum + x._1, current_index + 1, current_index)
        } else {
          recursion(xs, sum + x._1, current_index + 1, last_zero_index)
        }
      case _ => last_zero_index
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object AccidentalVictory extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toList.map(x => x.toInt).sorted
    lazy val index = recursion(as, 0, 0, -1)
    println(as.length - Math.max(index, 0))
    println((Math.max(index, 0) + 1 to as.length).toList.map(x => x.toString).mkString(" "))

    @tailrec
    def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {
      case x :: xs =>
        if(x > sum) {
          recursion(xs, sum + x, current_index + 1, current_index)
        } else {
          recursion(xs, sum + x, current_index + 1, last_zero_index)
        }
      case _ => last_zero_index
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object AccidentalVictory extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toList.map(x => x.toInt).sorted
    lazy val index = recursion(as, 0, 0, -1)
    println(as.length - index)
    println((Math.max(index, 0) + 1 to as.length).toList.map(x => x.toString).mkString(" "))

    @tailrec
    def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {
      case x :: xs =>
        if(x > sum) {
          recursion(xs, sum + x, current_index + 1, current_index)
        } else {
          recursion(xs, sum + x, current_index + 1, last_zero_index)
        }
      case _ => last_zero_index
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object AccidentalVictory extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toList.map(x => x.toInt).sorted
    lazy val index = recursion(as, 0, 0, -1)
    println(as.length - index)
    println(as.slice(index, as.length).map(x => x.toString).mkString(" "))

    @tailrec
    def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {
      case x :: xs =>
        if(x > sum) {
          recursion(xs, sum + x, current_index + 1, current_index)
        } else {
          recursion(xs, sum + x, current_index + 1, last_zero_index)
        }
      case _ => last_zero_index
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object AccidentalVictory extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toList.map(x => x.toInt).sorted
    lazy val index = recursion(as, 0, 0, -1)
    println(as.slice(index, as.length).map(x => x.toString).mkString(" "))

    @tailrec
    def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {
      case x :: xs =>
        if(x > sum) {
          recursion(xs, sum + x, current_index + 1, current_index)
        } else {
          recursion(xs, sum + x, current_index + 1, last_zero_index)
        }
      case _ => last_zero_index
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object AccidentalVictory extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val n = readLine.toInt
    val as = readLine.split(' ').toList.map(x => x.toInt)
    lazy val index = recursion(as, 0, 0, -1)
    println(as.slice(index, as.length).map(x => x.toString).mkString(" "))

    @tailrec
    def recursion(tokens: List[Int], sum : Int, current_index : Int, last_zero_index : Int): Int = tokens match {
      case x :: xs =>
        if(x > sum) {
          recursion(xs, sum + x, current_index + 1, current_index)
        } else {
          recursion(xs, sum + x, current_index + 1, last_zero_index)
        }
      case _ => last_zero_index
    }
  }
}


Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to $$$1$$$ meter movement in the south, north, west or east direction respectively).It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visited the first time), then the time of such movement is $$$5$$$ seconds. If he rolls along previously visited segment of a path (i.e., this segment of the path has been covered by his path before), then it takes $$$1$$$ second.Find the skier's time to roll all the path.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each set is given by one nonempty string of the characters 'S', 'N', 'W', 'E'. The length of the string does not exceed $$$10^5$$$ characters. The sum of the lengths of $$$t$$$ given lines over all test cases in the input does not exceed $$$10^5$$$.

For each test case, print the desired path time in seconds.

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

object C {

  def solution(moves: String): Int = {
    val isRightTaken = mutable.Set.empty[(Int, Int)]
    val isTopTaken = mutable.Set.empty[(Int, Int)]
    def add[T](set: mutable.Set[T], value: T) = if (set.add(value)) 5 else 1

    var (time, i, j) = (0, 0, 0)
    for (dir <- moves) {
      dir match {
        case 'E' => // Right
          time += add(isRightTaken, (i, j))
          i += 1
        case 'W' => // Left
          time += add(isRightTaken, (i - 1, j))
          i -= 1
        case 'N' => // Top
          time += add(isTopTaken, (i, j))
          j += 1
        case 'S' => // Bottom
          time += add(isTopTaken, (i, j - 1))
          j -= 1
      }
    }
    time
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val moves = readLine
      println(solution(moves))
    }
  }
}

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

object C {

  def solution(moves: String): Int = {
    val isRightTaken = mutable.Set.empty[(Int, Int)]
    val isTopTaken = mutable.Set.empty[(Int, Int)]
    def add[T](set: mutable.Set[T], value: T) = if (set.add(value)) 5 else 1

    var (time, i, j) = (0, 0, 0)
    for (dir <- moves) {
      dir match {
        case 'E' => // Right
          time += add(isRightTaken, (i, j))
          i += 1
        case 'W' => // Left
          time += add(isRightTaken, (i - 1, j))
          i -= 1
        case 'N' => // Top
          time += add(isTopTaken, (i, j))
          j += 1
        case 'S' => // Bottom
          time += add(isTopTaken, (i, j - 1))
          i -= 1
      }
    }
    time
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val moves = readLine
      println(solution(moves))
    }
  }
}


As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:A swap operation is the following sequence of actions:  choose two indexes i, j (i ≠ j);  perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp. What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?

The first line contains two integers n and k (1 ≤ n ≤ 200; 1 ≤ k ≤ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 ≤ a[i] ≤ 1000).

In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Int = {
    val N, K = sc.nextInt
    val A = Array.fill(N)(sc.nextInt)

    @tailrec
    def loop(acc: Int, i: Int, j: Int): Int = {
      if (i == N) acc
      else if (j == N + 1) loop(acc, i + 1, i + 2)
      else {
        val lr = A.slice(i, j)
        val kmax = (A.slice(0, i) ++ A.slice(j, N)).sorted(Ordering.Int.reverse).take(K)
        val sum = (lr ++ kmax).sorted(Ordering.Int.reverse).take(j - i).sum
        loop(acc max sum, i, j + 1)
      }
    }

    loop(Int.MinValue, 0, 1)
  }

  out.println(solve)
  out.close
}


You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:   Operation AND ('&', ASCII code 38)  Operation OR ('|', ASCII code 124)  Operation NOT ('!', ASCII code 33)  Variables x, y and z (ASCII codes 120-122)  Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one.Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:E ::= E '|' T | TT ::= T '&' F | FF ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'

The first line contains one integer n — the number of functions in the input (1 ≤ n ≤ 10 000). The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1 — the truth table of the i-th function. The digit on position j (0 ≤ j < 8) equals to the value of the function in case of ,  and .

You should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.

NoteThe truth table for the second function:

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

import scala.annotation.tailrec

object E {
  def fromBinary(s: String): Int = s.zipWithIndex.map(p => if (p._1 == '1') 1 << p._2 else 0).sum

  def compare(l: String, r: String): Int = {
    if (l == r) 0 else if (l == null) 1 else if (r == null) -1 else if (l.length != r.length) {
      l.length - r.length
    } else l.compareTo(r)
  }

  def generate(): Array[String] = {
    val shortestE, shortestF, shortestT = Array.ofDim[String](256)
    shortestF(fromBinary("00001111")) = "x"
    shortestF(fromBinary("00110011")) = "y"
    shortestF(fromBinary("01010101")) = "z"
    var changed = false
    do {
      changed = false
      for (i <- 0 until 256) {
        if (shortestE(i) != null) {
          val br = "(" + shortestE(i) + ")"
          if (compare(shortestF(i), br) > 0) {
            shortestF(i) = br
            changed = true
          }
        }
        if (compare(shortestT(i), shortestF(i)) > 0) {
          shortestT(i) = shortestF(i)
          changed = true
        }
        if (compare(shortestE(i), shortestT(i)) > 0) {
          shortestE(i) = shortestT(i)
          changed = true
        }
        if (shortestF(i) != null) {
          val neg = "!" + shortestF(i)
          if (compare(shortestF(~i & 255), neg) > 0) {
            shortestF(~i & 255) = neg
            changed = true
          }
        }
        for (j <- 0 until 256) {
          if (shortestE(i) != null && shortestT(j) != null) {
            val or = shortestE(i) + "|" + shortestT(j)
            if (compare(shortestE(i | j), or) > 0) {
              shortestE(i | j) = or
              changed = true
            }
          }
          if (shortestT(i) != null && shortestF(j) != null) {
            val and = shortestT(i) + "&" + shortestF(j)
            if (compare(shortestT(i & j), and) > 0) {
              shortestT(i & j) = and
              changed = true
            }
          }
        }
      }
    } while (changed)
    shortestE
  }

  def solve(in: Input, out: Output): Unit = {
    val answers = generate()
    val n = in.nextInt()
    for (_ <- 0 until n) {
      val line = in.next()
      val tableKey = (0 until 8).map(i => if (line(i) == '1') 1 << i else 0).sum
      out.println(answers(tableKey))
    }
  }

  class Input(in: InputStream) extends Closeable {
    private[this] val br = new BufferedReader(new InputStreamReader(in))
    private[this] var st = new StringTokenizer(br.readLine())

    override def close(): Unit = br.close()

    @tailrec
    final def next(): String = if (st.hasMoreTokens) st.nextToken() else {
      st = new StringTokenizer(br.readLine())
      next()
    }

    final def nextInt(): Int = next().toInt
    final def nextLong(): Long = next().toLong
    final def nextDouble(): Double = next().toDouble
  }

  final type Output = PrintWriter

  def main(args: Array[String]): Unit = {
    val in = new Input(System.in)
    val out = new Output(System.out)
    solve(in, out)
    out.close()
    in.close()
  }
}


Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.

The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.

NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.

import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 6..
  */
object BSolution extends App {
  val numOfJar = StdIn.readLine().toInt
  val listOfJar = StdIn.readLine().split(' ').map(_.toInt)

  val minLiter = listOfJar.min.toLong
  val indexOfEmpty = for {
    i <- 0 until numOfJar
    if listOfJar(i) == minLiter
  } yield i

  val maxDistance = indexOfEmpty.length match {
    case 1 =>
      numOfJar - 1
    case n =>
      val indexOfEmpty2 = indexOfEmpty.tail ++ Seq(numOfJar + indexOfEmpty.head)

      indexOfEmpty2.zip(indexOfEmpty).map { case (end, start) =>
        end - start - 1
      }.max
  }

  val output = minLiter * numOfJar + maxDistance
  println(output)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val min = data.min
  val max = data.foldLeft((0l, 0l, 0l, -1)) {
    case ((m, soFar, first, -1), el) if el == min => (0, 0, first, 0)
    case ((m, soFar, first, -1), el) => (0, 0, first + 1, -1)
    case ((m, soFar, first, _), el) if el == min => (Math.max(m, soFar), 0, first, 0)
    case ((m, soFar, first, _), el) => (Math.max(m, soFar + 1), soFar + 1, first, 0)
  }
  val maxValue = Math.max(max._1, max._3 + max._2)
  println(min.toLong * data.length + maxValue)
}

//package c610

/**
  * Created by user on 04.01.16.
  */
object B {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val colors = io.StdIn.readLine().split(" ").map(BigInt(_))

    val min = colors.min

    println(MaxLenght(n, colors))
  }

  def MaxLenght(n: Int, colors: Array[BigInt]): BigInt = {
    val minColor = colors.min

    var leftIndex = colors.lastIndexOf(minColor)
    val result = colors.zipWithIndex.filter {
      case (color, index) =>
        color == minColor
    } map {
      case (color, currentIndex) =>
        var diff = 0
        if (leftIndex > currentIndex) {
          diff = n + currentIndex - leftIndex - 1
        } else {
          if (currentIndex == leftIndex) {
            diff = n - 1
          } else {
            diff = currentIndex - leftIndex - 1
          }
        }
//        println(currentIndex + " " + color + " " + " " + diff + " " + leftIndex)
        leftIndex = currentIndex
        minColor * n + diff
    } max

    return result

//    val maxLength = colors.zipWithIndex.map {
//      case (currentColor, currentIndex) =>
//        val nextMinColorIndex = upperBound(currentIndex, minColorsIndex)
//        var diff = 0
//        if (nextMinColorIndex < currentIndex) {
//          diff = n - currentIndex + nextMinColorIndex
//        } else {
//          diff = nextMinColorIndex - currentIndex
//        }
//        val res = colors(nextMinColorIndex) * n + diff
//        res
//    }.max
//
//    maxLength
  }

  def upperBound(key: Int, xs: Array[Int]): Int = {
    val isHere = xs.find(_==key)
    if (isHere.isDefined) return key

    var len = xs.length
    var first = 0
    while (len > 0) {
      val half = len >>> 1
      val middle = first + half
      if (key < xs(middle)) {
        len = half
      } else {
        first = middle + 1
        len = len - half - 1
      }
    }
    if (first < xs.length)
      xs(first)
    else
      xs(0)
  }

}

import java.util.Scanner
import scala.math._

object Main {
  def main(args: Array[String]) {
    val scanner = new Scanner(System.in)
    def next = scanner.next.toInt

    println(compute(0.until(next).map(_ => next)))
  }

  // r: a==[], many mins
  def compute(as: IndexedSeq[Int]) = {
    assert(as.size > 0)

    val minIndex = findMin(as)
    val maxBefore = countConsequentGreater(as, minIndex)
    maxBefore + as(minIndex).toLong * as.size
  }

  def findMin(as: IndexedSeq[Int]): Int = {
    var result = 0
    for (i <- 1 until as.size) {
      if (as(i) < as(result))
        result = i
    }
    result
  }

  def countConsequentGreater(as: IndexedSeq[Int], minIndex: Int) = {
    val n = as.size
    var maxBefore = 0
    var curBefore = 0

    for (i <- 0 until n) {
      val j = (minIndex - i + n) % n
      if (as(j) > as(minIndex))
        curBefore += 1
      else
        curBefore = 0
      maxBefore = max(maxBefore, curBefore)
    }

    maxBefore
  }
}

import scala.collection._

object B 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) = readInts(1)
  val as = readInts(n)
  val min = as.min.toLong

  var start = -1
  var end = -1
  var maxLen = 0
  for (i <- as.indices) {
    if (as(i) > min) {
     if (start == -1) start = i
     if (i - start + 1 > maxLen) maxLen = i - start + 1
    } else {
      start = -1
    }
  }

  var i = 0
  while (i < n && as(i) > min) i += 1
  var j = 0
  while (j < n && as(n - j - 1) > min) j += 1
  if (i + j > maxLen) maxLen = i + j

  println(min * n + maxLen)
}

import java.util.Scanner

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

    var jar = new Array[Int](n+1)
    for(i <- 1 to n)
      jar(i) = sc.nextInt()

    // statement
    var ans = 0L

    val max = jar.max
    jar(0) = Int.MaxValue
    val min = jar.min

    // func
    def checkMinPoint(cnt: Int): List[Int] = {
      cnt > n match{
        case true  => Nil
        case false =>
          if(jar(cnt) == min)
            cnt :: checkMinPoint(cnt+1)
          else
            checkMinPoint(cnt+1)
      }
    }

    val minlist = checkMinPoint(1)

    // func
    def maxDif(list: List[Int]): Int = {
      list match{
        case _ :: Nil | Nil => 0
        case x :: y :: l2 => Math.max(y-x, maxDif(y :: l2))
      }
    }

    val tmpmax = maxDif(minlist) - 1
    val side = (n - minlist.last) + minlist(0) - 1
    val bonus = Math.max(side, tmpmax)

    if(min == max)
      println((n.toLong * jar(1)))
    else{
      println(min * n.toLong + bonus)
    }
  }

}

import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 6..
  */
object BSolution extends App {
  val numOfJar = StdIn.readLine().toInt
  val listOfJar = StdIn.readLine().split(' ').map(_.toInt)

  val minLiter = listOfJar.min
  val indexOfEmpty = for {
    i <- 0 until numOfJar
    if listOfJar(i) == minLiter
  } yield i

  val maxDistance = indexOfEmpty.length match {
    case 1 =>
      numOfJar - 1
    case n =>
      val indexOfEmpty2 = indexOfEmpty.tail ++ Seq(numOfJar - indexOfEmpty.head)

      indexOfEmpty2.zip(indexOfEmpty).map { case (start, end) =>
        start - end - 1
      }.max
  }

  val output = minLiter * numOfJar + maxDistance
  println(output)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val min = data.min
  val max = data.foldLeft((0, 0, 0, -1)) {
    case ((m, soFar, first, -1), el) if el == min => (0, 0, first, 0)
    case ((m, soFar, first, -1), el) => (0, 0, first + 1, -1)
    case ((m, soFar, first, _), el) if el == min => (Math.max(m, soFar), 0, first, 0)
    case ((m, soFar, first, _), el) => (Math.max(m, soFar + 1), soFar + 1, first, 0)
  }
  val maxValue = Math.max(max._1, max._3 + max._2)
  println(min * data.length + maxValue)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val min = data.min
  val max = data.foldLeft((0l, 0l, 0l, -1)) {
    case ((m, soFar, first, -1), el) if el == min => (0, 0, first, 0)
    case ((m, soFar, first, -1), el) => (0, 0, first + 1, -1)
    case ((m, soFar, first, _), el) if el == min => (Math.max(m, soFar), 0, first, 0)
    case ((m, soFar, first, _), el) => (Math.max(m, soFar + 1), soFar + 1, first, 0)
  }
  val maxValue = Math.max(max._1, max._3 + max._2)
  println(min * data.length + maxValue)
}

//package c610

/**
  * Created by user on 04.01.16.
  */
object B {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val colors = io.StdIn.readLine().split(" ").map(BigInt(_))

    val min = colors.min

    println(MaxLenght(n, colors))
  }

  def MaxLenght(n: Int, colors: Array[BigInt]): BigInt = {
    val minColor = colors.min

    var leftIndex = colors.lastIndexOf(minColor)
    val result = colors.zipWithIndex.filter {
      case (color, index) =>
        color == minColor
    } map {
      case (color, currentIndex) =>
        var diff = 0
        if (leftIndex > currentIndex) {
          diff = n + currentIndex - leftIndex - 1
        } else {
          diff = currentIndex - leftIndex - 1
        }
//        println(currentIndex + " " + color + " " + " " + diff + " " + leftIndex)
        leftIndex = currentIndex
        minColor * n + diff
    } max

    return result

//    val maxLength = colors.zipWithIndex.map {
//      case (currentColor, currentIndex) =>
//        val nextMinColorIndex = upperBound(currentIndex, minColorsIndex)
//        var diff = 0
//        if (nextMinColorIndex < currentIndex) {
//          diff = n - currentIndex + nextMinColorIndex
//        } else {
//          diff = nextMinColorIndex - currentIndex
//        }
//        val res = colors(nextMinColorIndex) * n + diff
//        res
//    }.max
//
//    maxLength
  }

  def upperBound(key: Int, xs: Array[Int]): Int = {
    val isHere = xs.find(_==key)
    if (isHere.isDefined) return key

    var len = xs.length
    var first = 0
    while (len > 0) {
      val half = len >>> 1
      val middle = first + half
      if (key < xs(middle)) {
        len = half
      } else {
        first = middle + 1
        len = len - half - 1
      }
    }
    if (first < xs.length)
      xs(first)
    else
      xs(0)
  }

}

import java.util.Scanner
import scala.math._

object Main {
  def main(args: Array[String]) {
    val scanner = new Scanner(System.in)
    def next = scanner.next.toInt

    println(compute(0.until(next).map(_ => next)))
  }

  // r: a==[], many mins
  def compute(as: IndexedSeq[Int]) = {
    assert(as.size > 0)

    val minIndex = findMin(as)
    val maxBefore = countConsequentGreater(as, minIndex)
    maxBefore + as(minIndex) * as.size
  }

  def findMin(as: IndexedSeq[Int]): Int = {
    var result = 0
    for (i <- 1 until as.size) {
      if (as(i) < as(result))
        result = i
    }
    result
  }

  def countConsequentGreater(as: IndexedSeq[Int], minIndex: Int) = {
    val n = as.size
    var maxBefore = 0
    var curBefore = 0

    for (i <- 0 until n) {
      val j = (minIndex - i + n) % n
      if (as(j) > as(minIndex))
        curBefore += 1
      else
        curBefore = 0
      maxBefore = max(maxBefore, curBefore)
    }

    maxBefore
  }
}


Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?

The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.

Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.

NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.

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 S = ns().map(a => (a - '0') % 3)
    val s = Array.ofDim[Boolean](3)
    var ans = 0
    import java.util

    def found(): Unit = {
      ans += 1
      util.Arrays.fill(s, false)
    }

    REP(S.length) { i =>
      S(i) match {
        case 0 => found()

        case 1 =>
          if (s(2)) {
            found()
          } else {
            s(2) = s(1)
            s(1) = true
          }

        case 2 =>
          if (s(1)) {
            found()
          } else {
            s(1) = s(2)
            s(2) = true
          }
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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

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 A = ns().toCharArray.map(a => (a - '0') % 3)
    val N = A.length

    val last = Array.fill[Int](2, 3)(-1)
    val dp = Array.ofDim[Int](N + 1)

    REP(N) { i =>
      val x = i % 2
//      debug(s"$i ${dp.mkString}, ${last(x).mkString(",")}")

      val m = A(i)

      // まえの状態から遷移
      REP(3) { j =>
        last(x^1)((j + m) % 3) = last(x)(j)
      }
      // mの状態の最短を更新
      last(x^1)(m) = i  // 参照するのは１歩手前のDPの状態

      if (m == 0) {
        dp(i + 1) = dp(i) + 1
      } else {
        // 3をつくらない場合の個数
        dp(i + 1) = dp(i)

        if (last(x)(3 - m) != -1) {
          dp(i + 1) = max(dp(i + 1), dp(last(x)(3 - m)) + 1)
        }
      }

//      debug(s"$i ${dp.mkString}, ${last(x^1).mkString(",")}")
    }

    out.println(dp(N))
  }

  def debug(msg: String): Unit = {
    System.err.println(msg)
  }

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

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

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

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

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

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

object Codeforces1005D {

  def getMaximumDivisibleBy3Numbers(digits: Seq[Int]): Int = {
    var previousNumbers = new ArrayBuffer[Int]
    var totalNumber = 0
    for (digit <- digits) {
      var currentReminder = digit % 3

      var index = previousNumbers.length - 1
      var found = false
      if (currentReminder == 0) {
        found = true
      }
      while (!found && index >= 0) {
        currentReminder = (currentReminder + previousNumbers(index)) % 3
        if (currentReminder == 0) found = true
        index -= 1
      }
      if (found) {
        totalNumber += 1
        previousNumbers = new ArrayBuffer[Int]
      } else {
        previousNumbers.append(digit)
      }
    }
    totalNumber
  }

  def main(args: Array[String]): Unit = {
    val digits = StdIn.readLine().map(_.toInt)
    val maximumDivisibleBy3Numbers = getMaximumDivisibleBy3Numbers(digits)
    println(maximumDivisibleBy3Numbers)
  }
}


You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$n$$$ is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are greater than or equal to $$$0$$$.  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are less than or equal to $$$0$$$. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 500$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n \le 99$$$, $$$n$$$ is odd)  — the number of integers given to you. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)  — the numbers themselves. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10000$$$.

For each test case, print $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$, corresponding to the integers after flipping signs. $$$b_i$$$ has to be equal to either $$$a_i$$$ or $$$-a_i$$$, and of the adjacent differences $$$b_{i + 1} - b_i$$$ for $$$i = 1, \dots, n - 1$$$, at least $$$\frac{n - 1}{2}$$$ should be non-negative and at least $$$\frac{n - 1}{2}$$$ should be non-positive. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.

NoteIn the first test case, the difference $$$(-4) - (-2) = -2$$$ is non-positive, while the difference $$$3 - (-4) = 7$$$ is non-negative.In the second test case, we don't have to flip any signs. All $$$4$$$ differences are equal to $$$0$$$, which is both non-positive and non-negative.In the third test case, $$$7 - (-4)$$$ and $$$4 - (-6)$$$ are non-negative, while $$$(-4) - (-2)$$$ and $$$(-6) - 7$$$ are non-positive.

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

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

      for (i <- as.indices) {
        val s = if (i % 2 == 1) 1 else -1
        as(i) = math.abs(as(i)) * s
      }

      out.println(as.mkString(" "))
    }

    out.flush()
  }

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

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

  val t = readInt()

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

    val bn = an.zipWithIndex.map { case (a, i) => if (i % 2 == 0) a.abs else -a.abs }

    println(bn.mkString(" "))
  }
}

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

  val t = readInt()

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

    val bn = an.zipWithIndex.map { case (a, i) => if (i % 2 == 0) a else -a }

    println(bn.mkString(" "))
  }
}


Monocarp wrote down two numbers on a whiteboard. Both numbers follow a specific format: a positive integer $$$x$$$ with $$$p$$$ zeros appended to its end.Now Monocarp asks you to compare these two numbers. Can you help him?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$x_1$$$ and $$$p_1$$$ ($$$1 \le x_1 \le 10^6; 0 \le p_1 \le 10^6$$$) — the description of the first number. The second line of each testcase contains two integers $$$x_2$$$ and $$$p_2$$$ ($$$1 \le x_2 \le 10^6; 0 \le p_2 \le 10^6$$$) — the description of the second number.

For each testcase print the result of the comparison of the given two numbers. If the first number is smaller than the second one, print '<'. If the first number is greater than the second one, print '>'. If they are equal, print '='.

import scala.io.StdIn

object ProblemA extends App {

  type Input = List[((String, Int, Long), (String, Int, Long))]
  def start() = {
    val input = parseInput()
    val result = input.map(solve(_))
    println(result.mkString("\n"))
  }

  def parseInput(): Input = {
    val ntc = StdIn.readLine().stripLineEnd.trim.toInt
    var result: Input = List()
    for (_ <- 0.until(ntc)) {
      val a = StdIn.readLine().stripLineEnd.trim.split(" ").map( a => (a, a.length-1))
      val b = StdIn.readLine().stripLineEnd.trim.split(" ").map( a => (a, a.length-1))
      result = ((a(0)._1, a(0)._2, a(1)._1.toLong), (b(0)._1, b(0)._2, b(1)._1.toLong) ) :: result
    }
    result.reverse
  }

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

    if (a._2 < b._2) solve(( (a._1 + "0", a._2+1, a._3-1), b))
    else if (a._2 > b._2) solve(( a, (b._1 + "0", b._2+1, b._3-1)))
    else {
      if (a._3 == b._3) {
        val x = a._1.toInt
        val y = b._1.toInt
        if ( x < y) "<"
        else if (x > y) ">"
        else "="
      } else if (a._3 > b._3) {
        val x = (a._1 + "0").toInt
        val y = b._1.toInt
        if ( x < y) "<"
        else if (x > y) ">"
        else "="
      } else {
        val x = (a._1).toInt
        val y = (b._1 + "0").toInt
        if ( x < y) "<"
        else if (x > y) ">"
        else "="
      }
    }

  }

  def pow10(a: Int): Long = {
    var result = 1L
    for (_ <- 0.until(a)) result = result * 10L
    result
  }
  start()
}

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)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 = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        var x1 = readInt()
        val p1 = readInt()
        var x2 = readInt()
        val p2 = readInt()
        var c1 = 0
        var c2 = 0
        var tmp = x1
        while (tmp > 0) {
            c1 += 1
            tmp /= 10
        }
        tmp = x2
        while (tmp > 0) {
            c2 += 1
            tmp /= 10
        }
        if (p1 + c1 > p2 + c2) {
            writer.println('>')
        }
        if (p1 + c1 < p2 + c2) {
            writer.println('<')
        }
        if (p1 + c1 == p2 + c2){
            while (c1 < c2) {
                c1 += 1
                x1 *= 10
            }
            while (c2 < c1) {
                c2 += 1
                x2 *= 10
            }
            if (x1 < x2) {
                writer.println('<')
            }
            if (x1 > x2){
                writer.println('>')
            }
            if (x1 == x2){
                writer.println('=')
            }
        }

        def check(kk: Int): Boolean = {
            return true
        }
        def bs(st:Int, en:Int): Int = {
            if (en - st <= 1) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}