Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust. Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105). Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.

Output the number of pieces of sausage that lay on the crust.

NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

object BGlebAndPizza extends App {
  val Array(r, d) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
  val n = scala.io.StdIn.readLine.toInt
  val count = (0 until n).foldLeft(0) { (count, _) =>
    val Array(xi, yi, ri) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val di = xi * xi + yi * yi
    if (di >= (ri + r - d) * (ri + r - d) && di <= (r - ri) * (r - ri)) count + 1
    else count
  }
  println(count)
}

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

  override def apply(io: IO): io.type = {
    val outer, _d = io.read[Double]
    val inner = outer - _d
    val sausages = io.read[Seq[(Double, Double, Double)]]

    val ans = sausages count { case (x, y, r) =>
      val d = Math.hypot(x, y)
      inner <= d - r && d + r <= outer
    }

    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()
}
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
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  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
      }
    }
  }
}


Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $$$s = s_1 s_2 \dots s_{n}$$$ of length $$$n$$$ where each letter is either R, S or P.While initializing, the bot is choosing a starting index $$$pos$$$ ($$$1 \le pos \le n$$$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $$$s_{pos}$$$:   if $$$s_{pos}$$$ is equal to R the bot chooses "Rock";  if $$$s_{pos}$$$ is equal to S the bot chooses "Scissors";  if $$$s_{pos}$$$ is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of $$$s_{pos + 1}$$$. In the third round — on $$$s_{pos + 2}$$$ and so on. After $$$s_n$$$ the bot returns to $$$s_1$$$ and continues his game.You plan to play $$$n$$$ rounds and you've already figured out the string $$$s$$$ but still don't know what is the starting index $$$pos$$$. But since the bot's tactic is so boring, you've decided to find $$$n$$$ choices to each round to maximize the average number of wins.In other words, let's suggest your choices are $$$c_1 c_2 \dots c_n$$$ and if the bot starts from index $$$pos$$$ then you'll win in $$$win(pos)$$$ rounds. Find $$$c_1 c_2 \dots c_n$$$ such that $$$\frac{win(1) + win(2) + \dots + win(n)}{n}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains string $$$s = s_1 s_2 \dots s_{n}$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$s_i \in \{\text{R}, \text{S}, \text{P}\}$$$) — the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$n$$$ choices $$$c_1 c_2 \dots c_n$$$ to maximize the average number of wins. Print them in the same manner as the string $$$s$$$. If there are multiple optimal answers, print any of them.

NoteIn the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all $$$n = 4$$$ rounds, so the average is also equal to $$$4$$$.In the second test case:   if bot will start from $$$pos = 1$$$, then $$$(s_1, c_1)$$$ is draw, $$$(s_2, c_2)$$$ is draw and $$$(s_3, c_3)$$$ is draw, so $$$win(1) = 0$$$;  if bot will start from $$$pos = 2$$$, then $$$(s_2, c_1)$$$ is win, $$$(s_3, c_2)$$$ is win and $$$(s_1, c_3)$$$ is win, so $$$win(2) = 3$$$;  if bot will start from $$$pos = 3$$$, then $$$(s_3, c_1)$$$ is lose, $$$(s_1, c_2)$$$ is lose and $$$(s_2, c_3)$$$ is lose, so $$$win(3) = 0$$$;  The average is equal to $$$\frac{0 + 3 + 0}{3} = 1$$$ and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining "Rock paper scissors" game:

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

    def play(a: Char, b: Char): Int = {
      (a, b) match {
        case ('P', 'R') | ('R', 'S') | ('S', 'P') => 1
        case ('R', 'P') | ('S', 'R') | ('P', 'S') => 0//-1
        case _ => 0
      }
    }

    val rsp = "RSP"

    for (_ <- 1 to nextInt) {
      val s = nextLine
      val c = rsp.maxBy(c => s.map(play(c, _)).sum)
      out.println(c.toString * s.length)
    }

    out.flush()
  }

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

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

  val winBy = Map.apply('S' -> 'R', 'R' -> 'P', 'P' -> 'S')

  val t = readInt()

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

    val ans = winBy(sn.groupBy(identity).maxBy(_._2.size)._1).toString * sn.size

    println(ans)
  }
}

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

  val rps = Map.apply('S' -> "R", 'R' -> "P", 'P' -> "S")

  val t = readInt()

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

    val ans = rps(
      List('R', 'S', 'P')
        .map(s => (s, sn.count(_ == s)))
        .sortBy(_._2)(Ordering.Int.reverse)
        .head
        ._1
    ) * sn.length

    println(ans)
  }
}

import scala.io.StdIn._

object B extends App {
  val t = readInt()
  1 to t foreach { _ =>
    val A      = readLine().toCharArray
    val (x, _) = A.groupBy(identity).mapValues(_.length).maxBy(_._2)
    val answer = x match {
      case 'R' => 'P'
      case 'S' => 'R'
      case 'P' => 'S'
    }
    println(Array.fill(A.length)(answer).mkString)
  }
}

object ProblemB extends App {

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

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  @scala.annotation.tailrec
  def gcd(a: Int, b: Int): Int = {
    if (b == 0) {
      a
    } else if (a < b) {
        gcd(b, a)
      } else {
      gcd(b, a % b)
    }
  }

  case class Step(n: Int, s: Int)

  def toPrimaryList(n: Int): List[Step] = {
    var acc = n
    var result = List[Step]()
    for (i <- 2 to math.sqrt(n).floor.toInt) {
      var count = 0
      while (acc % i == 0) {
        count = count + 1
        acc = acc / i
      }
      if (count > 0) {
        result = Step(i, count) :: result
      }
    }

    if (acc > 1) {
      result = Step(acc, 1) :: result
    }

    result
  }

  val t = in.nextInt()

  val winStrategy = Map("R" -> "S", "S" -> "P", "P" -> "R")
    .map(p => p._2 -> p._1)

