You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.

First line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.

Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.

NoteIn the first example, "aba" is a subsequence of "aba" which is a palindrome.In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.

object A932 {

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

  def main(args: Array[String]): Unit = {
    var tests = 1 // readInt
    while(tests > 0) {
      val n = read
      out.print(n)
      out.println(n.reverse)
      tests -= 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 A extends App {

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

  val s = readLine
  println(s + s.reverse)
}

object A extends App {
  val a = scala.io.StdIn.readLine()
  def b(a: String): String = {
    def _b(l: List[Char], r: List[Char], i: Int, j: Int): String =
      if (i > j) l.reverse.mkString("") + r.mkString("")
      else {
        val ai = a(i)
        val aj = a(j)
        if (ai == aj) _b(ai :: l, aj :: l, i + 1, j - 1)
        else _b(ai :: l, ai :: l, i + 1, j)
      }

    _b(Nil, Nil, 0, a.length - 1)
  }

  println(b(a))
}

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

  override def apply(io: IO): io.type = {
    val a = io.read[String]
    io.write(a + a.reverse)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p._1, ev(p._2))
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    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)}
    //def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    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 {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[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
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of 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 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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    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
      }
    }
  }
}


We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the computers with integers from 1 to n, let's index the cables with integers from 1 to m.Polycarpus was given an important task — check the reliability of his company's network. For that Polycarpus decided to carry out a series of k experiments on the computer network, where the i-th experiment goes as follows:  Temporarily disconnect the cables with indexes from li to ri, inclusive (the other cables remain connected).  Count the number of connected components in the graph that is defining the computer network at that moment.  Re-connect the disconnected cables with indexes from li to ri (that is, restore the initial network). Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.

The first line contains two space-separated integers n, m (2 ≤ n ≤ 500; 1 ≤ m ≤ 104) — the number of computers and the number of cables, correspondingly. The following m lines contain the cables' description. The i-th line contains space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the numbers of the computers that are connected by the i-th cable. Note that a pair of computers can be connected by multiple cables. The next line contains integer k (1 ≤ k ≤ 2·104) — the number of experiments. Next k lines contain the experiments' descriptions. The i-th line contains space-separated integers li, ri (1 ≤ li ≤ ri ≤ m) — the numbers of the cables that Polycarpus disconnects during the i-th experiment.

Print k numbers, the i-th number represents the number of connected components of the graph that defines the computer network during the i-th experiment.

import io.Source
import java.io.PrintWriter
import scala.collection.mutable.ArrayBuffer

object CF292D {

  class DJU(n: Int) {
    val p = Array.tabulate(n)(identity)
    val r = Array.fill(n)(0)

    def get(i: Int): Int = {
      if (p(i) == i) {
        i
      } else {
        p(i) = get(p(i))
        p(i)
      }
    }

    def join(i: Int, j: Int): Boolean = {
      val u = get(i)
      val v = get(j)
      if (u == v) {
        false
      } else {
        if (r(u) < r(v)) {
          p(u) = v
        } else {
          p(v) = u
        }
        if (r(u) == r(v)) {
          r(u) += 1
        }
        true
      }
    }

    def reset() {
      for (i <- 0 until n) {
        p(i) = i
        r(i) = 0
      }
    }
  }

