Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened:  if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing;  if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\rightarrow$$$ abb $$$\rightarrow$$$ abba $$$\rightarrow$$$ abbac $$$\rightarrow$$$ abbaca $$$\rightarrow$$$ abbacabb $$$\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string $$$s$$$ consisting of no less than $$$1$$$ and no more than $$$500$$$ lowercase Latin letters.

For each test case, print one line containing a string $$$res$$$. The string $$$res$$$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, $$$res$$$ should be empty.

import java.util.Scanner

object Main {

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

	def solve(): Unit = {
		val inp = new Scanner(System.in)
		val n = inp.nextInt()
		var cnt = 1
		inp.nextLine()
		(1 to n).foreach(_=>{
			val arr = new Array[Int](26)

			val s = inp.nextLine()
			for(i<- 1 until s.length){
				if(s.charAt(i)==s.charAt(i-1)){
					cnt+=1
				}else{
					if((cnt & 1) == 1){
						val c: Int = s.charAt(i-1) - 'a'
						arr(c) = 1
					}
					cnt = 1
				}
			}
			if((cnt & 1) == 1){
				val c: Int = s.charAt(s.length-1) - 'a'
				arr(c) = 1
			}
			cnt=1

			('a' to 'z').foreach(v=>{
				if(arr((v-'a')) == 1) print(v)
			})
			println()

		})

	}
}

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

object Main extends App {

  val n = readLine().toInt

  val alph = "qwertyuiopasdfghjklzxcvbnm"

  for(i <- 0 to n-1) {
    var st = readLine()
    for (i <- alph) {
      val pattern = i.toString + i.toString
      st = st.replaceAll(pattern, "-")
    }
    st = st.replaceAll("-", "")
    var set: mutable.TreeSet[String] = mutable.TreeSet()
    for (i <- st) {
      set += i.toString
    }
    val res = set.mkString
    println(res)
  }

}

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

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

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

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

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

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

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

object Workspace {
  import Main._
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val s = ns()
      val ok = Array.ofDim[Boolean](26)
      var cnt = 0
      REP(s.length) { i =>
        if (i == 0 || s(i) == s(i - 1)) cnt += 1
        else {
          ok(s(i-1)-'a') |= cnt % 2 == 1
          cnt = 1
        }
      }
      ok(s.last-'a') |= cnt % 2 == 1
      REP(26) { i =>
        if (ok(i)) out.print(('a'+i).toChar)
      }
      out.println()
    }
  }
}

object KeyBoard extends App {

  val array = readFromTerminal()
  for (row <- array)
    println(compute(row))

  def readFromTerminal() = {
//    val n = 1
    val n = readInt()
//    val t = List("aadffgfd")
    val t: Seq[String] = for (i <- 1 to n) yield  readLine()
    t
  }

  def compute(row: String): String = {
    var mutable: Array[Char] = row.toCharArray
    var i = 1
    while (i < mutable.length) {
//      println(s"compare ${mutable(i - 1)} and ${mutable(i)}")
      if (mutable(i - 1) == mutable(i)) {
        mutable(i - 1) = 0
        mutable(i) = 0
      }
      i = i + 1
    }
    mutable.toSet.toList.sortWith(_.compareTo(_) < 0).mkString.trim
  }
}

object A1251 {

  import IO._
  import collection.{mutable => cu}
  import scala.collection.mutable.ArrayBuffer
  def check(str: String, char: Char): Boolean = {
    if (str.contains(char)) {
      var i = 0
      while (i < str.length && i != -1) {
        i = str.indexWhere(_ == char, i)
        if (i != -1) {
          val count = str.drop(i).takeWhile(_ == char).length
          if (count % 2 == 1)
            return true
          i += count
        }
      }
      false
    } else false
  }