  for (_ <- 1 to t) {
    val s = in.nextToken()
    val mostUsed = s.groupBy(identity).maxBy(_._2.length)._1.toString

    val result = winStrategy(mostUsed) * s.length
    println(result)
  }

}

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

    def play(a: Char, b: Char): Int = {
      (a, b) match {
        case ('P', 'R') | ('R', 'S') | ('S', 'P') => 1
        case ('R', 'P') | ('S', 'R') | ('P', 'S') => -1
        case _ => 0
      }
    }

    val rsp = "RSP"

    for (_ <- 1 to nextInt) {
      val s = nextLine
      val c = rsp.maxBy(c => s.map(play(c, _)).sum)
      out.println(c.toString * s.length)
    }

    out.flush()
  }

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

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

  val t = readInt()

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

    val ans = List('R', 'S', 'P')
      .map(s => (s, sn.count(_ == s)))
      .sortBy(_._2) //(Ordering.Int.reverse)
      .head
      ._1
      .toString * sn.length

    println(ans)
  }
}

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

  val t = readInt()

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

    val ans = List('R', 'S', 'P')
      .map(s => (s, sn.count(_ == s)))
      .sortBy(_._2)(Ordering.Int.reverse)
      .head
      ._1
      .toString * sn.length

    println(ans)
  }
}

import scala.io.StdIn._

object B extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val A = readLine().toCharArray
    val answer = A.map {
      case 'P' => 'S'
      case 'S' => 'R'
      case 'R' => 'P'
    }

    println(answer.mkString)
  }
}


When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.Find the length of the longest almost constant range.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Print a single number — the maximum length of an almost constant range of the given sequence.

NoteIn the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  var total_max = 1
  var max = data.head
  var min = -1
  var maxCount = 1
  var minCount = 0
  var i = 0
  var j = 1
  var str = ""
  data.tail.foreach { el =>
    assert(minCount >= 0, "minCount less zero" )
    assert(maxCount >= 0, "maxCount less zero" )
    assert(j == i + minCount + maxCount, str)
    if (el == max) maxCount += 1
    else if (el == min) minCount += 1
    else if (min == -1 && max - el == 1) {
      min = el
      minCount = 1
    } else if (min == -1 && el - max == 1) {
      minCount = maxCount
      maxCount = 1
      min = max
      max = el
    }
    else if (min == -1) {
      max = el
      i += maxCount
      maxCount = 1
      str = "first"
    }
    else if (min - el == 1) {
      while (maxCount > 0) {
        if (data(i) == min)
          minCount -= 1
        else if (data(i) == max)
          maxCount -= 1
        i += 1
      }
      str = "second"
      max = min
      min = el
      maxCount = minCount
      minCount = 1
    } else if (el - max == 1) {
      while (minCount > 0) {
        if (data(i) == min)
          minCount -= 1
        else if (data(i) == max)
          maxCount -= 1
        i += 1
      }
      str = "third"
      min = max
      max = el
      minCount = maxCount
      maxCount = 1
    } else {
      str = "last"
      i += minCount + maxCount
      minCount = 0
      maxCount = 1
      min = -1
      max = el
    }
    if (minCount == 0)
      min = -1
    j += 1
    total_max = Math.max(total_max, maxCount + minCount)
  }
  println(total_max)
}

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

object B_333 {

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

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.t22.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val number = line1.int

    val counters = new Array[Rinf](number);
    val line2 = readLine
    var mapL = List[Rinf]()
    var mapV = List[Rinf]()
    var mapH = List[Rinf]()
    var prev = -1
    var max = 0;
    for (i <- 0 until number) {
      val vv = line2.int
      if (prev == -1 || prev == vv) {
      } else if (prev < vv) {
        val last = calcMax(mapL, i)
//        calcMax(mapV, i)
//        calcMax(mapH, i)
        mapL = mapV
        mapV = mapH
        mapH = List[Rinf]()
        clean(last, i)
      } else {
        val last = calcMax(mapH, i)
//        calcMax(mapV, i)
//        calcMax(mapL, i)
        mapH = mapV
        mapV = mapL
        mapL = List[Rinf]()
        clean(last, i)
      }
      mapV ::= new Rinf(i, vv)
      prev = vv
      dump(i, vv)
    }
    calcMax(mapL, number)
    calcMax(mapV, number)
    calcMax(mapH, number)

    print(max)

    def calcMax(li: List[Rinf], i: Integer) = {
      for (ri <- li) {
        val di = i - ri.start
        if (max < di) max = di
      }
      if (li == Nil) -1 else li.head.start
    }

    def clean(index:Integer, i:Integer) {
      if (index == -1) { return; }
      mapL = mapL.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }
      mapV = mapV.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }
      mapH = mapH.filter { x => if (x.start <= index){updateMax(x, i)} ;x.start > index }
    }

    def updateMax(ri:Rinf, i:Integer) {
      val di = i - ri.start
        if (max < di) max = di
    }

    def dump(i:Integer, value:Integer) {
      if (!debugV) return
      var res = s"Step: $i:$value max=$max\nL: "
      mapL.foreach { res += _.start + ", " }
      res += "\nV: "
      mapV.foreach { res += _.start + ", " }
      res += "\nH: "
      mapH.foreach { res += _.start + ", " }
      db(res)
    }

    //---------------------------- parameters reading end ----------------------

  }

  class Rinf(val start: Int, var value: Int) {
    var finished = false
    override def toString(): String = {
      return start + ":" + value
    }
  }

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

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

  //============================================================================================
object Test {
val sa1 = """5
1 2 3 3 2
"""

val sa2 = """
11
5 4 5 5 6 7 8 8 8 7 6
"""

val t5 = """
4
1 1 2 3
"""

def t22() = {
  val n = 100000
  var res = new StringBuilder(n + "\n")
  for (i <- 0 until n) {
    res append " 100000"
  }
//  (0 until n).foreach(x => res += "100000")
//  println(res.toString())
  res.toString()
}

}

}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val a=for(i<-0 until n) yield nextInt
    var l=0
    var r=1
    var maxl=2
    var mxv=a(l)
    var mnv=a(l)
    while(r<n){
      if(a(r)>mxv){
        if(mxv>mnv){
          //mxv-mnv=1, a(r)-mxv=1
          l=r-1
          while(l>0 && a(l)>mnv){
            l-=1
          }
          if(a(l)<=mnv){
            l+=1
          }

          mnv=mxv
        }
        mxv=a(r)
      }else if(a(r)<mnv){
        if(mnv<mxv){
          l=r-1
          while(l>0 && a(l)<mxv){
            l-=1
          }
          if(a(l)>=mxv){
            l+=1
          }
          mxv=mnv
        }
        mnv=a(r)
      }
      if(r-l+1>maxl){
        maxl=r-l+1

      }
      r+=1

    }
    out.println(maxl)

    //code ends here
    out.flush
    out.close
  }
}

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

