You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \le x \le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print "-1" (without quotes).

The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sequence itself.

Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print "-1" (without quotes).

NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number.

object Problem_977C {
  // Less or Equal
  // The first line of the input contains integer numbers n and k (1≤n≤2⋅105, 0≤k≤n).
  // The second line of the input contains n integer numbers a1,a2,…,an (1≤ai≤109) — the sequence itself.

  def main(args: Array[String]) {
    val scan = scala.io.StdIn

    //Get inputs
    val inputs: Array[Int] = scan.readLine().split(" ").map(_.toInt)
    val targetArr: Array[Int] = scan.readLine().split(" ").map(_.toInt)
    val n= inputs(0)
    val k= inputs(1)

    if (k == n) {
        println(targetArr.max)
    }
    else if (k == 0) {
      if (targetArr.min == 1)
        println("-1")
      else
        println(targetArr.min - 1)
    }
    else{
      val sortedArr = targetArr.sorted
      if(sortedArr(k-1) == sortedArr(k))
        println("-1")
      else
        println(sortedArr(k-1))
    }
  }

}

object 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, K = ni()
    val A = na(N)
    radixSort(A)

    val x = if (K == 0) 1 else A(K - 1)
    val x1 = if (K == N) A(K - 1) + 1 else A(K)
    if (x == x1) out.println(-1)
    else out.println(x)
  }

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

  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(f1: Array[Int], n: Int): Array[Int] = {
    var f = f1
    var to = Array.ofDim[Int](n)

    val b = Array.ofDim[Int](65537)
    rep(n){ i => b(1 + (f(i) & 0xffff)) += 1 }
    rep(65536, 1){ i => b(i) += b(i - 1) }
    rep(n){ i =>
      val j = f(i) & 0xffff
      to(b(j)) = f(i)
      b(j) += 1
    }
    val temp = f
    f = to
    to = temp

    java.util.Arrays.fill(b, 0)
    rep(n){ i => b(1 + (f(i) >>> 16)) += 1 }
    rep(65536, 1){ i => b(i) += b(i - 1) }
    rep(n){ i =>
      val j = f(i) >>> 16
      to(b(j)) = f(i)
      b(j) += 1
    }
    to
  }

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object 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, K = ni()
    val A = na(N)

    def cntLe(x: Int): Int = {
      var res = 0
      rep(N) { i =>
        if (A(i) <= x) res += 1
      }
      res
    }

    def f(x: Int): Boolean = {
      cntLe(x) >= K
    }

    var l = 0
    var h = 1e9.toInt + 1
    while(h - l > 1) {
      val m = (h + l) / 2
      if (f(m)) h = m
      else l = m
    }

    val x = h
    if (cntLe(x) == K) out.println(x)
    else out.println(-1)
  }

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

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.PriorityQueue

import scala.collection.mutable

object CE976B extends App {
  val arrayLine = readLine().split(" ")
  val n = arrayLine(0).toInt
  val k = arrayLine(1).toInt
  val string = readLine();
  val numMap = string.split(" ").map(_.toInt).sorted
  if (k == 0)
    if (numMap(0) > 1)
      print(numMap(0) - 1)
    else
      print(-1)
  else if (k == n)
    print(numMap(k - 1))
  else if (numMap(k - 1) == numMap(k))
    print(-1)
  else
    print(numMap(k - 1))
}

import scala.io.StdIn

object LessOrEqualTest {
  def main(args: Array[String]):Unit ={
//    val number = StdIn.readInt()
//    val lessOrEqual = new LessOrEqual
//    val isLessOrEqual = lessOrEqual.process(number )
//    print(isLessOrEqual)
    val nk = StdIn.readLine().split(" ").map(_.toInt)
    val elements = StdIn.readLine().split(" ").map(_.toInt)
    val elementsSorted = elements.sortWith(_ < _)
    val k = nk(1)
    val n = nk(0)

    val res = proc(k,n,elementsSorted)

    print(res)
  }

  def proc(k: Int, tam: Int, elements:Array[Int]): String ={
    if( k > tam ) return "-1"
    if (k == tam) return elements(k-1)+" "
    if(k < tam){

      if (k == 0 ){
        if (elements(0) > 1){
          return elements( 0 ) - 1+""
        }
        else return "-1"
      }

      if ( elements( k - 1 ) < elements( k ))
        {return elements(k - 1)+ ""}
    }
    return "-1"
  }
}

object C732 extends App {
  def parseIn(): (Int, Int, Array[Int]) = {
    val splitted = readLine.split(" ").map(_.toInt)
    (splitted(0), splitted(1), readLine.split(" ").map(_.toInt))
  }

  def solve(k: Int, data: Array[Int]): Int = {
    if (k == n) data.reverse.head
    else if (k != 0 & n > 1) {
      if (data(k - 1) != data(k)) data(k - 1)
      else -1
    } else {
      if (data.head > 1) {
        if (k == 0 & data.head == 1) -1
        else if (k == 0) data.head - 1
        else data.head
      } else -1
    }
  }