  def main(args: Array[String]): Unit = {
    var t = readInt
    while (t > 0) {
      val str = read
      for (ch <- 'a' to 'z') {
        if (check(str, ch))
          out.print(ch)
      }
      out.println()
      t -= 1
    }
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

  override def apply(implicit io: IO): io.type = repeat {
    val s = io.read[String]
    val good = splitRepeating(s).collect({case t if t.length.isOdd => t.head})
    io.writeAll(good.distinct.sorted, separator = "").writeLine()
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(implicit io: IO): io.type
  def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  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 splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

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

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

object Main extends App {

  val n = readLine().toInt

  val alph = "qwertyuiopasdfghjklzxcvbnm"

  for(i <- 0 to n-1) {
    var st = readLine()
    for (i <- alph) {
      val pattern = i.toString + i.toString
      st = st.replaceAll(pattern, "")
    }
    var set: mutable.TreeSet[String] = mutable.TreeSet()
    for (i <- st) {
      set += i.toString
    }
    val res = set.mkString
    println(res)
  }

}

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

  override def apply(io: IO): io.type = {
    repeat(io.read[Int]) {
      val s = io.read[String]
      val good = splitRepeating(s).collect({case t if t.length%2 == 1 => t.head})
      io.writeAll(good.sorted, separator = "").writeLine()
    }
    io
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

  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 splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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

  override def apply(io: IO): io.type = {
    repeat(io.read[Int]) {
      val s = io.read[String]
      val good = splitRepeating(s).collect({case t if t.size == 1 => t.head})
      io.writeAll(good.sorted, separator = "").writeLine()
    }
    io
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

  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 splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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


There are $$$n$$$ TV shows you want to watch. Suppose the whole time is split into equal parts called "minutes". The $$$i$$$-th of the shows is going from $$$l_i$$$-th to $$$r_i$$$-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments $$$[l_i, r_i]$$$ and $$$[l_j, r_j]$$$ intersect, then shows $$$i$$$ and $$$j$$$ can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to "move" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for $$$x$$$ rupees, and charges $$$y$$$ ($$$y < x$$$) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes $$$[a; b]$$$ you will need to pay $$$x + y \cdot (b - a)$$$. You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo $$$10^9 + 7$$$.

The first line contains integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le y < x \le 10^9$$$) — the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^9$$$) denoting the start and the end minute of the $$$i$$$-th TV show.

Print exactly one integer — the minimum cost to view all the shows taken modulo $$$10^9 + 7$$$.

NoteIn the first example, the optimal strategy would be to rent $$$3$$$ TVs to watch:  Show $$$[1, 2]$$$ on the first TV, Show $$$[4, 10]$$$ on the second TV, Shows $$$[2, 4], [5, 9], [10, 11]$$$ on the third TV. This way the cost for the first TV is $$$4 + 3 \cdot (2 - 1) = 7$$$, for the second is $$$4 + 3 \cdot (10 - 4) = 22$$$ and for the third is $$$4 + 3 \cdot (11 - 2) = 31$$$, which gives $$$60$$$ int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo $$$10^9 + 7$$$.

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

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

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

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

  def solve(): Unit = {
    val N, X, Y = ni()
    val (from, to) = na2(N)

    case class Point(v: Int, tpe: Int, i: Int)
    val P = Array.ofDim[Point](N * 2)
    rep(N) { i =>
      P(i * 2) = Point(from(i), 0, i)
      P(i * 2 + 1) = Point(to(i), 1, i) // 同じ場所ならTOの方が処理が後にならないと困る
    }

    Sorting.quickSort(P)(Ordering.by(a => (a.v, a.tpe)))

    var ans = N.toLong * X % MOD
    rep(N) { i =>
      ans = (ans + Y.toLong * (to(i) - from(i))) % MOD
    }

    val found = new java.util.ArrayDeque[Int]
    rep(N * 2) { i =>
      val p = P(i)
      p.tpe match {
        case 0 =>
          if (!found.isEmpty) {
            if ((p.v - found.peek).toLong * Y < X) {
              val top = found.pop()
              ans = (MOD + ans + (p.v - top).toLong * Y - X) % MOD
            }
          }

        case 1 =>
          found.addFirst(p.v)
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, X, Y = ni()
    val (from, to) = na2(N)

    case class Point(v: Int, tpe: Int, i: Int)
    val P = Array.ofDim[Point](N * 2)
    rep(N) { i =>
      P(i * 2) = Point(from(i), 0, i)
      P(i * 2 + 1) = Point(to(i), 1, i) // 同じ場所ならTOの方が処理が後にならないと困る
    }

    Sorting.quickSort(P)(Ordering.by(a => (a.v, a.tpe)))

    var ans = N.toLong * X % MOD
    rep(N) { i =>
      ans = (ans + Y.toLong * (to(i) - from(i))) % MOD
    }

    val found = new java.util.ArrayDeque[Int]
    rep(N * 2) { i =>
      val p = P(i)
      p.tpe match {
        case 0 =>
          if (!found.isEmpty) {
            if ((p.v - found.peek).toLong * Y < X) {
              val top = found.pop()
              ans = (ans + (p.v - top).toLong * Y - X) % MOD
            }
          }

        case 1 =>
          found.addFirst(p.v)
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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


A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define:  $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column.  $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$).  $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$).  In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$.  For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.

NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.

import scala.io.StdIn._

object D extends App {

  def display(A: Array[Array[Int]]): Unit = {
    var maxR = -1
    var minR = Int.MaxValue

    var maxC = -1
    var minC = Int.MaxValue

    for {
      row <- A.indices
    } {
      val s = A(row).sum
      maxR = Math.max(maxR, s)
      minR = Math.min(minR, s)
    }

    val B = A.transpose
    for {
      row <- B.indices
    } {
      val s = B(row).sum
      maxC = Math.max(maxC, s)
      minC = Math.min(minC, s)
    }

    val left  = (maxR - minR)
    val right = (maxC - minC)
    println(left * left + right * right)
    for {
      row <- A.indices
    } {
      println(A(row).mkString)
    }
  }

  val t = readInt()
  1 to t foreach { _ =>
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val A           = Array.fill(n, n)(0)

    var row       = 0
    var col       = 0
    var colOffset = 1

    for (i <- 0 until k) {
      A(row)(col) = 1

      row += 1
      col += 1
      if (row == n) {
        row = 0
        col = colOffset
        colOffset += 1
      } else {
        col = col % n
        row = row % n
      }
    }

    display(A)
  }
}


You have a string $$$s$$$ of length $$$n$$$ consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).For example, if we choose character > in string > > < >, the string will become to > > >. And if we choose character < in string > <, the string will become to <.The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good. Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to $$$n - 1$$$, but not the whole string). You need to calculate the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of test cases. Each test case is represented by two lines. The first line of $$$i$$$-th test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) – the length of string $$$s$$$. The second line of $$$i$$$-th test case contains string $$$s$$$, consisting of only characters > and <.

For each test case print one line. For $$$i$$$-th test case print the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.

NoteIn the first test case we can delete any character in string <>.In the second test case we don't need to delete any characters. The string > < < is good, because we can perform the following sequence of operations: > < < $$$\rightarrow$$$ < < $$$\rightarrow$$$ <.

import scala.math._, scala.io.StdIn._

object Foo extends App {
  val t = readInt

  for (i <- 0 until t) {
    val n = readInt
    val s = readLine

    println(min(s.prefixLength(_=='<'),
                s.reverse.prefixLength(_=='>')))
  }

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

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 java.util.Arrays

  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 = {
    REP(ni()) { _ =>
      val N = ni()
      val S = ns(N)

      var ans = 0
      val ix = S.lastIndexWhere(_ == '<')
      val ix2 = S.indexWhere(_ == '>')

      if (ix != -1 && ix2 != -1) {
        ans = min(N - 1 - ix, ix2)
      } else {
        ans = 0
      }

      out.println(ans)
    }
  }

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

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

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

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

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

object B extends App {

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

  val Array(t) = readInts(1)

  for (_ <- 1 to t) {
    val Array(n) = readInts(1)
    val s = readLine
    val l = s.takeWhile(_ == '<').length
    val r = s.reverse.takeWhile(_ == '>').length
    println(l min r)
  }
  Console.flush
}


A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height — use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as: +-        -++- -+    |+- -++- -+||   |||   ||   |||   ||+- -++- -+||   |+-        -++- -+Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.

The first line contains an even integer n (2 ≤ n ≤ 100) — the length of the sequence of brackets. The second line contains the sequence of brackets — these are n symbols "[" and "]". It is guaranteed that the given sequence of brackets is regular.

Print the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces.

/**
  * Created by ruslan on 3/12/17.
  */
object ProblemD extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  val br = new BufferedReader(new InputStreamReader(System.in))
  var st: StringTokenizer = null
  val out = new PrintWriter(System.out)

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

  def nextInt: Int = next.toInt

  val n = nextInt
  val inputString = next
  val base = new Empty()

  var lastClosed = new Empty
  var queue: List[Expression] = List(base)

  for (s <- inputString.toCharArray) {
    if (s == '[') {
      val newOpen = new Brackets
      queue match {
        case last :: tail => last.add(newOpen)
      }
      queue = newOpen :: queue
    }
    else {
      queue match {
        case last :: tail => {
          if (last.getExpressions == Nil) last.add(new Empty)
          queue = tail
        }
      }
    }
  }

  val maxLevel = base.getExpressions.foldLeft(0)((acc, e) => Math.max(acc, e.level))

  base.getString(maxLevel).foreach(println)
}

abstract class Expression {
  var expressions: List[Expression] = Nil
  var parent: Expression = _
  var level: Int = 2

  def add(e: Expression): Unit = {
    expressions = e :: expressions
    e.setParent(this)
    if (parent != null) parent.incrementLevel(level)
  }

  def setParent(e: Expression): Unit = this.parent = e

  def incrementLevel(subLevel: Int): Unit = {
    level = Math.max(level, subLevel + 1)
    if (parent != null) parent.incrementLevel(level)
  }

  def getExpressions: List[Expression] = expressions

  def getString(level: Int): Array[String]
}

class Brackets extends Expression {
  override def getString(level: Int): Array[String] = {
    val base = expressions.reverse.foldLeft(Array[String]())((a, e) => {
      val leftSide = e.getString(level - 1)
      a.zipAll(leftSide, "", "").foldLeft(Array[String]())((acc, pair) => Array.concat(acc, Array(pair._1 + pair._2)))
    })

    val topBottom = "+-" + " " * (base(0).length - 2) + "-+"
    for (i <- base.indices) base(i) = "|" + base(i) + "|"
    Array.concat(Array(topBottom), base, Array(topBottom))
  }
}

class Empty extends Expression {
  override def getString(level: Int): Array[String] = {
    if (expressions != Nil) {
      expressions.reverse.foldLeft(Array[String]())((a, e) => {
        val leftSide = e.getString(level)
        a.zipAll(leftSide, "", "").foldLeft(Array[String]())((acc, pair) => Array.concat(acc, Array(pair._1 + pair._2)))
      })
    } else {

      val emptySpace = new Array[String]((level - 1) * 2 + 1)
      for (i <- emptySpace.indices) emptySpace(i) = "   "

      emptySpace
    }
  }
}


Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.

A single line contains two integers m and n (1 ≤ m, n ≤ 105).

Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10  - 4.

NoteConsider the third test example. If you've made two tosses:  You can get 1 in the first toss, and 2 in the second. Maximum equals to 2.  You can get 1 in the first toss, and 1 in the second. Maximum equals to 1.  You can get 2 in the first toss, and 1 in the second. Maximum equals to 2.  You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value

import scala.io.StdIn._

object Main {

  def power(a: Double, n: Int): Double = {
    var ans = 1.0
    var b = a
    var p = n
    while (p > 0) {
      if ( (p & 0x01) != 0) ans = b * ans
      b = b * b
      p = p >> 1;
    }
    ans
  }
  def main(args: Array[String]): Unit = {
    val mn = readLine.split(" ").map(_.toInt)
    val m = mn.head
    val n = mn.last
    val ans = (1 to m).map { k =>
      k * (power((k*1.0)/m, n) - power(((k*1.0) - 1.0)/m, n))
    }.sum
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val m = cin.nextInt()
    val n = cin.nextInt()
    def solve(i: Int, res: Double):Double =
      if (i == 0) res
      else solve(i - 1, res + i * (Math.pow((1.0 * i) / m, n) - Math.pow((i - 1.0) / m, n)))
    println(solve(m, 0))
  }
}

object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val m = cin.nextInt()
    val n = cin.nextInt()
    var ans: Double = 0.0
    for (i <- 1 to m)
      ans += i * (Math.pow(i.toDouble / m, n) - Math.pow((i - 1.0) / m, n))
    println(ans)
  }
}

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

/**
 * Created by arseny on 01.08.14.
 */
object C extends App {

  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val m = nextDouble
    val n = nextDouble
    if (m == 1) {
      out.println(1)
    } else {
      var ans = m
      for (i <- 1 to (m - 1).toInt) {
        val p = i.toDouble / m
        val q = math.pow(p, n)
        ans = ans - q
      }
      out.println("%.6f".format(ans))
    }
  }

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

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object C extends App {

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

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

  val mn = math.pow(m.toDouble, n)
  var sum = 0d
  var prevCount = 0d
  for (i <- 1 to m) {
    val count = math.pow(i.toDouble / m.toDouble, n)
    //println(sum, count, i)
    sum += (count - prevCount) * i
    prevCount = count// - prevCount
  }

  println(sum)
}

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

object C {

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

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

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

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