object B_333 {

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

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val number = line1.int

    val counters = new Array[Rinf](number);
    val line2 = readLine
    var mapL = List[Rinf]()
    var mapV = List[Rinf]()
    var mapH = List[Rinf]()
    var prev = -1
    var max = 0;
    for (i <- 0 until number) {
      val vv = line2.int
      if (prev == -1 || prev == vv) {
      } else if (prev < vv) {
        val last = calcMax(mapL, i)
        calcMax(mapV, i)
        calcMax(mapH, i)
        mapL = mapV
        mapV = mapH
        mapH = List[Rinf]()
        clean(last)
      } else {
        val last = calcMax(mapH, i)
        calcMax(mapV, i)
        calcMax(mapL, i)
        mapH = mapV
        mapV = mapL
        mapL = List[Rinf]()
        clean(last)
      }
      mapV ::= new Rinf(i, vv)
      prev = vv
      dump(i, vv)
    }
    calcMax(mapL, number)
    calcMax(mapV, number)
    calcMax(mapH, number)

    print(max)

    def calcMax(li: List[Rinf], i: Integer) = {
      if (i == 10) {
        println("here")
      }
      for (ri <- li) {
        val di = i - ri.start
        if (max < di) max = di
      }
      if (li == Nil) -1 else li.head.start
    }

    def clean(index:Integer) {
      if (index == -1) { return; }
      mapL = mapL.filter { x => x.start > index }
      mapV = mapV.filter { x => x.start > index }
      mapH = mapH.filter { x => x.start > index }
    }

    def dump(i:Integer, value:Integer) {
      var res = s"Step: $i:$value max=$max\nL: "
      mapL.foreach { res += _.start + ", " }
      res += "\nV: "
      mapV.foreach { res += _.start + ", " }
      res += "\nH: "
      mapH.foreach { res += _.start + ", " }
      db(res)
    }

    //---------------------------- parameters reading end ----------------------

  }

  class Rinf(val start: Int, var value: Int) {
    var finished = false
    override def toString(): String = {
      return start + ":" + value
    }
  }

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

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

  //============================================================================================
object Test {
val sa1 = """5
1 2 3 3 2
"""

val sa2 = """
11
5 4 5 5 6 7 8 8 8 7 6
"""

val t5 = """
4
1 1 2 3
"""

}

}

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

object B_333 {

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

    //COMMENT ME !
//    is = new ByteArrayInputStream(Test.sa2.trim.getBytes("ISO-8859-1"))
//    debugV = true

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val number = line1.int

    val counters = new Array[Rinf](number);
    val line2 = readLine
    var mapL = List[Rinf]()
    var mapV = List[Rinf]()
    var mapH = List[Rinf]()
    var prev = -1
    var max = 0;
    for (i <- 0 until number) {
      val vv = line2.int
      if (prev == -1 || prev == vv) {
      } else if (prev < vv) {
        val last = calcMax(mapL, i)
        mapL = mapV
        mapV = mapH
        mapH = List[Rinf]()
        clean(last)
      } else {
        val last = calcMax(mapH, i)
        mapH = mapV
        mapV = mapL
        mapL = List[Rinf]()
        clean(last)
      }
      mapV ::= new Rinf(i, vv)
      prev = vv
      dump(i, vv)
    }
    calcMax(mapL, number-1)
    calcMax(mapV, number-1)
    calcMax(mapH, number-1)

    print(max)

    def calcMax(li: List[Rinf], i: Integer) = {
      for (ri <- li) {
        val di = i - ri.start + 1
        if (max < di) max = di
      }
      if (li == Nil) -1 else li.head.start
    }

    def clean(index:Integer) {
      if (index == -1) { return; }
      mapL = mapL.filter { x => x.start > index }
      mapV = mapV.filter { x => x.start > index }
      mapH = mapH.filter { x => x.start > index }
    }

    def dump(i:Integer, value:Integer) {
      var res = s"Step: $i:$value \nL: "
      mapL.foreach { res += _.start + ", " }
      res += "\nV: "
      mapV.foreach { res += _.start + ", " }
      res += "\nH: "
      mapH.foreach { res += _.start + ", " }
      db(res)
    }

    //---------------------------- parameters reading end ----------------------

  }

  class Rinf(val start: Int, var value: Int) {
    var finished = false
    override def toString(): String = {
      return start + ":" + value
    }
  }

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

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

  //============================================================================================
object Test {
val sa1 = """5
1 2 3 3 2
"""

val sa2 = """
11
5 4 5 5 6 7 8 8 8 7 6
"""

}

}