  val (n, k, data) = parseIn
  println(solve(k, data.sortWith(_ < _)))
}

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

  override def apply(io: IO): io.type = {
    val n, k = io.read[Int]
    val nums = 1 +: io.read[Vector, Int](n).sorted
    val ans = if (k == n || nums(k) != nums(k+1)) {
      nums(k)
    } else {
      -1
    }
    io.write(ans)
  }
}
/****************************[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
      }
    }
  }
}

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

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

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

    def main(args: Array[String]): Unit = {
        val Array(n, k) = readArray().map(_.toInt)
        var a = readArray().map(_.toInt)
        a = a.sortWith(_ < _)
        if (k == n) {
            print(a(n - 1))
            return
        }

        if (k == 0) {
            if (a(0) - 1 > 0) print(a(0) - 1)
            else print(-1)
            return
        }

        if (a(k - 1) == a(k)) {
            print(-1)
            return
        }
        print(a(k - 1))
    }
}

object Problem_977C {
  // Less or Equal
  // The first line of the input contains integer numbers n and k (1≤n≤2⋅105, 0≤k≤n).
  // The second line of the input contains n integer numbers a1,a2,…,an (1≤ai≤109) — the sequence itself.

  def main(args: Array[String]) {
    val scan = scala.io.StdIn

    //Get inputs
    val inputs: Array[Int] = scan.readLine().split(" ").map(_.toInt)
    val targetArr: Array[Int] = scan.readLine().split(" ").map(_.toInt)
    val n= inputs(0)
    val k= inputs(1)

    if (k == n) {
      if (targetArr.max == Math.pow(10, 9))
        println("-1")
      else
        println(targetArr.max + 1)
    }
    else if (k == 0) {
      if (targetArr.min == 1)
        println("-1")
      else
        println(targetArr.min - 1)
    }
    else{
      val sortedArr = targetArr.sorted
      if(sortedArr(k-1) == sortedArr(k))
        println("-1")
      else
        println(sortedArr(k-1))
    }
  }

}

object Problem_977C {
  // Less or Equal
  // The first line of the input contains integer numbers n and k (1≤n≤2⋅105, 0≤k≤n).
  // The second line of the input contains n integer numbers a1,a2,…,an (1≤ai≤109) — the sequence itself.

  def main(args: Array[String]) {
    val scan = scala.io.StdIn

    //Get inputs
    val inputs: Array[Int] = scan.readLine().split(" ").map(_.toInt)
    val targetArr: Array[Int] = scan.readLine().split(" ").map(_.toInt)
    val n= inputs(0)
    val k= inputs(1)

    if (k == n) {
      if (targetArr.max == Math.pow(10, 9))
        println("-1")
      else
        println(targetArr.max + 1)
    }
    else if (k == 0) {
      if (targetArr.min == 0)
        println("-1")
      else
        println(targetArr.min - 1)
    }
    else{
      val sortedArr = targetArr.sorted
      if(sortedArr(k-1) == sortedArr(k))
        println("-1")
      else
        println(sortedArr(k-1))
    }
  }

}

object 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, K = ni()
    val A = na(N)

    val ms = A.min
    if (K == 0 && ms == 1) {
      out.println(-1)
    } else if (K == 0 && ms > 1) {
      out.println(1)
    } else if (K == N) {
      out.println(A(N - 1))
    } else {
      def cnt(x: Int) = {
        var s = 0
        rep(N) { i =>
          if (A(i) <= x) s += 1
        }
        s
      }

      var l = -1
      var h = N
      while(h - l > 1) {
        val m = (l + h) / 2
        if (cnt(m) < K) l = m
        else h = m
      }

      val x = h
      val ans = if (cnt(x) != K) -1 else x
      out.println(ans)
    }
  }

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

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object 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, K = ni()
    val A = na(N)

    def cnt(x: Int) = {
      var s = 0
      rep(N) { i =>
        if (A(i) <= x) s += 1
      }
      s
    }

    if (K == 0) {
      if (cnt(1) > 0) {
        out.println(-1)
      } else {
        out.println(1)
      }
    } else {
      var l = -1
      var h = N
      while(h - l > 1) {
        val m = (l + h) / 2
        if (cnt(m) < K) l = m
        else h = m
      }

      val x = h
      val ans = if (cnt(x) != K) -1 else x
      out.println(ans)
    }
  }

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

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object 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, K = ni()
    val A = na(N)

    def cnt(x: Int) = {
      var s = 0
      rep(N) { i =>
        if (A(i) <= x) s += 1
      }
      s
    }

    if (K == 0) {
      if (cnt(1) > 1) {
        out.println(-1)
      } else {
        out.println(1)
      }
    } else if (K == N) {
      out.println(A.max)
    } else {
      var l = -1
      var h = N
      while(h - l > 1) {
        val m = (l + h) / 2
        if (cnt(m) < K) l = m
        else h = m
      }

      val x = h
      val ans = if (cnt(x) != K) -1 else x
      out.println(ans)
    }
  }

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

  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): Array[Int] = map(n)(_ => ni())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.PriorityQueue

import scala.collection.mutable

object CE976B extends App {
  val arrayLine = readLine().split(" ")
  val n = arrayLine(0).toInt
  val k = arrayLine(1).toInt
  val string = readLine();
  val numMap = string.split(" ").map(_.toInt).sorted
  if (k == 0)
    print(numMap(0) - 1)
  else if (k == n)
    print(numMap(k - 1))
  else if (numMap(k - 1) == numMap(k))
    print(-1)
  else
    print(numMap(k - 1))
}

import scala.io.StdIn

object LessOrEqualTest {
  def main(args: Array[String]):Unit ={
//    val number = StdIn.readInt()
//    val lessOrEqual = new LessOrEqual
//    val isLessOrEqual = lessOrEqual.process(number )
//    print(isLessOrEqual)
    val nk = StdIn.readLine().split(" ").map(_.toInt)
    val elements = StdIn.readLine().split(" ").map(_.toInt)
    val elementsSorted = elements.sortWith(_ < _)
    val k = nk(1)
    if(k > 0)
      if ( elements( k - 1 ) < elements( k ))
        print( elementsSorted(k - 1) )

    print("-1")

  }
}

import scala.io.StdIn

object LessOrEqualTest {
  def main(args: Array[String]):Unit ={
//    val number = StdIn.readInt()
//    val lessOrEqual = new LessOrEqual
//    val isLessOrEqual = lessOrEqual.process(number )
//    print(isLessOrEqual)
    val nk = StdIn.readLine().split(" ").map(_.toInt)
    val elements = StdIn.readLine().split(" ").map(_.toInt)
    val elementsSorted = elements.sortWith(_ < _)
    val k = nk(1)
    if(k > 0)
      if ( elements( k - 1 ) < elements( k ))
        print( elementsSorted(k - 1) )
      else print("-1")
    else print("-1")

  }
}

import scala.io.StdIn

object LessOrEqualTest {
  def main(args: Array[String]):Unit ={
//    val number = StdIn.readInt()
//    val lessOrEqual = new LessOrEqual
//    val isLessOrEqual = lessOrEqual.process(number )
//    print(isLessOrEqual)
    val nk = StdIn.readLine().split(" ").map(_.toInt)
    val elements = StdIn.readLine().split(" ").map(_.toInt)
    val elementsSorted = elements.sortWith(_ < _)
    val k = nk(1)
    if(k > 0)
      if ( elements( k - 1 ) < elements( k ))
        print( elementsSorted(k - 1) )
      else print("-1")
    print("-1")

  }
}

object C732 extends App {
  def parseIn(): (Int, Int, Array[Int]) = {
    val splitted = readLine.split(" ").map(_.toInt)
    (splitted(0), splitted(1), readLine.split(" ").map(_.toInt))
  }

  def solve(k: Int, data: Array[Int]): Int = {
    if (k != 0) {
      if (data(k - 1) != data(k)) data(k - 1)
      else -1
    } else -1
  }

  val (n, k, data) = parseIn
  println(solve(k, data.sortWith(_ < _)))
}


Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:   Tetrahedron. Tetrahedron has 4 triangular faces.  Cube. Cube has 6 square faces.  Octahedron. Octahedron has 8 triangular faces.  Dodecahedron. Dodecahedron has 12 pentagonal faces.  Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below:  Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:   "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.  "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.  "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.  "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.  "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.

Output one number — the total number of faces in all the polyhedrons in Anton's collection.

4
Icosahedron
Cube
Tetrahedron
Dodecahedron

NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.

object tanya extends App{
var a = readInt
var sum = 0
for(i <- 0 to a){
    var str = readLine
    if(str == "Tetrahedron"){
        sum = sum + 4
    }else if(str == "Cube"){
        sum = sum + 6
    }else if(str == "Octahedron"){
        sum = sum + 8
    }else if(str == "Dodecahedron"){
        sum = sum + 12
    }else if(str == "Icosahedron"){
        sum = sum + 20
    }
}
println(sum)
}

import java.util.Scanner

import scala.collection.immutable.HashMap

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/7018
  */