  def solve(in: In, out: PrintWriter) {
    val n, m = in().toInt
    val x, y = Array.ofDim[Int](m)
    for (i <- 0 until m) {
      x(i) = in().toInt - 1
      y(i) = in().toInt - 1
    }
    val left_, right_ = ArrayBuffer.empty[Int]
    val d = new DJU(n)
    for (i <- 0 until m) {
      if (d.join(x(i), y(i))) {
        left_ += i
      }
    }
    d.reset()
    for (i <- m - 1 to (0, -1)) {
      if (d.join(x(i), y(i))) {
        right_ += i
      }
    }
    val left = left_.toArray
    val right = right_.toArray
    val k = in().toInt
    for (it <- 0 until k) {
      val l, r = in().toInt - 1
      d.reset()
      var ans = n
      var it = 0
      while (it < left.length && left(it) < l) {
        val i = left(it)
        it += 1
        if (d.join(x(i), y(i))) {
          ans -= 1
        }
      }
      it = 0
      while (it < left.length && right(it) > r) {
        val i = right(it)
        it += 1
        if (d.join(x(i), y(i))) {
          ans -= 1
        }
      }
      out.println(ans)
    }
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "thread", 64000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

import io.Source
import java.io.PrintWriter
import scala.collection.mutable.ArrayBuffer

object CF292D {

  class DJU(n: Int) {
    val p = Array.tabulate(n)(identity)
    val r = Array.fill(n)(0)

    def get(i: Int): Int = {
      if (p(i) == i) {
        i
      } else {
        p(i) = get(p(i))
        p(i)
      }
    }

    def join(i: Int, j: Int): Boolean = {
      val u = get(i)
      val v = get(j)
      if (u == v) {
        false
      } else {
        if (r(u) < r(v)) {
          p(u) = v
        } else {
          p(v) = u
        }
        if (r(u) == r(v)) {
          r(u) += 1
        }
        true
      }
    }

    def reset() {
      for (i <- 0 until n) {
        p(i) = i
        r(i) = 0
      }
    }
  }

  def solve(in: In, out: PrintWriter) {
    val n, m = in().toInt
    val x, y = Array.ofDim[Int](m)
    for (i <- 0 until m) {
      x(i) = in().toInt - 1
      y(i) = in().toInt - 1
    }
    val left_, right_ = ArrayBuffer.empty[Int]
    val d = new DJU(n)
    for (i <- 0 until m) {
      if (d.join(x(i), y(i))) {
        left_ += i
      }
    }
    d.reset()
    for (i <- m - 1 to (0, -1)) {
      if (d.join(x(i), y(i))) {
        right_ += i
      }
    }
    val left = left_.toArray
    val right = right_.toArray
    val k = in().toInt
    for (it <- 0 until k) {
      val l, r = in().toInt - 1
      d.reset()
      var ans = n
      var it = 0
      while (it < left.length && left(it) < l) {
        val i = left(it)
        it += 1
        if (d.join(x(i), y(i))) {
          ans -= 1
        }
      }
      it = 0
      while (it < left.length && left(it) < l) {
        val i = right(it)
        it += 1
        if (d.join(x(i), y(i))) {
          ans -= 1
        }
      }
      out.println(ans)
    }
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "thread", 64000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0 ≤ n ≤ 10100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

NoteIn the first sample the number already is one-digit — Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.

object Solver {
    def main(args: Array[String]) {
        var data = Console.readLine
        var count = 0

        while (data.length > 1) {
            data = data.map(_.toInt - '0'.toInt).reduceRight(_ + _).toString
            count += 1
        }
        println(count)
    }
}

object P102B extends App {
  def f(n: String) = n.toCharArray.map(_.getNumericValue).sum.toString()
  var n = readLine
  var c = 0
  while (n.size > 1) {
    n = f(n)
    c += 1
  }
  print(c)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next()
  var sum = data.foldLeft(0l){case (acc, el) => acc + el.asDigit}
  var i = 0
  if (data.length != 1) {
    i = 1
    while (sum > 9) {
      i += 1
      sum = sum.toString.foldLeft(0l) { case (acc, el) => acc + el.asDigit }
    }
  }
  println(i)
}

object Main {
  def main(args: Array[String]) {
    var n = readLine()
    var step = 0
    while(n.size != 1) {
      val sum = n.map(_.toLong - '0').sum
      n = sum.toString
      step += 1
    }
    println(step)
  }
}


You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.

For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.

NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, l, r) = readLine().split(" ").map(_.toLong)

    def collect: Unit = {
      @tailrec
      def go(i: Int = 1, p: Long = 0L): Unit =
        (p, p + 2 * (n - i)) match {
          case (p, q) if i > n || p >= r => println()
          case _ if i == n               => println(1)
          case (_, q) if q < l           => go(i + 1, q)
          case (p, q) =>
            lazy val stream: Stream[Int] = i #:: (i + 1) #:: stream.zip(stream.tail).map {
              case (j, _) if j == i => i
              case (j, _)           => j + 1
            }

            stream
              .drop(0 max (l - p - 1).toInt)
              .take((r.min(q) - p.max(l - 1)).toInt)
              .foreach(j => print(s"$j "))

            go(i + 1, q)
        }

      go()
    }

    collect
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, l, r) = readLine().split(" ").map(_.toLong)

    def collect: Unit = {
      @tailrec
      def go(i: Int = 1, p: Long = 0L): Unit =
        (p, p + 2 * (n - i)) match {
          case (p, q) if i > n || p >= r => ()
          case _ if i == n               => print(1)
          case (_, q) if q < l           => go(i + 1, q)
          case (p, q) =>
            lazy val stream: Stream[Int] = i #:: (i + 1) #:: stream.zip(stream.tail).map {
              case (j, _) if j == i => i
              case (j, _)           => j + 1
            }

            stream
              .drop(0 max (l - p - 1).toInt)
              .take((r.min(q) - p.max(l - 1)).toInt)
              .foreach(j => print(s"$j "))

            go(i + 1, q)
        }

      go()
    }

    collect
  }
}


Polycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version — positive integer from 1 to 106. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies.You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored.More formal, choose such a set of projects of minimum possible size that the following conditions hold:   Polycarp's project is chosen;  Polycarp's project depends (directly or indirectly) on all other projects in the set;  no two projects share the name;  for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order.

The first line contains an only integer n (1 ≤ n ≤ 1 000) — the number of projects in Vaja. The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to n - 1) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding. It's guaranteed that there are no cyclic dependencies.

Output all Polycarp's project's dependencies in lexicographical order.

9
codehorses 5
3
webfrmk 6
mashadb 1
mashadb 2

commons 2
0

mashadb 3
0

webfrmk 6
2
mashadb 3
commons 2