You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array:   [1] (from index 1 to index 1), imbalance value is 0;  [1, 4] (from index 1 to index 2), imbalance value is 3;  [1, 4, 1] (from index 1 to index 3), imbalance value is 3;  [4] (from index 2 to index 2), imbalance value is 0;  [4, 1] (from index 2 to index 3), imbalance value is 3;  [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.

The first line contains one integer n (1 ≤ n ≤ 106) — size of the array a. The second line contains n integers a1, a2... an (1 ≤ ai ≤ 106) — elements of the array.

Print one integer — the imbalance value of a.

//hint: https://codeforces.com/contest/817/submission/27832753
/* Divide and conquer */

import scala.math.min
import scala.math.max

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

  val n = InOut.nextInt
  val arr:Array[Int] = InOut.nextInts(n)
  val max_at:Array[Int] = new Array[Int](n)
  val min_at:Array[Int] = new Array[Int](n)

  def get_max(start:Int, end:Int):Long = {
    if (start == end){
      return arr(start)
    }

    val mid:Int = (start+end)/2
    var sum:Long = 0L
    var ans:Long = 0L
    var curr_max:Int = 0
    for(i <- mid+1 to end){
      curr_max = max(curr_max, arr(i))
      sum += curr_max
      max_at(i) = curr_max
    }

    var right = mid+1
    curr_max = 0
    for (i <- mid to start by -1){
      curr_max = max(curr_max, arr(i))
      while (right <= end && max_at(right) <= curr_max){
        sum -= max_at(right)
        right += 1
      }
      val scope:Long = right-mid-1
      ans += (sum + curr_max * scope)
    }
    return ans + get_max(start, mid) + get_max(mid+1, end)
  }

  def get_min(start:Int, end:Int):Long = {
    if (start == end){
        return arr(start)
    }
    val mid:Int = (start+end)/2
    var sum:Long = 0L
    var curr_min:Int = 100000000
    for (i <- mid+1 to end){
      curr_min = min(curr_min, arr(i))
      sum += curr_min
      min_at(i) = curr_min
    }

    var right:Int = mid+1
    curr_min = 100000000
    var ans:Long = 0L
    for (i <- mid to start by -1){
      curr_min = min(curr_min, arr(i))
      while (right <= end && min_at(right) > curr_min){
        sum -= min_at(right)
        right += 1
      }
      val scope:Long = right-mid-1
      ans += (sum + curr_min * scope)
    }
    return ans + get_min(start, mid) + get_min(mid+1, end)
  }

  print(get_max(0, n-1) - get_min(0, n-1))
}

//hint: https://codeforces.com/contest/817/submission/27832753
/* Divide and conquer */

import scala.math.min
import scala.math.max

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

  val n = InOut.nextInt
  val arr:Array[Int] = InOut.nextInts(n)
  val max_at:Array[Int] = new Array[Int](n)
  val min_at:Array[Int] = new Array[Int](n)

  def get_max(start:Int, end:Int):Long = {
    if (start == end){
      return arr(start)
    }

    val mid:Int = (start+end)>>1
    var sum:Long = 0
    var ans:Long = 0
    var curr_max:Int = 0
    for(i <- mid+1 to end){
      curr_max = max(curr_max, arr(i))
      sum += curr_max
      max_at(i) = curr_max
    }

    var right = mid+1
    curr_max = 0
    for (i <- mid to start by -1){
      curr_max = max(curr_max, arr(i))
      while (right <= end && max_at(right) <= curr_max){
        sum -= max_at(right)
        right += 1
      }
      ans += (sum + curr_max * (right-mid-1))
    }
    return ans + get_max(start, mid) + get_max(mid+1, end)
  }

  def get_min(start:Int, end:Int):Long = {
    if (start == end){
        return arr(start)
    }
    val mid:Int = (start+end) >> 1
    var ans:Long = 0
    var sum:Long = 0
    var curr_min:Int = 10000000
    for (i <- mid+1 to end){
      curr_min = min(curr_min, arr(i))
      sum += curr_min
      min_at(i) = curr_min
    }

    var right = mid+1
    curr_min = 10000000
    for (i <- mid to start by -1){
      curr_min = min(curr_min, arr(i))
      while (right <= end && min_at(right) > curr_min){
        sum -= min_at(right)
        right += 1
      }
      ans += (sum + curr_min * (right-mid-1))
    }
    return ans + get_min(start, mid) + get_min(mid+1, end)
  }

  print(get_max(0, n-1) - get_min(0, n-1))
}

//hint: https://codeforces.com/contest/817/submission/27832753
/* Divide and conquer */

import scala.math.min
import scala.math.max

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

  val n = InOut.nextInt
  val arr:Array[Int] = InOut.nextInts(n)
  val max_at:Array[Int] = new Array[Int](n)
  val min_at:Array[Int] = new Array[Int](n)

  def get_max(start:Int, end:Int):Long = {
    if (start == end){
      return arr(start)
    }

    val mid:Int = (start+end)>>1
    var sum:Long = 0L
    var ans:Long = 0L
    var curr_max:Int = 0
    for(i <- mid+1 to end){
      curr_max = max(curr_max, arr(i))
      sum += curr_max
      max_at(i) = curr_max
    }

    var right = mid+1
    curr_max = 0
    for (i <- mid to start by -1){
      curr_max = max(curr_max, arr(i))
      while (right <= end && max_at(right) <= curr_max){
        sum -= max_at(right)
        right += 1
      }
      ans += (sum + curr_max * (right-mid-1))
    }
    return ans + get_max(start, mid) + get_max(mid+1, end)
  }

  def get_min(start:Int, end:Int):Long = {
    if (start == end){
        return arr(start)
    }
    val mid:Int = (start+end) >> 1
    var ans:Long = 0L
    var sum:Long = 0L
    var curr_min:Int = 100000000
    for (i <- mid+1 to end){
      curr_min = min(curr_min, arr(i))
      sum += curr_min
      min_at(i) = curr_min
    }

    var right = mid+1
    curr_min = 100000000
    for (i <- mid to start by -1){
      curr_min = min(curr_min, arr(i))
      while (right <= end && min_at(right) > curr_min){
        sum -= min_at(right)
        right += 1
      }
      ans += (sum + curr_min * (right-mid-1))
    }
    return ans + get_min(start, mid) + get_min(mid+1, end)
  }

  print(get_max(0, n-1) - get_min(0, n-1))
}


You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.

For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.

NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$.

object P1445A extends App {
  import scala.collection.{immutable, mutable}