  def solve: Int = {
    val m = nextInt
    val n = nextInt
    var ans: Double = m.toDouble
    for (i <- 0 to m - 1) {
      ans -= Math.pow(i.toDouble / m.toDouble, n)
    }
    out.println(ans)
    return 1
  }

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

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

object C {

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

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

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

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

  def solve: Int = {
    val m = nextInt
    val n = nextInt
    var ans: Double = 0.0d
    val delimeter: Double = Math.pow(m, n)
    for (i <- 1 to m) {
      ans += Math.pow(i.toDouble, n + 1) - Math.pow(i - 1, n) * i.toDouble
    }
    out.println(ans / delimeter)
    return 1
  }

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


You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.

The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.

Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.

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

object C {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val g = new ArrayList[List[(Int, Long)]]
    for (i <- 0 until n) {
      g.add(new util.ArrayList[(Int, Long)]())
    }
    for (i <- 0 until m) {
      val a = nextInt - 1
      val b = nextInt - 1
      val len = nextLong
      g.get(a).add((b, len))
      g.get(b).add((a, len))
    }
    val graph = new Array[Array[(Int, Long)]](n)
    for (i <- 0 until n) {
      graph(i) = new Array[(Int, Long)](g.get(i).size)
      val len = graph(i).length
      for (j <- 0 until len) {
        graph(i)(j) = g.get(i).get(j)
      }
    }