extra 4
1
extra 3

extra 3
0

extra 1
0

mashadb 1
1
extra 3

mashadb 2
1
extra 1

NoteThe first sample is given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «a» (version 3) depends on are painted black.  The second sample is again given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «codehorses» (version 5) depends on are paint it black. Note that «extra 1» is chosen instead of «extra 3» since «mashadb 1» and all of its dependencies are ignored due to «mashadb 2».

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object C {
  type Proj = (String, Int)

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val projects: mutable.Map[Proj, Seq[Proj]] = mutable.Map()
    val n = sc.nextInt
    val myProject = readProject(sc)
    val myDeps = readDependencies(sc)
    for (_ <- 1 until n) {
      projects += (readProject(sc) -> readDependencies(sc))
    }

    val result: ArrayBuffer[Proj] = ArrayBuffer()
    addDeps(myDeps)
    println(result.size)
    result.sortBy(_._1).foreach(t => println(s"${t._1} ${t._2}"))

    def addDeps(deps: Seq[Proj]): Unit = {
      val goodDeps: mutable.Map[String, Int] = mutable.Map()
      for {
        dep <- deps
        if myProject._1 != dep._1
        if !result.exists(_._1 == dep._1)
        if !goodDeps.contains(dep._1) || goodDeps(dep._1) < dep._2
      } {
        goodDeps += dep
      }
      val seq = goodDeps.toSeq
      if (seq.nonEmpty) {
        result ++= seq
        addDeps(seq.flatMap(projects))
      }
    }
  }

  def readProject(sc: java.util.Scanner): Proj = (sc.next("\\S+"), sc.nextInt)

  def readDependencies(sc: java.util.Scanner): Seq[Proj] =
    for {
      _ <- 1 to sc.nextInt
    } yield readProject(sc)
}


As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.

The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).

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

object D {

  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 java.lang.Integer.parseInt(next)
  }

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

  def addEdge(edge: (Int, Int), graph: Array[List[Int]]): Array[List[Int]] = {
    graph(edge._1).add(edge._2)
    graph(edge._2).add(edge._1)
    return graph
  }

  def solve = {
    val n = nextInt
    val edges = new Array[(Int, Int)](n - 1)
    var graph = new Array[List[Int]](n)
    for (i <- 0 until n) {
      graph(i) = new ArrayList[Int]()
    }
    for (i <- 0 until n - 1) {
      edges(i) = (nextInt - 1, nextInt - 1)
      graph = addEdge(edges(i), graph)
    }
    var ans = Int.MinValue
    for (i <- 0 until n - 1) {
      val first = edges(i)._1
      val second = edges(i)._2
      val used = new Array[Boolean](n)
      val dist = new Array[Int](n)

      object Helper {
        def bfs(start: Int) = {
          val q: util.Queue[Int] = new util.LinkedList[Int]()
          q.add(start)
          dist(start) = 0
          while (!q.isEmpty) {
            val v = q.poll()
            used(v) = true
            for (i <- 0 until graph(v).size()) {
              val next: Int = graph(v).get(i)
              if (!used(next)) {
                dist(next) = dist(v) + 1
                q.add(next)
              }
            }
          }
        }

        def cleanUpWith(vert: Int) = {
          Arrays.fill(used, false)
          Arrays.fill(dist, -1)
          used(vert) = true
        }
      }

      var firstDiameter = 0
      Helper.cleanUpWith(first)
      Helper.bfs(second)
      val max1 = dist.zipWithIndex.max
      Helper.cleanUpWith(first)
      Helper.bfs(max1._2)
      firstDiameter = dist.max

      var secondDiameter = 0
      Helper.cleanUpWith(second)
      Helper.bfs(first)
      val max2 = dist.zipWithIndex.max
      Helper.cleanUpWith(second)
      Helper.bfs(max2._2)
      secondDiameter = dist.max

      ans = Math.max(ans, firstDiameter * secondDiameter)
    }
    out.println(ans)
  }

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


Ashish has an array $$$a$$$ of size $$$n$$$.A subsequence of $$$a$$$ is defined as a sequence that can be obtained from $$$a$$$ by deleting some elements (possibly none), without changing the order of the remaining elements.Consider a subsequence $$$s$$$ of $$$a$$$. He defines the cost of $$$s$$$ as the minimum between:   The maximum among all elements at odd indices of $$$s$$$.  The maximum among all elements at even indices of $$$s$$$. Note that the index of an element is its index in $$$s$$$, rather than its index in $$$a$$$. The positions are numbered from $$$1$$$. So, the cost of $$$s$$$ is equal to $$$min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$$$.For example, the cost of $$$\{7, 5, 6\}$$$ is $$$min( max(7, 6), max(5) ) = min(7, 5) = 5$$$.Help him find the minimum cost of a subsequence of size $$$k$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 2 \cdot 10^5$$$)  — the size of the array $$$a$$$ and the size of the subsequence. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$)  — the elements of the array $$$a$$$.

Output a single integer  — the minimum cost of a subsequence of size $$$k$$$.