object A extends App {

  val sc = new Scanner(System.in)

  val sides = HashMap[String, Int](
    "Tetrahedron" -> 4,
    "Cube" -> 6,
    "Octahedron" -> 8,
    "Dodecahedron" -> 12,
    "Icosahedron" -> 20
  )

  val n = sc.nextInt()
  var total = 0
  (1 to n) foreach { _ =>
    total += sides(sc.next())
  }
  println(total)
}

object A785 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    var res = 0L
    val map = Map("Tetrahedron"->4, "Cube"->6, "Octahedron"->8, "Dodecahedron"->12, "Icosahedron"->20)
    for(_ <- 1 to n) {
      val input = read
      res += map(input)
    }
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import io.StdIn._
object AntonAndHydrones {

  def main(args: Array[String]): Unit = {
    val number = readInt()
    var sum = 0
    val result = for(i <- 1 to number) yield{
      var line = readLine()
      var lineValue = line match {
        case "Tetrahedron" => 4
        case "Cube" => 6
        case "Octahedron" => 8
        case "Dodecahedron" => 12
        case "Icosahedron" => 20
      }
      sum += lineValue
    }
    println(sum)
  }

}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val polygons = read[Seq[String]]

    val faces = polygons sumWith {
      case "Tetrahedron" => 4
      case "Cube" => 6
      case "Octahedron" => 8
      case "Dodecahedron" => 12
      case "Icosahedron" => 20
    }

    write(faces)
  }
}
/****************************[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, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = 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])
    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 testBit(i: Int): Boolean = ((x >> i) & 1) == 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 testBit(i: Int): Boolean = ((x >> i) & 1) == 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
      }
    }
  }
}

import scala.io.StdIn

object TaskA {

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

    def f(): Int = {
      StdIn.readLine() match {
      case "Tetrahedron" => 4
      case "Cube" => 6
      case "Octahedron" => 8
      case "Dodecahedron" => 12
      case "Icosahedron" => 20
      }
    }

    println((1 to n map (_ => f())).sum)
  }

}

import scala.io.StdIn

object Codeforces785A extends App {
  var n = StdIn.readLine().toInt
  var s = 0
  while (n > 0) {
    n -= 1
    val p = StdIn.readLine()
    if (p == "Tetrahedron") s += 4
    if (p == "Cube") s += 6
    if (p == "Octahedron") s += 8
    if (p == "Dodecahedron") s += 12
    if (p == "Icosahedron") s += 20
  }
  print(s)
}

import scala.io.StdIn._

object Main2 extends App {
  val figureNumber = readInt()
  val res = 0.until(figureNumber).map(_ => readLine()).map {
    case "Tetrahedron" => 4
    case "Cube" => 6
    case "Octahedron" => 8
    case "Dodecahedron" => 12
    case "Icosahedron" => 20
  }.sum
  println(res)
}

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemE extends App {
    import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer

  override def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null
    val out = new PrintWriter(System.out)

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

    def nextInt: Int = next.toInt

    val n = nextInt

    var result = 0
    for (i <- 1 to n) {
      result += (next match {
        case "Tetrahedron" => 4
        case "Cube" => 6
        case "Octahedron" => 8
        case "Dodecahedron" => 12
        case "Icosahedron" => 20
      })
    }
    println(result)
  }
}

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

import scala.language.postfixOps

object TaskA extends App {
  val ir = new InputReader(System.in)
  val n = ir.nextInt

  val m = Map("Tetrahedron" -> 4, "Cube" -> 6, "Octahedron" -> 8, "Dodecahedron" -> 12, "Icosahedron" -> 20)

  println(1 to n map { _ => ir.nextString } map m sum)
}

class InputReader(val stream: InputStream) {
  val reader = new BufferedReader(new InputStreamReader(stream))
  var stt: StringTokenizer = _

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

  def nextInt: Int = nextString.toInt
}

import scala.io.StdIn._

object Solution {

	var n = readLine.toInt
    var shapes = Array.fill[String](n)(null)
    for(i <- 0 until n) shapes(i) = readLine

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

		var ret = 0

        for(i <- 0 until n) {
            var sides = shapes(i) match {
                case "Tetrahedron" => 4
				case "Cube" => 6
				case "Octahedron" => 8
				case "Dodecahedron" => 12
				case "Icosahedron" => 20
            }
			ret += sides
        }

		println(ret)
	}

}

/**
  * Created by ruslan on 3/4/17.
  */