    object Dijkstra {
      val path = new Array[Int](n)

      def findShortestPath(start: Int, end: Int): (Long, Array[Int]) = {
        val dist = new Array[Long](n)
        val relaxed = new Array[Boolean](n)
        Arrays.fill(dist, Long.MaxValue)
        dist(start) = 0
        val set = new util.PriorityQueue[Edge]()
        val path = new Array[Int](n)
        Arrays.fill(path, -1)
        set.add(new Edge(dist(start), start))
        while (!set.isEmpty) {
          val v = set.poll().to
          if (!relaxed(v)) {
            for (i <- 0 until graph(v).length) {
              val to = graph(v)(i)._1
              val len = graph(v)(i)._2
              if (dist(v) + len < dist(to)) {
                relaxed(v) = true
                dist(to) = dist(v) + len
                path(to) = v
                set.add(new Edge(dist(to), to))
              }
            }
          }
        }
        return (dist(end), path)
      }
    }
    val (dist, p) = Dijkstra.findShortestPath(0, n - 1)
    if (dist == Long.MaxValue) {
      out.println(-1)
    } else {
      val path = new util.ArrayList[Int]()
      var v = n - 1
      while (v != 0) {
        path.add(v + 1)
        v = p(v)
      }
      path.add(1)
      for (i <- path.size - 1 to 0 by -1) {
        out.print(path.get(i) + " ")
      }
    }
    return 1
  }