  def parseInt(str: String, count: Int): Seq[Int] = {
    val scanner = new java.util.Scanner(str)
    val res = (1 to count) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def scanInts(count: Int): Seq[Int] = parseInt(scala.io.StdIn.readLine(), count)
  def readMatrix(row: Int, col: Int) = (1 to row) map (x => scanInts(col))

  def solve(a: Seq[Int], b: Seq[Int], x: Int): Boolean = {
    var bSorted = new mutable.TreeMap[Int, Int]()(Ordering[Int].reverse)

    b.foreach((k) => bSorted(k)=bSorted.getOrElse(k, 0)+1)

    def haveNoMatch(v: Int) : Boolean = {
      val it = bSorted.iteratorFrom(x-v)
      if (!it.hasNext) true
      else {
        val (bVal, bCnt) = it.next()
        if (bCnt <= 1)
          bSorted.remove(bVal)
        else
          bSorted(bVal) = bSorted(bVal) - 1
        false
      }
    }

    !a.exists(haveNoMatch)
  }

  val nCases = scanInts(1)(0)

  for (nCase <- 1 to nCases) {
    val s = scanInts(2)
    val n = s(0)
    val x = s(1)

    val a = scanInts(n)
    val b = scanInts(n)
    scala.io.StdIn.readLine()

    println(if (solve(a, b, x)) "Yes" else "No")
  }
}


The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 ≤ si ≤ c).Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 ≤ c, and 0, otherwise.You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right — (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.A star lies in a rectangle if it lies on its border or lies strictly inside it.

The first line contains three integers n, q, c (1 ≤ n, q ≤ 105, 1 ≤ c ≤ 10) — the number of the stars, the number of the views and the maximum brightness of the stars. The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 ≤ xi, yi ≤ 100, 0 ≤ si ≤ c ≤ 10) — the coordinates of i-th star and its initial brightness. The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 ≤ ti ≤ 109, 1 ≤ x1i < x2i ≤ 100, 1 ≤ y1i < y2i ≤ 100) — the moment of the i-th view and the coordinates of the viewed rectangle.

For each view print the total brightness of the viewed stars.

NoteLet's consider the first example.At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.

object C extends App {

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

  val Array(n, q, c) = readInts(3)

  val cnt = Array.fill(c + 1, 101, 101){ 0 }

  Array.fill(n) {
    val Array(x, y, s) = readInts(3)
    cnt(s)(x)(y) += 1
  }

  for (s <- 0 to c) {
    for (y <- 1 to 100) {
      var left = 0
      for (x <- 1 to 100) {
        left += cnt(s)(x)(y)
        cnt(s)(x)(y) = left + cnt(s)(x)(y - 1)
      }
    }
  }

  val res = Array.ofDim[Int](q)

  for (i <- 0 until q) {
    val Array(t, x1, y1, x2, y2) = readInts(5)
    var sum = 0
    for (s <- 0 to c) {
      val count = cnt(s)(x2)(y2) - cnt(s)(x1 - 1)(y2) - cnt(s)(x2)(y1 - 1) + cnt(s)(x1 - 1)(y1 - 1)
      val brightness = (s + t) % (c + 1)
      sum += count * brightness
    }
    res(i) = sum
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.mkString("\n"))

  Console.flush
}

object CStarSky extends App {
  val Array(n, q, c) = scala.io.StdIn.readLine.split(" ").map(_.toInt)

  var cnt = Array.fill[Int](c + 1, 101, 101){0}
  (0 until n).foreach { _ =>
    val Array(x, y, s) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    cnt(s)(x)(y) = cnt(s)(x)(y) + 1
  }
  for (p <- 0 to c; x <- 1 to 100; y <- 1 to 100)
    cnt(p)(x)(y) = cnt(p)(x)(y) + cnt(p)(x - 1)(y) + cnt(p)(x)(y - 1) - cnt(p)(x - 1)(y - 1)

  (0 until q).foreach { _ =>
    val Array(t, x1, y1, x2, y2) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val s = (0 to c).foldLeft(0) { (s, p) =>
      val brightness = (p + t) % (c + 1)
      val amount = cnt(p)(x2)(y2) + cnt(p)(x1-1)(y1-1) - cnt(p)(x1-1)(y2) - cnt(p)(x2)(y1-1)
      s + brightness * amount
    }
    println(s)
  }
}


n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.

The first line contains integer n (1 ≤ n ≤ 18) — the amount of fish in the lake. Then there follow n lines with n real numbers each — matrix a. aij (0 ≤ aij ≤ 1) — the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.

Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.

import java.util.Scanner

/**
  * Created by Meepo on 17/3/14.
  */
object Main extends App
{
    val input = new Scanner(System.in)
    val n = input.nextInt()
    val arr = Array.ofDim[Double](n, n)
    for (i <- arr.indices; j <- arr.indices)
        arr(i)(j) = input.nextDouble()

    val dp = Array.ofDim[Double](1 << n)
    dp((1 << n) - 1) = 1.0

    def fishNum(stateInput: Int): Int =
    {
        var state = stateInput
        var fish = 0
        while (state != 0)
        {
            fish += state & 1
            state = state >> 1
        }
        fish
    }

    var i = (1 << n) - 1
    while (i >= 1)
    {
        val fish = fishNum(i)
        if (fish != 1)
        {
            val choose = 2.0 * dp(i) / fish / (fish - 1)
            for (j <- 0 until n)
            {
                if ((i & (1 << j)) != 0)
                {
                    for (k <- 0 until n)
                    {
                        if ((i & (1 << k)) != 0)
                            dp(i ^ (1 << k)) += choose * arr(j)(k)
                    }
                }
            }

        }
        i -= 1
    }

    val ans =
        {
            for (i <- 0 until n) yield
                dp(1 << i).formatted("%.6f")
        }.mkString(" ")
    println(ans)

}


Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $$$n$$$ steps. At the $$$i$$$-th step, a place is chosen for the number $$$i$$$ $$$(1 \leq i \leq n)$$$. The position for the number $$$i$$$ is defined as follows:  For all $$$j$$$ from $$$1$$$ to $$$n$$$, we calculate $$$r_j$$$  — the minimum index such that $$$j \leq r_j \leq n$$$, and the position $$$r_j$$$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $$$r_j$$$ is not defined.  For all $$$t$$$ from $$$1$$$ to $$$n$$$, we calculate $$$count_t$$$  — the number of positions $$$1 \leq j \leq n$$$ such that $$$r_j$$$ is defined and $$$r_j = t$$$.  Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $$$count$$$ array is maximum.  The generator selects one of these positions for the number $$$i$$$. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example:  Let $$$n = 5$$$ and the algorithm has already arranged the numbers $$$1, 2, 3$$$ in the permutation. Consider how the generator will choose a position for the number $$$4$$$:  The values of $$$r$$$ will be $$$r = [3, 3, 3, 4, \times]$$$, where $$$\times$$$ means an indefinite value.  Then the $$$count$$$ values will be $$$count = [0, 0, 3, 1, 0]$$$.  There are only two unoccupied positions in the permutation: $$$3$$$ and $$$4$$$. The value in the $$$count$$$ array for position $$$3$$$ is $$$3$$$, for position $$$4$$$ it is $$$1$$$.  The maximum value is reached only for position $$$3$$$, so the algorithm will uniquely select this position for number $$$4$$$. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $$$p_1, p_2, \ldots, p_n$$$ and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^5)$$$  — the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the size of the permutation. The second line of the test case contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq n$$$)  — the permutation written by Denis. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