object ProblemE extends App {
    import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer

  override def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null
    val out = new PrintWriter(System.out)

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

    def nextInt: Int = next.toInt

    val n = nextInt

    var result = 0
    for (i <- 1 to n) {
      result += (next match {
        case "Tetrahedron" => 4
        case "Cube" => 4
        case "Octahedron" => 8
        case "Dodecahedron" => 12
        case "Icosahedron" => 20
      })
    }
    println(result)
  }
}


There are $$$n$$$ people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The value of the line is the sum of each person's count.For example, in the arrangement LRRLL, where L stands for a person looking left and R stands for a person looking right, the counts for each person are $$$[0, 3, 2, 3, 4]$$$, and the value is $$$0+3+2+3+4=12$$$.You are given the initial arrangement of people in the line. For each $$$k$$$ from $$$1$$$ to $$$n$$$, determine the maximum value of the line if you can change the direction of at most $$$k$$$ people.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the line. The following line contains a string consisting of $$$n$$$ characters, each of which is either L or R, representing a person facing left or right, respectively — the description of the line. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$. Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

For each test case, output $$$n$$$ space-separated non-negative integers — the maximum value of the line if you can change the direction of at most $$$k$$$ people for each $$$k$$$ from $$$1$$$ to $$$n$$$, inclusive.

6

3

LLR

5

LRRLL

1

L

12

LRRRLLLRLLRL

10

LLLLLRRRRR

9

LRLRLRLRL