  class Edge(var len: Long, var to: Int) extends Comparable[Edge] {

    override def compareTo(o: Edge): Int = -java.lang.Long.compare(o.len, this.len)
  }

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

import scala.io.Source
import scala.collection.mutable

object Main extends App {
  // process input!
  val input = Source.stdin.getLines.map(_.split(" ").map(_.toInt))
  type Node = Int
  type Weight = Int
  val graph = mutable.Map.empty[Node, mutable.Map[Node, Weight]]
  val (n :: numEdges :: Nil) = input.next.toList
  val edges = input.map(_.toList)

  // construct the graph!
  def makeEdge(from: Node, to: Node, weight: Weight) = {
      val source = graph.getOrElseUpdate(from, mutable.Map.empty[Node, Weight])
      source.get(to) match {
        case None => source.update(to, weight)
        case Some(prevWeight) => if(weight < prevWeight) source.update(to, weight)
      }
  }
  edges.foreach {
    case from :: to :: weight :: Nil => {
      makeEdge(from, to, weight)
      makeEdge(to, from, weight)
    }
    case _ => ()
  }

  // Prepare for Dijkstra! This represents a graph path!
  case class Path(val fullPath: List[Node], val cost: Weight) {
    def location = fullPath.head
    override def toString = fullPath.mkString(" ")
  }

  // Sort by lowest cost! and then target, so paths with same weight don't clobber each other!
  implicit val pathOrdering: Ordering[Path] = Ordering.by(path => (path.cost, path.location))

  // For example, we begin at node 1 with a cost of 0!
  val end = Path(List(n), 0)

  // Here are the Dijkstra Data Doodads of Doom!
  val conquered = mutable.Set.empty[Node]
  val frontier = new java.util.PriorityQueue[Path](10, pathOrdering)
  frontier.offer(end)

  // Here is the algorithm! Yay! I AM NAPOLEON!!!!
  var warPath: Option[Path] = None
  while(warPath.isEmpty && !frontier.isEmpty) {
    val battlefield = frontier.poll
    val location = battlefield.location
    if(location == 1) {
      warPath = Some(battlefield)
    } else {
      conquered += location
      for {
        connections <- graph.get(location).toList
        (target, weight) <- connections
        if !conquered(target)
      } yield {
        frontier.add(Path(
          fullPath = target :: battlefield.fullPath,
          cost = battlefield.cost + weight))
      }
    }
  }

  // And our answer!!!!!!!!!!!
  warPath match {
    case None => println("-1")
    case Some(path) => println(path)
  }
}

import scala.io.Source
import scala.collection.mutable

object Main extends App {
  // process input!
  val input = Source.stdin.getLines.map(_.split(" ").map(_.toInt))
  type Node = Int
  type Weight = Int
  val graph = mutable.Map.empty[Node, mutable.Map[Node, Weight]]
  val (n :: numEdges :: Nil) = input.next.toList
  val edges = input.map(_.toList)

  // construct the graph!
  def makeEdge(from: Node, to: Node, weight: Weight) = {
      val source = graph.getOrElseUpdate(from, mutable.Map.empty[Node, Weight])
      source.get(to) match {
        case None => source.update(to, weight)
        case Some(prevWeight) if(weight < prevWeight) => source.update(to, weight)
        case _ => ()
      }
  }
  edges.foreach {
    case from :: to :: weight :: Nil => {
      makeEdge(from, to, weight)
      makeEdge(to, from, weight)
    }
    case _ => ()
  }