NoteIn the first test, consider the subsequence $$$s$$$ = $$$\{1, 3\}$$$. Here the cost is equal to $$$min(max(1), max(3)) = 1$$$.In the second test, consider the subsequence $$$s$$$ = $$$\{1, 2, 4\}$$$. Here the cost is equal to $$$min(max(1, 4), max(2)) = 2$$$.In the fourth test, consider the subsequence $$$s$$$ = $$$\{3, 50, 2, 4\}$$$. Here the cost is equal to $$$min(max(3, 2), max(50, 4)) = 3$$$.

object D {

  import InOut._

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

    val n, k = nextInt
    val as = nextInts(n)

    def can2(limit: Long, isEven: Int): Boolean = {
      var i = 0
      var j = 0
      while (i < n && j < k) {
        if (as(i) > limit) {
          if (j % 2 == isEven) {
            j += 1
          }
        } else {
          j += 1
        }
        i += 1
      }
      j == k
    }

    def can(limit: Long): Boolean = {
      val c0 = can2(limit, 0)
      val c1 = can2(limit, 1)
//      println(limit, c0, c1)
      c0 || c1
    }

    @annotation.tailrec
    def binSearch(low: Long, hi: Long): Long = {
      if (hi < low) low
      else {
        val mid = (low + hi) / 2
        if (can(mid)) binSearch(low, mid - 1)
        else binSearch(mid + 1, hi)
      }
    }

    val res = binSearch(0, as.max)
    out.println(res)

    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
  }

}


Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \leq i_1 < i_2 < \ldots < i_k < m$$$ (possibly, empty), where $$$0 \leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \ldots, t$$$, or determine that he could have obtained this array without mistakes.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array Ildar obtained.

If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$ — the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \ldots, t$$$.

NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed.  $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$.  $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$.  $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$.  $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong.

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

  override def apply(io: IO): io.type = {
    val a = io.read[Vector[Long]]
    val valid = mutable.Set.empty[Long]

    @tailrec
    def findInvalidIndex(i: Int, currMax: Long): Option[Int] = {
      if (i == a.length) {
        None
      } else if (valid.contains(a(i))) {
        findInvalidIndex(i + 1, currMax)
      } else if (a(i) == currMax + 1) {
        valid += a(i)
        findInvalidIndex(i + 1, currMax + 1)
      } else {
        Some(i + 1)
      }
    }

    io.write(findInvalidIndex(i = 0, currMax = -1).getOrElse(-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 = this(new IO(System.in, System.out)).close()
}
/***********************************[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 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
      }
    }
  }
}


Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.

6

logic

codeforces

bca

aaaaaaaaaaa

adbaadabad

to

NoteIn the first test case, the required path corresponds to the picture:  In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.

object _1729C extends CodeForcesApp{
  import Math._
  override def solve(io: IO) = io.repeat() {
    val line = io.nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n - 1))
    var indexed = line.zipWithIndex
      .collect({ case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i + 1) })
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    io.print(cost, m).printLine().print(1, ans, n).printLine()
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): this.type = { out.print(xs.mkString(" ")); this }
  def printLine(xs: Any*): this.type = { if (xs.isEmpty) out.println() else xs.foreach(out.println); this }

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

object _1729C extends CodeForcesApp{
  import Math._
  override def solve(io: IO) = io.repeat() {
    val line = io.nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n - 1))
    var indexed = line.zipWithIndex
      .collect({ case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i + 1) })
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    io.printLine(
      s"$cost $m",
      s"1 $ans $n".replace("  ", " ")
    )
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solve(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
  def solve(io: IO): Any
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)

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

object _1729C extends CodeForcesAppMulti({io =>
  import Math._
  val line = io.nextLine().toSeq.map(_ - 'a' + 1)
  val n = line.length
  val (start, end) = (line(0), line(n-1))
  var indexed = line.zipWithIndex
    .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
    .drop(1).dropRight(1).sorted

  if (start > end) indexed = indexed.reverse
  val cost = (start - end).abs
  val m = indexed.length + 2
  val ans = indexed.map(_._2).mkString(" ")

  io.printLine(
    s"$cost $m",
    s"1 $ans $n".replace("  ", " ")
  )
})
/**************************** [Ignore Template Below] **************************************/
class CodeForcesApp(solution: IO => Any) {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solution(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
}
class CodeForcesAppMulti(solution: IO => Any) extends CodeForcesApp(solution) {
  override def run(io: IO) = try io.repeat()(solution(io)) finally io.close()
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }

  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)

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

object _1729C extends CodeForcesApp({io =>
  import Math._

  io.repeat() {
    val line = io.nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n-1))
    var indexed = line.zipWithIndex
      .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    io.printLine(
      s"$cost $m",
      s"1 $ans $n".replace("  ", " ")
    )
  }
})
/**************************** [Ignore Template Below] **************************************/
class CodeForcesApp(solution: IO => Any) {
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def run(io: IO): Unit = try solution(io) finally io.close()
  def main(args: Array[String]): Unit = run(new IO(in = System.in, out = System.out))
}
// Java I/O wrapper
import java.io._
class IO(in: BufferedReader, out: PrintWriter) extends AutoCloseable {
  def this(in: InputStream, out: OutputStream) = this(in = new BufferedReader(new InputStreamReader(in)), out = new PrintWriter(out))
  override def close() = out.close()
  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))
  // input utils
  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: Any)(res: => A): A = { printLine(query); out.flush(); res }
  //output utils
  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)
}