NoteIn the first test case:   $$$k=1$$$: change the direction of $$$1$$$ person to make the line RLR. The total value is $$$2+1+0=3$$$.  $$$k=2$$$: change the direction of $$$2$$$ people to make the line RLL. The total value is $$$2+1+2=5$$$.  $$$k=3$$$: change the direction of $$$2$$$ people to make the line RLL. The total value is $$$2+1+2=5$$$. Note that you have to change the direction of at most $$$k$$$ people. In the second test case, it is optimal to only change the direction of the first person for all $$$k$$$ from $$$1$$$ to $$$5$$$ (that is, make the line RRRLL).

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

  override def solve(io: IO) = io.repeat {
    val (n, s) = io.read[(Int, String)]
    val score = (s.zipWithIndex map {
      case ('L', i) => i.toLong
      case ('R', i) => (n-i-1).toLong
      case _ => 0L
    }).sum

    val ans = (s.zipWithIndex map {
      case ('L', i) => (i max (n - i - 1)) - i.toLong
      case ('R', i) => (i max (n - i - 1)) - (n - i - 1).toLong
      case _ => 0L
    }).sorted(desc[Long])
      .scanLeft(score)({case (x, y) => x + y})
      .tail

    io.writeAll(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence.

The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109).

Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r].

NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}.

import java.util._;

object Solution {
    def main(args : Array[String]) = {
        val sc = new Scanner(System.in)
        val n = sc.nextInt()
        val st = new Stack[Integer]()
        val vals = new Array[Integer](n)
        var ans = 0
        for(i <- 0 until n) {
            vals(i) = sc.nextInt()
            while(!st.empty() && st.peek() < vals(i))
                ans = Math.max(ans, st.pop() ^ vals(i))
            st.push(vals(i))
        }
        st.clear()
        for(i <- n - 1 to 0 by -1) {
            while(!st.empty() && st.peek() < vals(i))
                ans = Math.max(ans, st.pop() ^ vals(i))
            st.push(vals(i))
        }
        println(ans)
    }
}


Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?The cost of sending the message is the sum of the costs of sending every word in it.

The first line of input contains integers n, k and m (1 ≤ k ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively. The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct. The third line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) where ai is the cost of sending the i-th word. The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 ≤ x ≤ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group. The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.

The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.

5 4 4
i loser am the second
100 1 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

5 4 4
i loser am the second
100 20 1 5 10
1 1
1 3
2 2 5
1 4
i am the second