Print "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No". All letters can be displayed in any case.

NoteLet's simulate the operation of the generator in the first test.At the $$$1$$$ step, $$$r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]$$$. The maximum value is reached in any free position, so the generator can choose a random position from $$$1$$$ to $$$5$$$. In our example, it chose $$$5$$$.At the $$$2$$$ step, $$$r = [1, 2, 3, 4, \times], count = [1, 1, 1, 1, 0]$$$. The maximum value is reached in positions from $$$1$$$ to $$$4$$$, so the generator can choose a random position among them. In our example, it chose $$$1$$$.At the $$$3$$$ step, $$$r = [2, 2, 3, 4, \times], count = [0, 2, 1, 1, 0]$$$. The maximum value is $$$2$$$ and is reached only at the $$$2$$$ position, so the generator will choose this position.At the $$$4$$$ step, $$$r = [3, 3, 3, 4, \times], count = [0, 0, 3, 1, 0]$$$. The maximum value is $$$3$$$ and is reached only at the $$$3$$$ position, so the generator will choose this position.At the $$$5$$$ step, $$$r = [4, 4, 4, 4, \times], count = [0, 0, 0, 4, 0]$$$. The maximum value is $$$4$$$ and is reached only at the $$$4$$$ position, so the generator will choose this position.In total, we got a permutation of $$$2, 3, 4, 5, 1$$$, that is, a generator could generate it.

import scala.collection.mutable

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val ps = nextInts(n).map(_ - 1)
    val pos = Array.ofDim[Int](n)
    val counts = mutable.TreeMap.empty[Int, Int].withDefaultValue(0)
    counts(1) = n
    val countsByPos = Array.fill(n)(1)
    val next = new java.util.TreeSet[Int]
    for (i <- 0 until n) {
      pos(ps(i)) = i
      next.add(i)
    }
    var i = 0
    var ok = true
    while (i < n) {
      val p = pos(i)
      val c = countsByPos(p)
      if (c == counts.max._1) {
        val r: Integer = next.higher(p)
        if (r != null && r > p) {
          countsByPos(r) += countsByPos(p)
          counts(countsByPos(r)) += 1
        }
        next.remove(p)
        counts(countsByPos(p)) -= 1
        if (counts(countsByPos(p)) == 0) {
          counts.remove(countsByPos(p))
        }
        countsByPos(p) = 0
      } else {
        ok = false
        i = n
      }
      i += 1
    }

    out.println(if (ok) "Yes" else "No")
  }

  out.flush()

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


Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which  two planks of length at least $$$k+1$$$ — the base of the ladder;  $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps.   You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.

NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:

//package codeforces.contest1197

object DIYWoodenLadder {
  def main(args: Array[String]): Unit = {
    println((1 to io.StdIn.readInt).map { _ =>
      val n = io.StdIn.readInt()
      val seq = io.StdIn.readLine().split(" ").map(_.toInt).sorted

      if (seq.length > 2) {
        seq(n - 2) - 1 min n - 2
      } else 0

    }.mkString("\n"))
  }
}

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = na(N)
      if (N == 2) {
        out.println(0)
      } else {
        sort(A)
        val A1 = A(N - 1)
        val A2 = A(N - 2)
        val cnt = N - 2
        val ans = min(cnt, min(A1 - 1, A2 - 1))
        out.println(ans)
      }
    }
  }

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

import java.util.StringTokenizer

object problemA {
  def main(args: Array[String]): Unit = {
    val T = scala.io.StdIn.readInt()
    (0 until T).map(_ => {
      val n = scala.io.StdIn.readInt()
      val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
      val initmax1 = reader.nextToken().toInt
      val initmax2 = reader.nextToken().toInt
      var max1 = Math.max(initmax1, initmax2)
      var max2 = Math.min(initmax1, initmax2)
      val steps = (2 until n).map(_ => {
        val i = reader.nextToken().toInt
        if (i >= max1) {
          max2 = max1
          max1 = i
        } else if (i > max2) {
          max2 = i
        } else()
        i
      })
      Math.min(max2 - 1, steps.size)
    }).foreach(println)
  }

}

import java.util.StringTokenizer

object solve {
  def main(args: Array[String]): Unit = {
    val T = scala.io.StdIn.readInt()
    (0 until T).foreach(_ => {
      val n = scala.io.StdIn.readInt()
      val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
      val initmax1 = reader.nextToken().toInt
      val initmax2 = reader.nextToken().toInt
      var max1 = Math.max(initmax1, initmax2)
      var max2 = Math.min(initmax1, initmax2)
      val steps = (2 until n).map(_ => {
        val i = reader.nextToken().toInt
        if (i >= max1) {
          max2 = max1
          max1 = i
        }
        i
      })
      val res = Math.min(max2 - 1, steps.size)

      println(res)
    })
  }

}

import java.util.StringTokenizer

object solve {
  def main(args: Array[String]): Unit = {
    val T = scala.io.StdIn.readInt()
    (0 until T).map(_ => {
      val n = scala.io.StdIn.readInt()
      val reader = new StringTokenizer(scala.io.StdIn.readLine(), " ")
      val initmax1 = reader.nextToken().toInt
      val initmax2 = reader.nextToken().toInt
      var max1 = Math.max(initmax1, initmax2)
      var max2 = Math.min(initmax1, initmax2)
      val steps = (2 until n).map(_ => {
        val i = reader.nextToken().toInt
        if (i >= max1) {
          max2 = max1
          max1 = i
        }
        i
      })
      Math.min(max2 - 1, steps.size)
    }).foreach(println)
  }

}


Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.