import scala.annotation.tailrec

object _1729C extends CodeForcesApp {
  import Math._

  override def solve() = repeat() {
    val line = nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n-1))
    var indexed = line.zipWithIndex
      .collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
      .drop(1).dropRight(1).sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    printLine(
      s"$cost $m",
      s"1 $ans $n".replace("  ", " ")
    )
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  private var in = new BufferedReader(new InputStreamReader(System.in))
  private var out = new PrintWriter(System.out)

  def setIO(inputFile: File, outputFile: File): Unit = {
    in = new BufferedReader(new FileReader(inputFile))
    out = new PrintWriter(new FileWriter(outputFile))
  }

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: String)(res: => A): A = {printLine(query); out.flush(); res}

  def print(xs: Any*): Unit = out.print(xs.mkString(" "))
  def printLine(xs: Any*): Unit = if (xs.isEmpty) out.println() else xs.foreach(out.println)
  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}

object _1729C extends CodeForcesApp {
  import Math._

  override def solve() = repeat() {
    val line = nextLine().toSeq.map(_ - 'a' + 1)
    val n = line.length
    val (start, end) = (line(0), line(n-1))
    var indexed = line.zipWithIndex.collect({case (x, i) if min(start, end) <= x && x <= max(start, end) => (x, i+1)})
      .drop(1).dropRight(1)
      .sorted

    if (start > end) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length + 2
    val ans = indexed.map(_._2).mkString(" ")

    out.println(s"$cost $m")
    out.println(s"1 $ans $n".replace("  ", " "))
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def illegal(msg: String = "can't happen") = throw new IllegalStateException(msg)

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}

object _1729C extends CodeForcesApp {
  import Math._

  override def solve() = repeat() {
    val line = nextLine().toSeq.map(_ - 'a' + 1)
    val (start, end) = (line.head, line.last)
    var indexed = line.zipWithIndex.collect({case (n, i) if min(start, end) <= n && n <= max(start, end) => (n, i+1)}).sorted
    if (end < start) indexed = indexed.reverse
    val cost = (start - end).abs
    val m = indexed.length
    val ans = indexed.map(_._2).mkString(" ")
    out.println(s"$cost $m")
    out.println(ans)
  }
}
/**************************** [Ignore Template Below] **************************************/
trait CodeForcesApp {
  import java.io._
  var in = new BufferedReader(new InputStreamReader(System.in))
  var out = new PrintWriter(System.out)

  val tokens = Iterator.continually(nextLine()).takeWhile(_ != null).flatMap(_.split(' '))

  def nextLine(): String = in.readLine()
  def nextStr(): String = tokens.next()
  def nextInt(): Int = nextStr().toInt
  def nextLong(): Long = nextStr().toLong
  def nextDouble(): Double = nextStr().toDouble
  def nextN[A](r: => A): Iterator[A] = Iterator.fill(nextInt())(r)
  def repeat[U](n: Int = nextInt())(f: => U): Unit = (1 to n).foreach(_ => f)
  def query[A](query: String, res: => A): A = {out.println(query); out.flush(); res}

  def debug(x: => Any): Unit = if (!sys.props.contains("ONLINE_JUDGE")) println(s">>> DEBUG: $x")
  def illegal(msg: String = "can't happen") = throw new IllegalStateException(msg)

  def main(args: Array[String]): Unit = try solve() finally out.flush()
  def solve(): Any
}


After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.

The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102).

Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles.

import scala.collection.mutable

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))
    def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(hh, mm) = readInt()
        val Array(h, d, c, n) = readInt().map(_.toFloat)

        var price = 0.0
        if (hh >= 20) price = Math.ceil(h / n) * c * 0.8
        else price = Math.min(Math.ceil(h / n) * c, Math.ceil((h + ((20 - hh - 1)*60 + 60 - mm)*d) / n) * c * 0.8)

        print("%.4f".format(price))

        /*val s = readString()
        val s1 = new mutable.HashSet[Char]()
        val s2 = new mutable.HashSet[Char]()
        val f1 = new Array[Int](s.length)
        val f2 = new Array[Int](s.length)

        for (i <- 0 until s.length) {
            s1 += s(i)
            f1(i) = s1.size
        }

        for (i <- s.length - 1 to 0 by -1) {
            s2 += s(i)
            f2(i) = s2.size
        }

        for (i <- 0 until s.length - 1)
            if (f1(i) == f2(i + 1) && f1(i) == 2) {
                print("Yes")
                return
            }
        print("No")*/