NoteIn the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, k, m = r.read[Int]

    import collection.mutable.{ ArrayBuffer, HashMap, HashSet }
    var ws = new HashMap[String, Int]()

    for (i <- 0 to n - 1) {
      ws(r.read[String]) = i
    }

    val cs = r.read[Array[Long]](n)
    var gs = ArrayBuffer.fill(k)(Long.MaxValue)
    var gs2 = ArrayBuffer.fill(n)(0)

    for (i <- 0 to k - 1) {
      val s = r.read[Int]

      for (_ <- 1 to s) {
        val e = r.read[Int] - 1

        gs(i) = math.min(gs(i), cs(e))
        gs2(e) = i
      }
    }

    val ws2 = r.read[Array[String]](m)
    println(ws2.map{ w => gs(gs2(ws(w))) }.sum)
  }
}

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

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val int: Read[Int] = new Read(_.tokenizer.next.toInt)
    implicit val long: Read[Long] = new Read(_.tokenizer.next.toLong)
    implicit val double: Read[Double] = new Read(_.tokenizer.next.toDouble)
    implicit val string: Read[String] = new Read(_.tokenizer.next)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
}

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

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

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

    def main(args: Array[String]): Unit = {
        val Array(n, k, m) = readArray().map(_.toInt)
        val _s = readArray()
        var s = new Array[(String, Int)](n)
        for (i <- 0 until n) s(i) = ((_s(i), i))
        val a = readArray().map(_.toInt)
        var f = new Array[Array[Int]](k)
        val g = new mutable.HashMap[Int, Int]()

        for (i <- 0 until k) {
            val x = readArray().map(_.toInt)
            f(i) = new Array(x(0))
            for (j <- 0 until x(0)) {
                f(i)(j) = x(j + 1) - 1
                g += x(j + 1) - 1 -> i
            }
        }

        val _s2 = readArray()
        var s2 = new Array[(String, Int)](m)
        for (i <- 0 until m) s2(i) = ((_s2(i), i))

        var (x, y) = (0, 0)
        val index = new Array[Int](k)
        s = s.sortWith(_._1 < _._1)
        s2 = s2.sortWith(_._1 < _._1)
        f = f.map(_.sortWith(a(_) < a(_)))

        var res = 0L
        while (x < s.size && y < s2.size) {
            if (s(x)._1 == s2(y)._1) {
                val id = s(x)._2
                res += a(f(g(id))(0))
                index(g(id)) += 1

                y += 1
            } else x += 1
        }

        print(res)
    }
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, k, m = r.read[Int]

    import collection.mutable.{ ArrayBuffer, HashMap, HashSet }
    var ws = new HashMap[String, Int]()

    for (i <- 0 to n - 1) {
      ws(r.read[String]) = i
    }

    val cs = r.read[Array[Int]](n)
    var gs = ArrayBuffer.fill(k)(Int.MaxValue)
    var gs2 = ArrayBuffer.fill(n)(0)

    for (i <- 0 to k - 1) {
      val s = r.read[Int]

      for (_ <- 1 to s) {
        val e = r.read[Int] - 1

        gs(i) = math.min(gs(i), cs(e))
        gs2(e) = i
      }
    }

    val ws2 = r.read[Array[String]](m)
    println(ws2.map{ w => gs(gs2(ws(w))) }.sum)
  }
}

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

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val int: Read[Int] = new Read(_.tokenizer.next.toInt)
    implicit val long: Read[Long] = new Read(_.tokenizer.next.toLong)
    implicit val double: Read[Double] = new Read(_.tokenizer.next.toDouble)
    implicit val string: Read[String] = new Read(_.tokenizer.next)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
}

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

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

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

    def main(args: Array[String]): Unit = {
        val Array(n, k, m) = readArray().map(_.toInt)
        val _s = readArray()
        var s = new Array[(String, Int)](n)
        for (i <- 0 until n) s(i) = ((_s(i), i))
        val a = readArray().map(_.toInt)
        var f = new Array[Array[Int]](k)
        val g = new mutable.HashMap[Int, Int]()

        for (i <- 0 until k) {
            val x = readArray().map(_.toInt)
            f(i) = new Array(x(0))
            for (j <- 0 until x(0)) {
                f(i)(j) = x(j + 1) - 1
                g += x(j + 1) - 1 -> i
            }
        }

        val _s2 = readArray()
        var s2 = new Array[(String, Int)](m)
        for (i <- 0 until m) s2(i) = ((_s2(i), i))

        var (x, y) = (0, 0)
        val index = new Array[Int](k)
        s = s.sortWith(_._1 < _._1)
        s2 = s2.sortWith(_._1 < _._1)
        f = f.map(_.sortWith(a(_) < a(_)))

        var res = 0
        while (x < s.size && y < s2.size) {
            if (s(x)._1 == s2(y)._1) {
                val id = s(x)._2
                res += a(f(g(id))(0))
                index(g(id)) += 1

                y += 1
            } else x += 1
        }

        print(res)
    }
}

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

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

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

    def main(args: Array[String]): Unit = {
        val Array(n, k, m) = readArray().map(_.toInt)
        val s = readArray()
        val a = readArray().map(_.toInt)
        var f = new Array[Array[Int]](k)
        val g = new mutable.HashMap[Int, Int]()

        for (i <- 0 until k) {
            val x = readArray().map(_.toInt)
            f(i) = new Array(x(0))
            for (j <- 0 until x(0)) {
                f(i)(j) = x(j + 1) - 1
                g += x(j + 1) - 1 -> i
            }
        }

        val s2 = readArray()

        var (x, y) = (0, 0)
        val index = new Array[Int](k)
        f = f.map(_.sortWith(a(_) < a(_)))

        var res = 0
        while (x < s.size && y < s2.size) {
            if (s(x) == s2(y)) {
                res += a(f(g(x))(index(g(x))))
                index(g(x)) += 1

                x += 1
                y += 1
            } else x += 1
        }

        print(res)
    }
}

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

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

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

    def main(args: Array[String]): Unit = {
        val Array(n, k, m) = readArray().map(_.toInt)
        val _s = readArray()
        var s = new Array[(String, Int)](n)
        for (i <- 0 until n) s(i) = ((_s(i), i))
        val a = readArray().map(_.toInt)
        var f = new Array[Array[Int]](k)
        val g = new mutable.HashMap[Int, Int]()

        for (i <- 0 until k) {
            val x = readArray().map(_.toInt)
            f(i) = new Array(x(0))
            for (j <- 0 until x(0)) {
                f(i)(j) = x(j + 1) - 1
                g += x(j + 1) - 1 -> i
            }
        }

        val _s2 = readArray()
        var s2 = new Array[(String, Int)](m)
        for (i <- 0 until m) s2(i) = ((_s2(i), i))

        var (x, y) = (0, 0)
        val index = new Array[Int](k)
        s = s.sortWith(_._1 < _._1)
        s2 = s2.sortWith(_._1 < _._1)
        f = f.map(_.sortWith(a(_) < a(_)))

        var res = 0
        while (x < s.size && y < s2.size) {
            if (s(x)._1 == s2(y)._1) {
                val id = s(x)._2
                res += a(f(g(id))(index(g(id))))
                index(g(id)) += 1

                x += 1
                y += 1
            } else x += 1
        }

        print(res)
    }
}


You are playing a computer game, where you lead a party of $$$m$$$ soldiers. Each soldier is characterised by his agility $$$a_i$$$.The level you are trying to get through can be represented as a straight line segment from point $$$0$$$ (where you and your squad is initially located) to point $$$n + 1$$$ (where the boss is located).The level is filled with $$$k$$$ traps. Each trap is represented by three numbers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$. $$$l_i$$$ is the location of the trap, and $$$d_i$$$ is the danger level of the trap: whenever a soldier with agility lower than $$$d_i$$$ steps on a trap (that is, moves to the point $$$l_i$$$), he gets instantly killed. Fortunately, you can disarm traps: if you move to the point $$$r_i$$$, you disarm this trap, and it no longer poses any danger to your soldiers. Traps don't affect you, only your soldiers.You have $$$t$$$ seconds to complete the level — that is, to bring some soldiers from your squad to the boss. Before the level starts, you choose which soldiers will be coming with you, and which soldiers won't be. After that, you have to bring all of the chosen soldiers to the boss. To do so, you may perform the following actions:  if your location is $$$x$$$, you may move to $$$x + 1$$$ or $$$x - 1$$$. This action consumes one second;  if your location is $$$x$$$ and the location of your squad is $$$x$$$, you may move to $$$x + 1$$$ or to $$$x - 1$$$ with your squad in one second. You may not perform this action if it puts some soldier in danger (i. e. the point your squad is moving into contains a non-disarmed trap with $$$d_i$$$ greater than agility of some soldier from the squad). This action consumes one second;  if your location is $$$x$$$ and there is a trap $$$i$$$ with $$$r_i = x$$$, you may disarm this trap. This action is done instantly (it consumes no time). Note that after each action both your coordinate and the coordinate of your squad should be integers.You have to choose the maximum number of soldiers such that they all can be brought from the point $$$0$$$ to the point $$$n + 1$$$ (where the boss waits) in no more than $$$t$$$ seconds.