  // Prepare for Dijkstra! This represents a graph path!
  sealed abstract class Path {
    def cost: Int
  }
  case object Stop extends Path {
    override val toString = ""
    override val cost = 0
  }
  case class Go(val location: Node, val cost: Weight, val prev: Path) extends Path {
    override val toString = s"${prev.toString} $location".trim
  }

  // Sort by lowest cost!
  implicit val goOrdering: Ordering[Go] = Ordering.by(_.cost)

  // For example, we begin at node 1 with a cost of 0!
  val start = Go(1, 0, Stop)

  // Here are the Dijkstra Data Doodads of Doom!
  val conquered = mutable.Set.empty[Path]
  val frontier = mutable.SortedSet[Go](start)
  val enemy = mutable.Set((2 to n).toList:_*)

  // Here is the algorithm! Yay!
  var warPath: Option[Path] = None
  while(warPath.isEmpty && !frontier.isEmpty) {
    val battlefield = frontier.min
    frontier -= battlefield
    if(battlefield.location == n) {
      warPath = Some(battlefield)
    } else {
      conquered += battlefield
      for {
        connections <- graph.get(battlefield.location).toList
        (target, weight) <- connections
        totalCost = battlefield.cost + weight
        if enemy(target) || frontier.exists {
          case Go(targ, cost, _) => targ == target && cost > totalCost
        }
      } yield {
        frontier += Go(
          location = target,
          cost = totalCost,
          prev = battlefield)
        enemy -= target
      }
    }
  }

  // And our answer!!!!!!!!!!!
  warPath match {
    case None => println("-1")
    case Some(path) => println(path)
  }
}

import scala.io.Source
import scala.collection.mutable

object Main extends App {
  // process input!
  val input = Source.stdin.getLines.map(_.split(" ").map(_.toInt))
  type Node = Int
  type Weight = Int
  val graph = mutable.Map.empty[Node, mutable.Map[Node, Weight]]
  val (n :: numEdges :: Nil) = input.next.toList
  val edges = input.map(_.toList)

  // construct the graph!
  def makeEdge(from: Node, to: Node, weight: Weight) = {
      val source = graph.getOrElseUpdate(from, mutable.Map.empty[Node, Weight])
      source.get(to) match {
        case None => source.update(to, weight)
        case Some(prevWeight) => if(weight < prevWeight) source.update(to, weight)
      }
  }
  edges.foreach {
    case from :: to :: weight :: Nil => {
      makeEdge(from, to, weight)
      makeEdge(to, from, weight)
    }
    case _ => ()
  }

  // Prepare for Dijkstra! This represents a graph path!
  case class Path(val fullPath: List[Node], val cost: Weight) {
    def location = fullPath.head
    override def toString = fullPath.mkString(" ")
  }

  // Sort by lowest cost! and then target, so paths with same weight don't clobber each other!
  implicit val pathOrdering: Ordering[Path] = Ordering.by(path => (-path.cost, path.location))

  // For example, we begin at node 1 with a cost of 0!
  val end = Path(List(n), 0)

  // Here are the Dijkstra Data Doodads of Doom!
  val conquered = mutable.Set.empty[Node]
  val frontier = new java.util.PriorityQueue[Path](10, pathOrdering)
  frontier.offer(end)

  // Here is the algorithm! Yay! I AM NAPOLEON!!!!
  var warPath: Option[Path] = None
  while(warPath.isEmpty && !frontier.isEmpty) {
    val battlefield = frontier.poll
    val location = battlefield.location
    if(location == 1) {
      warPath = Some(battlefield)
    } else {
      conquered += location
      for {
        connections <- graph.get(location).toList
        (target, weight) <- connections
        if !conquered(target)
      } yield {
        frontier.add(Path(
          fullPath = target :: battlefield.fullPath,
          cost = battlefield.cost + weight))
      }
    }
  }

  // And our answer!!!!!!!!!!!
  warPath match {
    case None => println("-1")
    case Some(path) => println(path)
  }
}


Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.You are given an array a of length n and an integer c. The value of some array b of length k is the sum of its elements except for the  smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.

The first line contains integers n and c (1 ≤ n, c ≤ 100 000). The second line contains n integers ai (1 ≤ ai ≤ 109) — elements of a.

Output a single integer  — the smallest possible sum of values of these subarrays of some partition of a.

NoteIn the first example any partition yields 6 as the sum.In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively.In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively.

object eCashback {

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

    class SortedSeq {
      private val storage: mutable.TreeMap[Int, Int] = new mutable.TreeMap[Int, Int]
      private var sum:BigInt = 0