/*        val prime = Array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59)

        var Array(q) = readInt()
        while (q > 0) {
            var Array(l, r) = readInt()
            var result = 0
            if (l == 1) {
                l = 2
                result += 1
            }
            val maxb = (Math.log(r)/Math.log(2)).toInt
            for (i <- 2 to maxb if (prime.contains(i))) {
                var mina = Math.max(Math.pow(l, 1.0/i).ceil.toInt, 2)
                val maxa = Math.pow(r, 1.0/i).floor.toInt
                println(s"$i $mina $maxa ${maxa - mina + 1}")
                result += maxa - mina + 1
            }

            println(result)
            q -= 1
        }*/
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))
    def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(hh, mm) = readInt()
        val Array(h, d, c, n) = readInt().map(_.toFloat)

        var price = 0.0
        if (hh >= 20) price = Math.ceil(h / n) * c
        else price = Math.min(Math.ceil(h / n) * c, Math.ceil((h + ((20 - hh - 1)*60 + 60 - mm))*d / n) * c)

        print("%.4f".format(price))
    }
}

import scala.collection.mutable

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))
    def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(hh, mm) = readInt()
        val Array(h, d, c, n) = readInt().map(_.toFloat)

        var price = 0.0
        if (hh >= 20) price = Math.ceil(h / n) * c * 0.8
        else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)

        print("%.4f".format(price))

        /*val s = readString()
        val s1 = new mutable.HashSet[Char]()
        val s2 = new mutable.HashSet[Char]()
        val f1 = new Array[Int](s.length)
        val f2 = new Array[Int](s.length)

        for (i <- 0 until s.length) {
            s1 += s(i)
            f1(i) = s1.size
        }

        for (i <- s.length - 1 to 0 by -1) {
            s2 += s(i)
            f2(i) = s2.size
        }

        for (i <- 0 until s.length - 1)
            if (f1(i) == f2(i + 1) && f1(i) == 2) {
                print("Yes")
                return
            }
        print("No")*/

/*        val prime = Array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59)

        var Array(q) = readInt()
        while (q > 0) {
            var Array(l, r) = readInt()
            var result = 0
            if (l == 1) {
                l = 2
                result += 1
            }
            val maxb = (Math.log(r)/Math.log(2)).toInt
            for (i <- 2 to maxb if (prime.contains(i))) {
                var mina = Math.max(Math.pow(l, 1.0/i).ceil.toInt, 2)
                val maxa = Math.pow(r, 1.0/i).floor.toInt
                println(s"$i $mina $maxa ${maxa - mina + 1}")
                result += maxa - mina + 1
            }

            println(result)
            q -= 1
        }*/
    }
}

object objecta {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))
    def readInt()(implicit reader: BufferedReader): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(hh, mm) = readInt()
        val Array(h, d, c, n) = readInt().map(_.toFloat)

        var price = 0.0
        if (hh >= 20) price = Math.ceil(h / n) * c * 0.8
        else price = Math.min(Math.ceil(h / n) * c, Math.ceil(h + ((20 - hh - 1)*60 + 60 - mm)*d / n) * c * 0.8)

        print("%.4f".format(price))
    }
}


You are given a positive integer $$$n$$$ greater or equal to $$$2$$$. For every pair of integers $$$a$$$ and $$$b$$$ ($$$2 \le |a|, |b| \le n$$$), you can transform $$$a$$$ into $$$b$$$ if and only if there exists an integer $$$x$$$ such that $$$1 < |x|$$$ and ($$$a \cdot x = b$$$ or $$$b \cdot x = a$$$), where $$$|x|$$$ denotes the absolute value of $$$x$$$.After such a transformation, your score increases by $$$|x|$$$ points and you are not allowed to transform $$$a$$$ into $$$b$$$ nor $$$b$$$ into $$$a$$$ anymore.Initially, you have a score of $$$0$$$. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?

A single line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the given integer described above.

Print an only integer — the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print $$$0$$$.

NoteIn the first example, the transformations are $$$2 \rightarrow 4 \rightarrow (-2) \rightarrow (-4) \rightarrow 2$$$.In the third example, it is impossible to perform even a single transformation.

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 = ni()

    var ans = 0L
    2 until N foreach { d =>
      2 to N / d foreach { x =>
        ans += x * 4
      }
    }

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


As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.Elections are coming. You know the number of voters and the number of parties — $$$n$$$ and $$$m$$$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $$$i$$$-th voter $$$c_i$$$ bytecoins you can ask him to vote for any other party you choose.The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.

The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 3000$$$) — the number of voters and the number of parties respectively. Each of the following $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le m$$$, $$$1 \le c_i \le 10^9$$$) — the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision. The United Party of Berland has the index $$$1$$$.

Print a single number — the minimum number of bytecoins needed for The United Party of Berland to win the elections.