The first line contains four integers $$$m$$$, $$$n$$$, $$$k$$$ and $$$t$$$ ($$$1 \le m, n, k, t \le 2 \cdot 10^5$$$, $$$n < t$$$) — the number of soldiers, the number of integer points between the squad and the boss, the number of traps and the maximum number of seconds you may spend to bring the squad to the boss, respectively. The second line contains $$$m$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the agility of the $$$i$$$-th soldier. Then $$$k$$$ lines follow, containing the descriptions of traps. Each line contains three numbers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$1 \le d_i \le 2 \cdot 10^5$$$) — the location of the trap, the location where the trap can be disarmed, and its danger level, respectively.

Print one integer — the maximum number of soldiers you may choose so that you may bring them all to the boss in no more than $$$t$$$ seconds.

NoteIn the first example you may take soldiers with agility $$$3$$$, $$$4$$$ and $$$5$$$ with you. The course of action is as follows:  go to $$$2$$$ without your squad;  disarm the trap $$$2$$$;  go to $$$3$$$ without your squad;  disartm the trap $$$3$$$;  go to $$$0$$$ without your squad;  go to $$$7$$$ with your squad. The whole plan can be executed in $$$13$$$ seconds.

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._

  /**
    * 単調減少
    * [l, h) 方式
    */
  def findMax(f: Int => Boolean, min: Int, max: Int): Int = {
    var l = min
    var h = max + 1
    while(h - l > 1) {
      val x = (h + l) / 2
      if (f(x)) l = x
      else h = x
    }
    l
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    java.util.Arrays.sort(a)
    a
  }

  def reverse(as: Array[Int]): Unit = {
    REP(as.length / 2) { i =>
      val t = as(i)
      as(i) = as(as.length - 1 - i)
      as(as.length - 1 - i) = t
    }
  }
}

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

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

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

  def solve(): Unit = {
    val m, n, k, t = ni()
    val A = na(m)
    sort(A)
    reverse(A)
    val open, close = Array.fill[ArrayBuffer[Int]](n + 1)(ArrayBuffer())
    REP(k) { _ =>
      val l, r, d = ni()
      open(l) += d
      close(r) += d
    }

    def test(num: Int): Boolean = {
      val agility = A(num - 1)
      var cnt = 0
      var balance = 0
      TO(1, n) { i =>
        REP(open(i).length) { j =>
          val d = open(i)(j)
          if (d > agility) balance += 1
        }

        if (balance > 0) cnt += 1

        REP(close(i).length) { j =>
          val d = close(i)(j)
          if (d > agility) balance -= 1
        }
      }
      t >= n + 1 + cnt * 2
    }

    val ans = findMax(test, 0, m)
    out.println(ans)
  }
}


Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic:  The following matrices are not palindromic because they change after the order of rows is reversed:  The following matrices are not palindromic because they change after the order of columns is reversed:  You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".

The first line contains one integer $$$n$$$ ($$$1 \le n \le 20$$$). The second line contains $$$n^2$$$ integers $$$a_1, a_2, \dots, a_{n^2}$$$ ($$$1 \le a_i \le 1000$$$) — the numbers to put into a matrix of $$$n$$$ rows and $$$n$$$ columns.

If it is possible to put all of the $$$n^2$$$ numbers into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic, then print "YES". Then print $$$n$$$ lines with $$$n$$$ space-separated numbers — the resulting matrix. If it's impossible to construct any matrix, then print "NO". You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.