      def add(elem: Int):Unit = {
        storage(elem) = storage.getOrElse(elem, 0) + 1
        sum+=elem
      }

      def remove(elem: Int): Unit = {
        storage.get(elem) match {
          case None => ()
          case Some(1) => storage-= elem
          case Some(x) => storage(elem) = x - 1
        }
        sum-=elem
      }

      def min:Int = storage.head._1

      def cost:BigInt = sum - min

      override def toString: String = storage.toString()
    }

    def cashback(n: Int, c: Int, arr: Array[Int]):BigInt = {

    val seq = new SortedSeq

    val dp: Array[BigInt] = (0 until n).map(_ => BigInt(0)).toArray
    for (i <- 0 until n) {
      seq.add(arr(i))
      if (i < c - 1) dp(i) = {if (i > 0) dp(i-1) else BigInt(0)} + arr(i)
      else if (i == c - 1) dp(i) = seq.cost
      else {
        seq.remove(arr(i - c))
        dp(i) = if (dp(i - 1) + arr(i) < dp(i - c) + seq.cost) dp(i - 1) + arr(i) else dp(i - c) + seq.cost
      }
    }
    dp(n - 1)
  }

  def main(args: Array[String]):Unit = {
    val n::c::Nil = readLine().split(" ").map(_.toInt).toList
    val arr = readLine.split(" ").map(_.toInt)
    println(cashback(n, c, arr))
  }
}

import java.util.StringTokenizer

import scala.collection.mutable

object E extends App {
  val INF = 1 << 30

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

  read()
  val n = int()
  val c = int()

  read()
  val a = Array.fill(n)(int())
  val b = new Array[Long](n)
  var globalMax = 0L

  val latest = mutable.SortedMap.empty[Int, Int]

  for (i <- 0 until n) {
    var previous = 0L
    val v = a(i)
    latest(v) = latest.getOrElse(v, 0) + 1
    if (i >= c) {
      val q = a(i-c)
      val qq = latest(q)
      if (qq == 1) latest.remove(q)
      else latest(q) = qq - 1
      previous = b(i-c)
    }
    if (i >= c-1) {
      globalMax = Math.max(globalMax, previous + latest.firstKey)
    }
    b(i) = globalMax
  }

  val sum = a.foldLeft(0L)(_ + _)
  println(sum - globalMax)

}

object eCashback {

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

    class SortedSeq {
      private val storage: mutable.TreeMap[Int, Int] = new mutable.TreeMap[Int, Int]
      private var sum:BigInt = 0

      def add(elem: Int):Unit = {
        storage(elem) = storage.getOrElse(elem, 0) + 1
        sum+=elem
      }

      def remove(elem: Int): Unit = {
        storage.get(elem) match {
          case None => ()
          case Some(1) => storage-= elem
          case Some(x) => storage(elem) = x - 1
        }
        sum-=elem
      }

      def min:Int = storage.head._1

      def cost:BigInt = sum - min

      override def toString: String = storage.toString()
    }

    def cashback(n: Int, c: Int, arr: Array[Int]):BigInt = {

    val seq = new SortedSeq

    val dp: Array[BigInt] = (0 until n).map(_ => BigInt(0)).toArray
    dp(0) = arr(0)
    seq.add(arr(0))
    for (i <- 1 until n) {
      seq.add(arr(i))
      if (i < c - 1) dp(i) = dp(i-1) + arr(i)
      else if (i == c - 1) {
        dp(i) = seq.cost
      }
      else {
        seq.remove(arr(i - c))
        dp(i) = if (dp(i - 1) + arr(i) < dp(i - c) + seq.cost) dp(i - 1) + arr(i) else dp(i - c) + seq.cost
      }
    }
    dp(n - 1)
  }

  def main(args: Array[String]):Unit = {
    val n::c::Nil = readLine().split(" ").map(_.toInt).toList
    val arr = readLine.split(" ").map(_.toInt)
    println(cashback(n, c, arr))
  }
}

object eCashback {

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

    class SortedSeq {
      private val storage: mutable.TreeMap[Int, Int] = new mutable.TreeMap[Int, Int]
      private var sum = 0

      def add(elem: Int):Unit = {
        storage(elem) = storage.getOrElse(elem, 0) + 1
        sum+=elem
      }

      def remove(elem: Int): Unit = {
        storage.get(elem) match {
          case None => ()
          case Some(1) => storage-= elem
          case Some(x) => storage(elem) = x - 1
        }
        sum-=elem
      }

      def min:Int = storage.head._1

      def cost:Int = sum - min

      override def toString: String = storage.toString()
    }