NoteIn the first sample, The United Party wins the elections even without buying extra votes.In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties $$$3$$$, $$$4$$$ and $$$5$$$ get one vote and party number $$$2$$$ gets no votes.In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party.

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 = {
    import java.util
    val N, M = ni()
    val (p, c) = na2(N)

    var vote1 = 0
    val V = Array.fill[java.util.ArrayList[Integer]](M)(new util.ArrayList())
    REP(N) { i =>
      if (p(i) == 1) vote1 += 1
      else V(p(i) - 1).add(c(i))
    }
    REP(M) { i =>
      import java.util.Collections
      Collections.sort(V(i))
    }

    val ans = map(N) { remain =>
      var res = 0L
      var cnt = 0
      var mx = 0
      val q = new java.util.PriorityQueue[Int]()
      REP(M) { m =>
        val v = V(m)
        val n = v.size()

        val del = if (n > remain) v.size - remain else 0
        REP(del) { k =>
          res += v.get(k)
          cnt += 1
        }
        REP(n) { k =>
          if (k >= del) q.add(v.get(k))
        }
        mx = max(mx, n - del)
      }

      if (vote1 + cnt <= mx) {
        REP(mx + 1 - vote1 - cnt) { _ =>
          res += q.poll()
        }
      }

      res
    }.min

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

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream
import scala.collection.mutable.PriorityQueue
import java.security.SecureRandom

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

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

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val n = line.int
    val m = line.int
    val vArr = new Array[(Int, Int)](n)
    val pArr = new Array[Int](m+1)
    var pQ = Array.fill[List[Int]](m+1)(List())
    (0 until n).foreach(x => {
      val vLine = readLine
      val p = vLine.int
      val money = vLine.int
      vArr(x) = (p, money)
      pArr(p) += 1
      pQ(p) ::= money
    })

    pQ = pQ.map(_.sorted)

    val from = if (m == 1) pArr(1) else pArr.drop(2).min+1
    val levels = (from to pArr.max+1)

    val variants = levels.map{ l =>
      debug("level=" + l)
      val parts = pArr.clone()
      val prices = pQ.clone
      var variant = 0l
      (2 to m).foreach{ pp =>
        while (parts(pp) >= l) {
          val vv = prices(pp).head;
          prices(pp) = prices(pp).tail
//          debug(s" take from $pp - $vv")
          parts(1) += 1
          parts(pp) -= 1
          variant += vv
        }
      }
      val toTakeFromLeft = if (parts(1) < l) l - parts(1) else 0
      var ll: List[(Int, Int)] = List()
      for(i <- 2 until prices.length) {
        prices(i).foreach(lp => ll ::= (lp, i) )
      }

      val left2 = ll.toArray.sorted.take(toTakeFromLeft)

//      val unsortedLeft = prices.zipWithIndex.drop(2).flatMap(x => x._1.map(y => (y, x._2)))
//      val left = unsortedLeft.sortBy(_._1).take(toTakeFromLeft)
      left2.foreach{ x =>
//        debug(s" take left from ${x._2} - ${x._1}")
        parts(1) += 1
        parts(x._2) -= 1
        variant += x._1
      }

      val maxLeft = if (m == 1) 0 else parts.drop(2).max
      if (maxLeft >= parts(1)) -1
      else variant

    }.filterNot(_ == -1)

    outLn(variants.min+"")

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

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

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

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

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

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

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

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

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

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

val sa1 = """
1 2
1 100
"""

val sa2 = """
5 5
2 100
3 200
4 300
5 400
5 900
""" //500

val sa3 = """
5 5
2 100
3 200
4 300
5 800
5 900
""" //600

val big = {
    var rr = "3000 3000\n"
    for (i <- 1 to 3000) {
      rr += "3000 " + new SecureRandom().nextInt().abs + "\n"
    }
    rr
  }

}

}

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 = {
    import java.util
    val N, M = ni()
    val (p, c) = na2(N)

    var vote1 = 0
    val V = Array.fill[java.util.ArrayList[Integer]](M)(new util.ArrayList())
    REP(N) { i =>
      if (p(i) == 1) vote1 += 1
      else V(p(i) - 1).add(c(i))
    }
    REP(M) { i =>
      import java.util.Collections
      Collections.sort(V(i))
    }

    val ans = map(N) { remain =>
      var res = 0
      var cnt = 0
      var mx = 0
      val q = new java.util.PriorityQueue[Int]()
      REP(M) { m =>
        val v = V(m)
        val n = v.size()

        val del = if (n > remain) v.size - remain else 0
        REP(del) { k =>
          res += v.get(k)
          cnt += 1
        }
        REP(n) { k =>
          if (k >= del) q.add(v.get(k))
        }
        mx = max(mx, n - del)
      }

      if (vote1 + cnt <= mx) {
        REP(mx + 1 - vote1 - cnt) { _ =>
          res += q.poll()
        }
      }

      res
    }.min

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

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

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

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

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val line = readLine
    val n = line.int
    val m = line.int
    val vArr = new Array[(Int, Int)](n)
    val pArr = new Array[Int](m+1)
    val pQ = Array.fill[List[Int]](m+1)(List())
    (0 until n).foreach(x => {
      val vLine = readLine
      val p = vLine.int
      val money = vLine.int
      vArr(x) = (p, money)
      pArr(p) += 1
//      if (pQ(p) == null) {
//        pQ(p) = PriorityQueue()(Ordering.Int.reverse)
//      }
//      pQ(p).enqueue(money)
      pQ(p) ::= money
    })

    pQ.map(_.sorted)

    val levels = (pArr.drop(2).min+1 to pArr.max+1)

    val variants = levels.map{ l =>
      debug("level=" + l)
      val parts = pArr.clone()
      val prices = pQ.clone
      var variant = 0
      (2 to m).foreach{ pp =>
        while (parts(pp) >= l) {
          val vv = prices(pp).head;
          prices(pp) = prices(pp).tail
          debug(s" take from $pp - $vv")
          parts(1) += 1
          parts(pp) -= 1
          variant += vv
        }
      }
      val toTakeFromLeft = if (parts(1) < l) l - parts(1) else 0
      val unsortedLeft = prices.zipWithIndex.drop(2).flatMap(x => x._1.map(y => (y, x._2)))
      val left = unsortedLeft.sortBy(_._1).take(toTakeFromLeft)
      left.foreach{ x =>
        debug(s" take left from ${x._2} - ${x._1}")
        parts(1) += 1
        parts(x._2) -= 1
        variant += x._1
      }

      val maxLeft = parts.drop(2).max
      if (maxLeft >= parts(1)) -1
      else variant

    }.filterNot(_ == -1)

    outLn(variants.min)

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

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

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

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

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

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

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

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

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

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

val sa1 = """
1 2
1 100
"""

val sa2 = """
5 5
2 100
3 200
4 300
5 400
5 900
""" //500

val sa3 = """
5 5
2 100
3 200
4 300
5 800
5 900
""" //600
}

}