The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.

Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.

NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.

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

object P369A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M, K = sc.nextInt
  type Dishes = List[Int]
  val A: Dishes = List.fill(N)(sc.nextInt)

  def solve(): Int = {

    @tailrec
    def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //
        case Nil       => acc
        case 1 :: rest => { // first type from bowl
          if (b > 0) loop(acc, b - 1, p, rest)
          else loop(acc + 1, 0, p, rest)
        }
        case 2 :: rest => { // second type from either bowl or plate
          if (p > 0) loop(acc, b, p - 1, rest)
          else if (b > 0) loop(acc, b - 1, p, rest)
          else loop(acc + 1, 0, 0, rest)
        }
        case _ => -1
      }

    loop(0, M, K, A)
  }

  out.println(solve)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val Array(n, m, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ")
    val c1 = a.count(_ == "1")
    val c2 = a.count(_ == "2")

    val count = (c1 - m).max(0) + (c2 - k - (m - c1).max(0)).max(0)
    println(count)
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A369 extends App{
  val sc = new Scanner(System.in)
  val n, m, k = sc.nextInt()
  val a: Array[Int] = (1 to n).map(_ => sc.nextInt()).toArray
  val needBowl = a.count(_ == 1)
  val needAny = n - needBowl

  // 需要洗的碗
  val needWashBowl = if (m - needBowl >= 0) {
    0
  } else {
    needBowl - m
  }

  // 需要洗的其他
  val needWashAny: Int = if (needWashBowl == 0) {
    needAny - (m - needBowl + k) // 存量的其他
  } else {
    needAny - k
  }

  println(needWashBowl + (if (needWashAny < 0) {
    0
  } else {
    needWashAny
  }))
}

object HelloWorld   {
    def main(args:Array[String]){
        var nmk=readLine().split(" ").map(_.toInt)
        var n=nmk(0)
        var m=nmk(1)
        var k=nmk(2)
        var sum=0
        var array=readLine().split(" ").map(_.toInt)
        for(i<-0 to n-1){
            var int=array(i)
            if(int==1){
                if (m>=1) {
                    m-=1
                }else{
                    sum+=1
                }
            }else{
                if (k>=1) {
                    k-=1
                }else if(m>=1){
                    m-=1
                }else{
                    sum+=1
                }
            }
        }
        println(sum)
    }
}

object HelloWorld   {
    def main(args:Array[String]){
        var Array(n,m,k)=readLine().split(" ").map(_.toInt)
        var sum=0
        var array=readLine().split(" ")
        for(i<-0 to n-1){
            var int=array(i).toInt
            if(int==1){
                if (m>=1) {
                    m-=1
                }else{
                    sum+=1
                }
            }else{
                if (k>=1) {
                    k-=1
                }else if(m>=1){
                    m-=1
                }else{
                    sum+=1
                }
            }
        }
        println(sum)
    }
}

object HelloWorld   {
    def main(args:Array[String]){
        var Array(n,m,k)=readLine().split(" ").map(_.toInt)
        var sum=0
        var array=readLine().split(" ").map(_.toInt)
        for(i<-0 to n-1){
            var int=array(i)
            if(int==1){
                if (m>=1) {
                    m-=1
                }else{
                    sum+=1
                }
            }else{
                if (k>=1) {
                    k-=1
                }else if(m>=1){
                    m-=1
                }else{
                    sum+=1
                }
            }
        }
        println(sum)
    }
}

object Solution216A extends App {

  def solution() {
    val n = _int
    val b = _int
    val p = _int

    val a = 1.to(n).map(_ => _int)
    val gr = a.groupBy(i => i)
    val n1 = gr.get(1).getOrElse(Nil).size
    val n2 = math.max(gr.get(2).getOrElse(Nil).size - p, 0)

    val req = n1 + n2

    if (req <= b) {
      println(0)
    } else {
      println(req - b)
    }
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

import java.util.StringTokenizer

object _369A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  var m = next.toInt
  val k = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val one = a.filter(i => i == 1).size
  val two = a.filter(i => i == 2).size

  var ans = if (m >= one) 0 else one - m
  m = if (m - one >= 0) m - one else 0
  ans = ans + (if (m + k - two >= 0) 0 else two - m - k)
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).groupBy(k => k).map(t => t._1 -> t._2.length)
  val first = Math.max(0, data.getOrElse(1, 0) - m)
  val second =
    if (first == 0)
      Math.max(0, data.getOrElse(2, 0) - k - m + data.getOrElse(1, 0))
  else
    Math.max(0, data.getOrElse(2, 0) - k)
  println(first + second)
}

object A369 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, m, k) = readInts(3)
    val in = readInts(n)
    var res = 0
    for(i <- 0 until n) {
      val day = in(i)
      if(day == 1) {
        if(m > 0) {m -= 1} else {res += 1}
      } else {
        if(m > 0 || k > 0) {
          if(k > 0) {
            k -= 1
          } else {
            m -= 1
          }
        } else {
          res += 1
        }
      }
    }
    println(res)
  }

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

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

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

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

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

}

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

object P369A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M, K = sc.nextInt
  val A = List.fill(N)(sc.nextInt)

  type Dishes = List[Int]

  def solve(): Int = {

    @tailrec
    def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //
        case Nil       => acc
        case 1 :: rest => { // first type from bowl and dish
          if (b < 1) loop(acc + 1, M, K, rest)
          else loop(acc, b - 1, p, rest)
        }
        case 2 :: rest => { // second type from either bowl or plate
          if (b < p) {
            if (p < 1) loop(acc + 1, M, K, rest)
            else loop(acc, b, p - 1, rest)
          }
          else {
            if (b < 1) loop(acc + 1, M, K, rest)
            else loop(acc, b - 1, p, rest)
          }
        }
        case _ => -1
      }

    loop(0, M, K, A)
  }

  out.println(solve)
  out.close
}

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