    def cashback(n: Int, c: Int, arr: Array[Int]):Int = {

    val seq = new SortedSeq

    val dp: Array[Int] = (0 until n).map(_ => 0).toArray
    dp(0) = arr(0)
    seq.add(arr(0))
    for (i <- 1 until n) {
      seq.add(arr(i))
      if (i < c - 1) dp(i) = dp(i-1) + arr(i)
      else if (i == c - 1) {
        dp(i) = seq.cost
      }
      else {
        seq.remove(arr(i - c))
        dp(i) = math.min(dp(i - 1) + arr(i), dp(i - c) + seq.cost)
      }
    }
    dp(n - 1)
  }

  def main(args: Array[String]):Unit = {
    val n::c::Nil = readLine().split(" ").map(_.toInt).toList
    val arr = readLine.split(" ").map(_.toInt)
    println(cashback(n, c, arr))
  }
}


One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.

Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map(_ => in.next()).groupBy(x => x).maxBy(_._2.length)._1)
}

object A43 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val goals = Array.fill(n)(read)
    val diff = goals.toSet.toArray
    val map = collection.mutable.Map[String, Int]().withDefaultValue(0)
    for(i <- diff) {
      map(i) = goals.count(_ == i)
    }
    println(map.toArray.maxBy(_._2)._1)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

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

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

  val N = sc.nextInt
  sc.nextLine
  val GOALS = List.fill(N)(sc.nextLine)

  def solve(): String = GOALS.groupBy(identity).toSeq.sortWith(_._2.size > _._2.size).head._1

  out.println(solve)
  out.close
}

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var map = Map[String, Int]();
    for (i <- 0 until n) {
      var s = readLine;
      map.put(s, map.getOrElse(s, 0) + 1);
    }
    println(map.maxBy(_._2)._1);
  }
}

object Main {
  def main(args: Array[String]) = {
    var n = readInt()
    val map = scala.collection.mutable.Map[String, Int]()
    for(_ <- 1 to n) {
      val c = readLine()
      map(c) = map.getOrElse(c, 0) + 1
    }
    val e = map.toList.sortBy(_._2).reverse.apply(0)
    println(e._1)
  }
}


Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA $$$\to$$$ AABBA $$$\to$$$ AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 20000)$$$  — the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains a single test case each, consisting of a non-empty string $$$s$$$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $$$s$$$ are either 'A' or 'B'. It is guaranteed that the sum of $$$|s|$$$ (length of $$$s$$$) among all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer: the length of the shortest string that Zookeeper can make.

NoteFor the first test case, you can't make any moves, so the answer is $$$3$$$.For the second test case, one optimal sequence of moves is BABA $$$\to$$$ BA. So, the answer is $$$2$$$.For the third test case, one optimal sequence of moves is AABBBABBBB $$$\to$$$ AABBBABB $$$\to$$$ AABBBB $$$\to$$$ ABBB $$$\to$$$ AB $$$\to$$$ (empty string). So, the answer is $$$0$$$.

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val s = nextLine
      var prev = ' '
      val cntsBuilder = new mutable.ArrayBuilder.ofInt
      var cnt = 1
      for (c <- s) {
        if (c == prev) {
          cnt += 1
        } else if (prev == 'A') {
          cntsBuilder += -cnt
          cnt = 1
        } else if (prev == 'B') {
          cntsBuilder += cnt
          cnt = 1
        }
        prev = c
      }
      if (prev == 'A') {
        cntsBuilder += -cnt
      } else if (prev == 'B') {
        cntsBuilder += cnt
      }
      var cnts = cntsBuilder.result()

      var changed = true
      while (changed) {
//        println(cnts.mkString(" "))
        changed = false
        for (i <- 1 until cnts.length) {
          val a = cnts(i - 1)
          val b = cnts(i)
          if (a < 0 && b > 0) {
            val c = math.min(-a, b)
            cnts(i - 1) += c
            cnts(i) -= c
            changed = true
          }
        }
        cnts = cnts.filter(_ != 0)
      }

      changed = true
      while (changed) {
        changed = false
        for (i <- cnts.indices) {
          if (cnts(i) > 1) {
            cnts(i) %= 2
            changed = true
          }
        }
        cnts = cnts.filter(_ != 0)
        for (i <- 1 until cnts.length) {
          if (cnts(i - 1) == 1 && cnts(i) == 1) {
            cnts(i - 1) = 0
            cnts(i) = 0
          }
        }
        cnts = cnts.filter(_ != 0)
      }

      out.println(cnts.map(math.abs).sum)
    }

    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 C extends App {
  import scala.io.StdIn._

  val t = readInt()

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

    val ans = s
      .foldLeft(List.empty[Char]) {
        case ('A' :: t, 'B') => t
        case ('B' :: t, 'B') => t
        case (ls, c)         => c :: ls
      }
      .length

    println(ans)
  }
}