There is a $$$n \times m$$$ grid. You are standing at cell $$$(1, 1)$$$ and your goal is to finish at cell $$$(n, m)$$$.You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell $$$(x, y)$$$. You can:   move right to the cell $$$(x, y + 1)$$$ — it costs $$$x$$$ burles;  move down to the cell $$$(x + 1, y)$$$ — it costs $$$y$$$ burles. Can you reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first and only line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n, m \le 100$$$; $$$0 \le k \le 10^4$$$) — the sizes of grid and the exact amount of money you need to spend.

For each test case, if you can reach cell $$$(n, m)$$$ spending exactly $$$k$$$ burles, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, you are already in the final cell, so you spend $$$0$$$ burles.In the second, third and fourth test cases, there are two paths from $$$(1, 1)$$$ to $$$(2, 2)$$$: $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(1, 2)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ or $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$. Both costs $$$1 + 2 = 3$$$ burles, so it's the only amount of money you can spend.In the fifth test case, there is the only way from $$$(1, 1)$$$ to $$$(1, 4)$$$ and it costs $$$1 + 1 + 1 = 3$$$ burles.

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

object Main extends App {
  val t = StdIn.readInt()
  for (i <- 0 until t) {
    val values = StdIn.readLine().split(" ").map(_.toInt)
    val n = min(values(0), values(1))
    val m = max(values(1), values(0))
    val t = values(2)

    println(if (n * m - 1 == t) "YES" else "NO")
  }
}

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

object Main extends App {
  val t = StdIn.readInt()
  for (i <- 0 until t) {
    val values = StdIn.readLine().split(" ").map(_.toInt)
    val n = min(values(0), values(1))
    val m = max(values(1), values(0))
    val t = values(2)

    println(if (n * (n - 1) + m - 1 == t) "YES" else "NO")
  }
}


This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.

In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.

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

import scala.annotation.tailrec

object D2 {
  def solve(in: Input, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val arr = Array.fill(n)(in.nextInt())
    java.util.Arrays.sort(arr)
    val arr2 = new Array[Int](n)
    var trg = 1
    var src = 0
    while (trg < n) {
      arr2(trg) = arr(src)
      trg += 2
      src += 1
    }
    trg = 0
    while (trg < n) {
      arr2(trg) = arr(src)
      trg += 2
      src += 1
    }

    val result = (1 to n - 2).count(i => arr2(i) < arr2(i - 1) && arr2(i) < arr2(i + 1))
    out.println(result)
    out.println(arr2.mkString(" "))
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("5\n1 2 3 4 5", "2\n3 1 4 2 5 ", "Sample"),
    ("7\n1 3 2 2 4 5 4", "3\n3 1 4 2 4 2 5", "Sample 2"),
    ("1\n1", "0\n1", "Size 1"),
    ("2\n1 2", "0\n2 1", "Size 2"),
    ("3\n1 2 3", "1\n2 1 3", "Size 3"),
    ("4\n1 2 3 4", "1\n3 1 4 2", "Size 4"),
    ("5\n1 1 1 2 2", "1\n1 1 2 1 2", "Size 5, v1"),
    ("5\n1 1 2 2 2", "2\n2 1 2 1 2", "Size 5, v2"),
  )

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

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