object P369A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M, K = sc.nextInt
  val A = List.fill(N)(sc.nextInt)

  type Dishes = List[Int]

  def solve(): Int = {

    @tailrec
    def loop(acc: Int, b: Int, p: Int, ds: Dishes): Int = ds match { //
        case Nil       => acc
        case 1 :: rest => { // first type from bowl and dish
          val wash = if (b < 1) 1 else 0
          loop(acc + wash, b - 1, p, rest)
        }
        case 2 :: rest => { // second type from either bowl or plate
          val wash = if (b < 1 && p < 1) 1 else 0
          if (b < p) loop(acc + wash, b, p - 1, rest)
          else loop(acc + wash, b - 1, p, rest)
        }
        case _ => -1
      }

    loop(0, M, K, A)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-19.
 */
object A369 extends App{
  val sc = new Scanner(System.in)
  val n, m, k = sc.nextInt()
  val a: Array[Int] = (1 to n).map(_ => sc.nextInt()).toArray
  val needBowl = a.count(_ == 1)
  val needAny = n - needBowl

  // 需要洗的碗
  val needWashBowl = if (m - needBowl >= 0) {
    0
  } else {
    needBowl - m
  }

  val needWashAny: Int = if (needWashBowl == 0) {
    needAny - (m - needBowl + n)
  } else {
    needAny - k
  }

  println(needWashBowl + (if (needWashAny < 0) {
    0
  } else {
    needWashAny
  }))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt).groupBy(k => k).map(t => t._1 -> t._2.length)
  println(Math.max(0, data.getOrElse(1, 0) - m) + Math.max(0, data.getOrElse(2, 0) - k))
}

object A369 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, m, k) = readInts(3)
    val in = readInts(n)
    var res = 0
    for(i <- 0 until n) {
      val day = in(i)
      if(day == 1) {
        if(m > 0) {m -= 1} else {res += 1}
      } else {
        if(m > 0 || k > 0) {
          if(m > k) {
            m -= 1
          } else {
            k -= 1
          }
        } else {
          res += 1
        }
      }
    }
    println(res)
  }

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

}


Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 7000$$$) — the number of students interested in the camp. The second line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$a_i$$$ ($$$0 \leq a_i < 2^{60}$$$). The third line contains $$$n$$$ integers. The $$$i$$$-th of them is $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).

Output one integer which denotes the maximum sum of $$$b_i$$$ over the students in a group of students which can work together calmly. If no group of at least two students can work together calmly, print 0.

NoteIn the first sample test, it's optimal to send the first, the second and the third student to the camp. It's also possible to send only the first and the third student, but they'd have a lower sum of $$$b_i$$$.In the second test, in each group of at least two students someone will always think that he is better than everyone else in the subset.

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 private final 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[Long]]): 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 private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 = {
    var i = from
    while(i <= to) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

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

  def solve(): Unit = {
    import java.util
    val n = ni()
    val a = nal(n)
    val b = na(n)
    val c = Array.ofDim[Int](n)
    REP(n) { i =>
      REP(n) { j =>
        if (i != j) {
          if ((a(i)^a(j)&a(i)) > 0) {
            c(i) += 1
          }
        }
      }
    }
    val alive = Array.fill[Boolean](n)(true)
    val q = new util.ArrayDeque[Int]
    REP(n) { i =>
      if (c(i) == n - 1) {
        alive(i) = false
        q.add(i)
      }
    }

    var setCnt = n
    while (!q.isEmpty) {
      val v = q.poll()
      debug(s"v:$v")
      setCnt -= 1
      REP(n) { u =>
        if ((a(v)^a(u)&a(v)) > 0 && alive(u)) {
          if ((a(u) ^ a(v) & a(u)) > 0) c(u) -= 1
          if (c(u) == setCnt - 1) {
            alive(u) = false
            q.add(u)
          }
        }
      }
    }
    debug(alive)
    var ans = 0L
    REP(n) { i =>
      if (alive(i)) ans += b(i)
    }
    out.println(ans)
  }
}

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 private final 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[Long]]): 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 private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 = {
    var i = from
    while(i <= to) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

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

  def solve(): Unit = {
    import java.util
    val n = ni()
    val a = nal(n)
    val b = na(n)
    val c = Array.ofDim[Int](n)
    val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())
    REP(n) { i =>
      REP(n) { j =>
        if (i != j) {
          if ((a(i)^a(j)&a(i)) > 0) {
            g(i) += j
            c(i) += 1
          }
        }
      }
    }
    debug(g.mkString(" "))
    val alive = Array.fill[Boolean](n)(true)
    val q = new util.ArrayDeque[Int]
    REP(n) { i =>
      if (c(i) == n - 1) q.add(i)
    }

    var setCnt = n
    while (!q.isEmpty) {
      val v = q.poll()
      debug(s"v:$v")
      setCnt -= 1
      alive(v) = false
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (alive(u)) {
          if ((a(u) ^ a(v) & a(u)) > 0) c(u) -= 1
          if (c(u) == setCnt - 1) q.add(u)
        }
      }
    }
    debug(alive)
    var ans = 0L
    REP(n) { i =>
      if (alive(i)) ans += b(i)
    }
    out.println(ans)
  }
}

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 private final 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[Long]]): 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 private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 = {
    var i = from
    while(i <= to) { 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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

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

  def solve(): Unit = {
    import java.util
    val n = ni()
    val a = nal(n)
    val b = na(n)
    val c = Array.ofDim[Int](n)
    val g = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())
    REP(n) { i =>
      REP(n) { j =>
        if (i != j) {
          if ((a(i)^a(j)&a(i)) > 0) {
            g(i) += j
            c(i) += 1
          }
        }
      }
    }
    debug(g.mkString(" "))
    val alive = Array.fill[Boolean](n)(true)
    val q = new util.ArrayDeque[Int]
    REP(n) { i =>
      if (c(i) == n - 1) q.add(i)
    }

    var setCnt = n
    while (!q.isEmpty) {
      val v = q.poll()
      debug(s"v:$v")
      setCnt -= 1
      alive(v) = false
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if ((a(u)^a(v)&a(u)) > 0) c(u) -= 1
        if (c(u) == setCnt - 1) q.add(u)
      }
    }
    debug(alive)
    var ans = 0L
    REP(n) { i =>
      if (alive(i)) ans += b(i)
    }
    out.println(ans)
  }
}