NoteNote that there exist multiple answers for the first two examples.

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()
    val g = Array.ofDim[Int](N, N)
    val A = na(N * N)
    val C = Array.ofDim[Int](1001)
    REP(A.length) { i =>
      C(A(i)) += 1
    }

    // 0 => 1, 1 => 2, 2 => 4
    val nums = Array.fill[mutable.Queue[Int]](3)(mutable.Queue())

    REP(C.length) { i =>
      while(C(i) >= 4) {
        C(i) -= 4
        nums(2) += i
      }

      while(C(i) >= 2) {
        C(i) -= 2
        nums(1) += i
      }

      while(C(i) >= 1) {
        C(i) -= 1
        nums(0) += i
      }
    }

    def claim(i: Int): Unit = {
      if (nums(i).isEmpty && i < 2) {
        claim(i + 1)
        if (nums(i + 1).nonEmpty) {
          val a = nums(i + 1).dequeue()
          REP(2) { _ => nums(i) += a }
        }
      }
    }

    case class Coord(r: Int, c: Int)

    def samePos(r: Int, c: Int): Array[Coord] = {
      val set = mutable.Set[Coord]()

      (for {
        rr <- Seq(r, N - 1 - r)
        cc <- Seq(c, N - 1 - c)
      } yield Coord(rr, cc)).toSet.toArray
    }

    def fillAll(i: Int, ps: Array[Coord]): Unit = {
      claim(i)
      if (nums(i).nonEmpty) {
        val a = nums(i).dequeue()
        REP(ps.length) { i =>
          g(ps(i).r)(ps(i).c) = a
        }
      }
    }

    def fill(r: Int, c: Int): Unit = {
      val ps = samePos(r, c)
      ps.length match {
        case 1 => fillAll(0, ps)
        case 2 => fillAll(1, ps)
        case 4 => fillAll(2, ps)
      }
    }

    REP(N) { r =>
      REP(N) { c =>
        if (g(r)(c) == 0) {
          fill(r, c)
        }
      }
    }

    val ok = g.forall(_.forall(_ != 0))
    if (!ok) out.println("NO")
    else {
      out.println("YES")
      REP(N) { r =>
        out.println(g(r).mkString(" "))
      }
    }
  }

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

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

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

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

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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


Recently, your friend discovered one special operation on an integer array $$$a$$$:   Choose two indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$);  Set $$$a_i = a_j = |a_i - a_j|$$$. After playing with this operation for a while, he came to the next conclusion:   For every array $$$a$$$ of $$$n$$$ integers, where $$$1 \le a_i \le 10^9$$$, you can find a pair of indices $$$(i, j)$$$ such that the total sum of $$$a$$$ will decrease after performing the operation. This statement sounds fishy to you, so you want to find a counterexample for a given integer $$$n$$$. Can you find such counterexample and prove him wrong?In other words, find an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) such that for all pairs of indices $$$(i, j)$$$ performing the operation won't decrease the total sum (it will increase or not change the sum).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first and only line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — the length of array $$$a$$$.

For each test case, if there is no counterexample array $$$a$$$ of size $$$n$$$, print NO. Otherwise, print YES followed by the array $$$a$$$ itself ($$$1 \le a_i \le 10^9$$$). If there are multiple counterexamples, print any.

NoteIn the first test case, the only possible pairs of indices are $$$(1, 2)$$$ and $$$(2, 1)$$$.If you perform the operation on indices $$$(1, 2)$$$ (or $$$(2, 1)$$$), you'll get $$$a_1 = a_2 = |1 - 337| = 336$$$, or array $$$[336, 336]$$$. In both cases, the total sum increases, so this array $$$a$$$ is a counterexample.

    import scala.io.StdIn.readLine

    object Solution {

      def solve() = {
        val len = readLine().toInt
        if (len < 20) {
          println("YES")
          for (
            i <- 0 until len
          ) print(s"${Math.pow(3, i).toInt} ")
          println()
        }
        else println("NO")

      }

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

        val cases = readLine().toInt
        for (
          i <- 0 until cases
        ) solve()

      }
    }

import scala.io.StdIn.readLine

object Solution {

  def solve() = {
    val len = readLine().toInt
    if (len < 19) {
      println("YES")
      for (
        i <- 0 until len
      ) print(s"${Math.pow(3, i).toInt} ")
      println()
    }
    else println("NO")

  }

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

    val cases = readLine().toInt
    for (
      i <- 0 until cases
    ) solve()

  }
}


Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?

The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of participants Anton has outscored in this contest . The next n lines describe participants results: the i-th of them consists of a participant handle namei and two integers beforei and afteri ( - 4000 ≤ beforei, afteri ≤ 4000) — participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters «_» and «-» characters. It is guaranteed that all handles are distinct.

Print «YES» (quotes for clarity), if Anton has performed good in the contest and «NO» (quotes for clarity) otherwise.

3
Burunduk1 2526 2537
BudAlNik 2084 2214
subscriber 2833 2749

3
Applejack 2400 2400
Fluttershy 2390 2431
Pinkie_Pie -2500 -2450

NoteIn the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest.

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  if (lines.take(n).map(_.split(' ').drop(1).map(_.toInt)).exists{
    case Array(a, b) => a >= 2400 && b > a
  })
    println("YES")
  else
    println("NO")
}

object A681 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n){
      val tl = tokenizeLine
      tl.nextToken()
      (tl.nextToken().toInt, tl.nextToken().toInt)
    }
    if(in.exists{case (b, a) => b >= 2400 && a > b}) {
      println("YES")
    } else {
      println("NO")
    }
  }

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

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

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

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

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

}

object A681 extends App {
  var n = readInt
  var result = "NO"
  while(n > 0) {
    val s = readLine.split(" ")

    if(s(1).toInt >= 2400 && s(2).toInt > s(1).toInt) {
      result = "YES"
      n = 0
    }

    n = n - 1
  }

  print(result)
}