Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends. Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.

Print the maximum number of people that may come to Famil Door's party.

NoteIn the first sample, friends 3 and 4 can come on any day in range [117, 128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.

import scala.io.Source

object CF343_B extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt

  val mens = new Array[Int](367)
  val wms = new Array[Int](367)

  for(r <- 0 to n-1) {
      val line = in.next()
      val info = line.split(" ")
      var arr = mens
      if(info(0).equals("F")) {
         arr = wms
      }
      for(idx <- info(1).toInt to info(2).toInt) {
        arr(idx) += 1
      }
  }

  var max = 0

  for(i <- 0 to 366) {
    val cand = mens(i).min(wms(i)) * 2
    max = max.max(cand)
  }

println(max)

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map { _ =>
    val Array(sex, start, end) = in.next().split(' ')
    (sex.head, start.toInt, end.toInt)
  }
  println(2 * (1 to 366).foldLeft(0) {
    case(acc, i) =>
      val res = data.foldLeft((0, 0)) {
        case((m, f), ('M', start, end)) if i >= start && i <= end => (m + 1, f)
        case((m, f), ('F', start, end)) if i >= start && i <= end => (m, f + 1)
        case(acc, _) => acc
      }
      Math.max(acc, Math.min(res._1, res._2))
  })
}

import io.StdIn._
import java.lang.Math._
object div2_B {
    def main(args: Array[String]){
        val n = readInt()
        var F = Vector[(String,(Int,Int))]()
        for (i <- 0 until n) {
            val ln = readLine().split(" ")
            val v = (ln(0).toString,(ln(1).toInt, ln(2).toInt))

            F = F :+ v
        }
        var res = 0
        for(i <- 1 to 366) {
            var m = 0
            var f = 0
            for(j <- 0 until F.length){
                if (F(j)._2._1 <= i && F(j)._2._2 >= i) {
                    if (F(j)._1 == "M") {
                        m = m + 1
                    }
                    else {
                        f = f + 1
                    }
                }
            }
            res = max(res, min(m,f))
        }
        println(res*2)
    }
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _629B extends CodeForcesApp {
  override type Result = Int

  override def solve(read: InputReader) = {
    val (males, females) = (Array.ofDim[Int](367), Array.ofDim[Int](367))
    val n = read[Int]
    repeat(n) {
      val (s, a, b) = read[(Char, Int, Int)]
      val arr = if (s == 'M') males else females
      for {i <- a to b} arr(i) += 1
    }

    val couples = males zip females map { case (a, b) => a min b}
    couples.max * 2
  }

  @inline def repeat(n: Int)(f: => Unit): Unit = for {_ <- 1 to n} f

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

  @inline private[this] def tokenizer(): Option[StringTokenizer] = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine() = till("\n\r")

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}
object Parser {
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collection[C[_], A: Parser](implicit cbf: Collection[C, A])   : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}

import java.util.Scanner

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

    var imosM = new Array[Int](370)
    var imosF = new Array[Int](370)

    for(i <- 1 to n){
      val c = sc.next()
      val a = sc.nextInt()
      val b = sc.nextInt()
      if(c == "M"){
        imosM(a) += 1
        imosM(b+1) -= 1
      }
      else{
        imosF(a) += 1
        imosF(b+1) -= 1
      }
    }

    //
    for(i <- 1 to 366){
      imosM(i+1) += imosM(i)
      imosF(i+1) += imosF(i)
    }

    var ans = 0
    for(i <- 1 to 366){
      val tmp = Math.min(imosM(i), imosF(i))
      ans = Math.max(ans, tmp)
    }

    println(ans*2)
  }
}

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

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

      //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading --------------------------
    val n = readLine.int
    val males, females = new Array[Int](367)
    debug("n = " + n)

    (1 to n).foreach{ x =>
      val line = readLine
      val arr = if (line.string == "M") males else females
      (line.int to line.int).foreach(arr(_) += 1)
    }
    //---------------------------- parameters reading end ----------------------
    val res = (1 to 366).map(i => males(i).min(females(i)) ).max * 2
    outLn(res+"")
    finish
  }

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

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

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

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

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

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

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

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

val sa1 = """
4
M 151 307
F 343 352
F 117 145
M 24 128
"""

val sa2 = """
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
"""

}

}

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

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

      //COMMENT ME !
    runTest(Test.sa2)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading --------------------------
    val n = readLine.int
    val males = new Array[Int](367)
    val females = new Array[Int](367)
    debug("n = " + n)

    (1 to n).foreach{ x =>
      val line = readLine
      val male = line.string == "M"
      val start = line.int
      val end = line.int
      for (i <- start to end) {
        if (male) males(i) += 1
        else females(i) += 1
      }
    }

    //---------------------------- parameters reading end ----------------------
    var res = 0
    for (i <- 1 to 366) {
      val possible = males(i).min(females(i))
      if (res < possible) res = possible
    }
    res = res *2

    outLn(res+"")

    finish
  }

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

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

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

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

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

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

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

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

val sa1 = """
4
M 151 307
F 343 352
F 117 145
M 24 128
"""

val sa2 = """
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
"""

}

}

import scala.io.Source

object CF343_B extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt

  val mens = new Array[Int](367)
  val wms = new Array[Int](367)

  for(r <- 0 to n-1) {
      val line = in.next()
      val info = line.split(" ")
      var arr = mens
      if(info(0).equals("W")) {
         arr = wms
      }
      for(idx <- info(1).toInt to info(2).toInt) {
        arr(idx) += 1
      }
  }

  var max = 0

  for(i <- 0 to 366) {
    val cand = mens(i).min(wms(i))
    max = max.max(cand)
  }

println(max)

}

import scala.io.Source

object CF343_B extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt

  val mens = new Array[Int](367)
  val wms = new Array[Int](367)

  for(r <- 0 to n-1) {
      val line = in.next()
      val info = line.split(" ")
      var arr = mens
      if(info(0).equals("W")) {
         arr = wms
      }
      for(idx <- info(1).toInt to info(2).toInt) {
        arr(idx) += 1
      }
  }

  var max = 0

  for(i <- 0 to 366) {
    val cand = mens(i).max(wms(i))
    max = max.max(cand)
  }

println(max)

}


There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

The first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.

Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.

6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6

object P7B {
    def main(args : Array[String]) {
        val Array(t, m) = readLine split ' ' map {_.toInt}
        var b = collection.mutable.Buffer.fill(m){0}
        val curr = Iterator from 1
        val cAlloc = "alloc (.*)".r
        val cErase = "erase (.*)".r
        val cDefrag = "defragment".r
        for (_ <- 1 to t) readLine match {
            case cAlloc(nS) => {
                val n = nS.toInt
                val k = b.scanLeft(0){
                    (p0, x) => if (x == 0) p0 + 1 else 0
                }.indexWhere(_ >= n.toInt) - 1
                if (k >= 0) {
                    val x = curr.next
                    println(x)
                    for (i <- k - n + 1 to k) b(i) = x
                } else println("NULL")
            }
            case cErase(xS) => {
                val x = xS.toInt
                if (x > 0 && (b contains x)) {
                    b = b map {bi => if (bi == x) 0 else bi}
                } else println("ILLEGAL_ERASE_ARGUMENT")
            }
            case cDefrag() => {
                b = b filter {_ != 0}
                while (b.size < m) b += 0
            }
        }
    }
}

object P7B {
    def main(args : Array[String]) {
        val Array(t, m) = readLine split ' ' map {_.toInt}
        var b = collection.mutable.Buffer.fill(m){0}
        val curr = Iterator from 1
        val cAlloc = "alloc (.*)".r
        val cErase = "erase (.*)".r
        val cDefrag = "defragment".r
        for (_ <- 1 to t) readLine match {
            case cAlloc(nS) => {
                val n = nS.toInt
                val k = b.scanLeft(0){
                    (p0, x) => if (x == 0) p0 + 1 else 0
                }.indexWhere(_ >= n.toInt) - 1
                if (k >= 0) {
                    val x = curr.next
                    println(x)
                    for (i <- k - n + 1 to k) b(i) = x
                } else println("NULL")
                println(b)
            }
            case cErase(xS) => {
                val x = xS.toInt
                if (b contains x) {
                    b = b map {bi => if (bi == x) 0 else bi}
                } else println("ILLEGAL_ERASE_ARGUMENT")
                println(b)
            }
            case cDefrag() => {
                b = b filter {_ != 0}
                while (b.size < m) b += 0
                println(b)
            }
        }
    }
}

object P7B {
    def main(args : Array[String]) {
        val Array(t, m) = readLine split ' ' map {_.toInt}
        var b = collection.mutable.Buffer.fill(m){0}
        val curr = Iterator from 1
        val cAlloc = "alloc (.*)".r
        val cErase = "erase (.*)".r
        val cDefrag = "defragment".r
        for (_ <- 1 to t) readLine match {
            case cAlloc(nS) => {
                val n = nS.toInt
                val k = b.scanLeft(0){
                    (p0, x) => if (x == 0) p0 + 1 else 0
                }.indexWhere(_ >= n.toInt) - 1
                if (k >= 0) {
                    val x = curr.next
                    println(x)
                    for (i <- k - n + 1 to k) b(i) = x
                } else println("NULL")
            }
            case cErase(xS) => {
                val x = xS.toInt
                if (b contains x) {
                    b = b map {bi => if (bi == x) 0 else bi}
                } else println("ILLEGAL_ERASE_ARGUMENT")
            }
            case cDefrag() => {
                b = b filter {_ != 0}
                while (b.size < m) b += 0
            }
        }
    }
}


You are given a multiset (i. e. a set that can contain multiple equal integers) containing $$$2n$$$ integers. Determine if you can split it into exactly $$$n$$$ pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by $$$2$$$, the remainder is $$$1$$$).

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\leq n\leq 100$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1,a_2,\dots, a_{2n}$$$ ($$$0\leq a_i\leq 100$$$) — the numbers in the set.

For each test case, print "Yes" if it can be split into exactly $$$n$$$ pairs so that the sum of the two elements in each pair is odd, and "No" otherwise. You can print each letter in any case.

NoteIn the first test case, a possible way of splitting the set is $$$(2,3)$$$, $$$(4,5)$$$.In the second, third and fifth test case, we can prove that there isn't any possible way.In the fourth test case, a possible way of splitting the set is $$$(2,3)$$$.

import scala.io.StdIn._

object A extends App {
  for (_ <- 0 until readInt) {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    if (a.count(_ % 2 != 0) == n)
      println("Yes")
    else
      println("No")
  }
}

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

  val t = readInt()

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

    val ans = an.count(_ % 2 == 1) == an.count(_ % 2 == 0)

    ans match {
      case true => println("Yes")
      case _    => println("No")
    }
  }
}


You are given strings $$$S$$$ and $$$T$$$, consisting of lowercase English letters. It is guaranteed that $$$T$$$ is a permutation of the string abc. Find string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.String $$$a$$$ is a permutation of string $$$b$$$ if the number of occurrences of each distinct character is the same in both strings.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a string $$$S$$$ ($$$1 \le |S| \le 100$$$), consisting of lowercase English letters. The second line of each test case contains a string $$$T$$$ that is a permutation of the string abc. (Hence, $$$|T| = 3$$$). Note that there is no limit on the sum of $$$|S|$$$ across all test cases.

For each test case, output a single string $$$S'$$$, the lexicographically smallest permutation of $$$S$$$ such that $$$T$$$ is not a subsequence of $$$S'$$$.

7
abacaba
abc
cccba
acb
dbsic
bac
abracadabra
abc
dddddddddddd
cba
bbc
abc
ac
abc

aaaacbb
abccc
bcdis
aaaaacbbdrr
dddddddddddd
bbc
ac

NoteIn the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence.

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val s = readLine()
    val t = readLine()
    val aCount = s.count(_ == 'a')
    val bCount = s.count(_ == 'b')
    val cCount = s.count(_ == 'c')

    val answer = if (aCount == 0 || bCount == 0 || cCount == 0) s.sorted else {
      val remainingString = s.filter(c => c != 'a' && c != 'b' && c != 'c').sorted.mkString("")

      def mkFragment(count: Int, letter: Char) = 1.to(count).map(_ => letter).mkString

      val prefix = if (t != "abc") mkFragment(aCount, 'a') + mkFragment(bCount, 'b') + mkFragment(cCount, 'c')
      else mkFragment(aCount, 'a') + mkFragment(cCount, 'c') + mkFragment(bCount, 'b')
      prefix + remainingString
    }

    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val s = readLine()
    val t = readLine()
    val aCount = s.count(_ == 'a')
    val bCount = s.count(_ == 'b')
    val cCount = s.count(_ == 'c')
    val remainingString = s.filter(c => c != 'a' && c != 'b' && c != 'c').sorted.mkString("")

    def mkFragment(count: Int, letter: Char) = 1.to(count).map(_ => letter).mkString

    val answer = if (aCount == 0 || bCount == 0 || cCount == 0) s else {
      val prefix = if (t != "abc") mkFragment(aCount, 'a') + mkFragment(bCount, 'b') + mkFragment(cCount, 'c')
      else mkFragment(aCount, 'a') + mkFragment(cCount, 'c') + mkFragment(bCount, 'b')
      prefix + remainingString
    }

    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.

First line contains three integers n, k and m (2 ≤ k ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers. Second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the numbers in the multiset.

If it is not possible to select k numbers in the desired way, output «No» (without the quotes). Otherwise, in the first line of output print «Yes» (without the quotes). In the second line print k integers b1, b2, ..., bk — the selected numbers. If there are multiple possible solutions, print any of them.

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

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

    //COMMENT ME !
    runTest(Test.sa3)
    debugV = true
//    file = File("C:\\temp\\google cj\\2014q\\c-small.res")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val k = l1.int
    val m = l1.int
    val l2 = readLine
    val numbers = (1 to n).map(x => l2.int).toArray.sorted

    val groups = numbers.groupBy(x => x % m)
    val max = groups.values.reduce((a,b) => if (a.size > b.size) a else b)

    debug("max = " + max.mkString(" "))

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

    val res = if (max.size >= k) {
      "Yes\n" + max.take(k).mkString(" ")
    } else {
      "No"
    }

    outLn(res)
    finish
  }

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

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

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

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

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

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

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

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

val sa1 = """
3 2 3
1 8 4
"""

val sa2 = """
3 3 3
1 8 4
"""

val sa3 = """
4 3 5
2 7 7 7
"""
}

}


Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.

The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000). The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.

Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.

NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.

import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val a = StdIn.readLine()
  val b = StdIn.readLine()

  def binaryCount(s: String): (Long, Long) = {
    var i, j = 0l
    s.foreach {
      case '0' => i += 1
      case _ => j += 1
    }
    i -> j
  }
  val initialSub = b.take(b.length - a.length + 1)
  val (headIt, nextIt) = (b.iterator, b.substring(initialSub.length).iterator)
  var (count0, count1) = binaryCount(initialSub)

  val listOfDist = {
    for {
      c <- a
    } yield {
      val dist = c match {
        case '0' => count1
        case '1' => count0
      }

      if (nextIt.hasNext) {
        headIt.next() match {
          case '0' => count0 -= 1
          case '1' => count1 -= 1
        }

        nextIt.next() match {
          case '0' => count0 += 1
          case '1' => count1 += 1
        }
      }

      dist
    }
  }

  println(listOfDist.sum)
}

import java.util.Scanner

object CF2 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val as = sc.nextLine()
    val bs = sc.nextLine()
    val a = as.toCharArray
    val b = bs.toCharArray
    var b0 = 0L
    var b1 = 0L
    val lengthDiff = b.length - a.length
    for (i <- 0 to lengthDiff)
      if (b(i) == '0') b0 += 1 else b1 += 1
    var sum = 0L
    for (i <- 0 to a.length - 1) {
      if (a(i) == '0') sum += b1 else sum += b0
      if (i != a.length - 1) {
        if (b(i) == '0') b0 -= 1 else b1 -= 1
        if (b(lengthDiff + i + 1) == '0') b0 += 1 else b1 += 1
      }
    }
    System.out.print(sum)
  }
}

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

object B_336 {

  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 a = br.readLine()
    val b = br.readLine()

    val itN = b.length() - a.length() + 1
    db(itN+"")
    val sums = new Array[Int](b.length())

    var total = 0l

    var curSum = 0
    for (i <- 0 until b.length()) {
      curSum += value(b, i)
      sums(i) = curSum
      db(i + " - " + sums(i))
    }

    for (i <- 0 until a.length()) {
      val vv = value(a, i)
      var dSum = sums(itN-1+i)
      if (i > 0) {
        dSum -= sums(i-1)
      }
      var dif = 0
      if (vv == 0) {
        dif = dSum
      } else {
        dif = itN - dSum
      }
      total += dif
    }

    def value(str:String, ind:Int) = if (str.charAt(ind) == '0') 0 else 1

    println(total)

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

  }

  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
    def hasNext = tok.hasMoreElements()
  }

  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 = """
01
101
"""

val sa2 = """
0
101
"""

val sa3 = """
1
101
"""

}

}

import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val a = StdIn.readLine()
  val b = StdIn.readLine()

  def binaryCount(s: String): (Int, Int) = {
    var i, j = 0
    s.foreach {
      case '0' => i += 1
      case _ => j += 1
    }
    i -> j
  }
  val initialSub = b.take(b.length - a.length + 1)
  val (headIt, nextIt) = (b.iterator, b.substring(initialSub.length).iterator)
  var (count0, count1) = binaryCount(initialSub)

  val listOfDist = {
    for {
      c <- a
    } yield {
      val dist = c match {
        case '0' => count1
        case '1' => count0
      }

      if (nextIt.hasNext) {
        headIt.next() match {
          case '0' => count0 -= 1
          case '1' => count1 -= 1
        }

        nextIt.next() match {
          case '0' => count0 += 1
          case '1' => count1 += 1
        }
      }

      dist
    }
  }

  println(listOfDist.sum)
}

import java.util.Scanner

object CF2 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val as = sc.nextLine()
    val bs = sc.nextLine()
    val a = as.toCharArray
    val b = bs.toCharArray
    var b0 = 0
    var b1 = 0
    val lengthDiff = b.length - a.length
    for (i <- 0 to lengthDiff)
      if (b(i) == '0') b0 += 1 else b1 += 1
    var sum = 0
    for (i <- 0 to a.length - 1) {
      if (a(i) == '0') sum += b1 else sum += b0
      if (i != a.length - 1) {
        if (b(i) == '0') b0 -= 1 else b1 -= 1
        if (b(lengthDiff + i + 1) == '0') b0 += 1 else b1 += 1
      }
    }
    System.out.print(sum)
  }
}

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

object B_336 {

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

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

    //---------------------------- parameters reading --------------------------
    val a = br.readLine()
    val b = br.readLine()

    val itN = b.length() - a.length() + 1
    db(itN+"")
    val sums = new Array[Int](b.length())

    var total = 0

    var curSum: Integer = 0
    for (i <- 0 until b.length()) {
      curSum += value(b, i)
      sums(i) = curSum
    }

    for (i <-0 until a.length()) {
      val vv = value(a, i)
      var dif = 0
      if (vv == 0) {
        dif = sums(itN-1+i)
      } else {
        dif = itN - sums(itN-1+i)
      }
      total += dif
    }

//    var total = 0l
//    var curSum = 0l
//    val
//
//    for(i <- 0 until itN) {
////      if (i == 0) {
//      curSum = 0
//        for (j <- 0 until a.length()) {
//          val dist = Math.abs(value(a, j) - value(b, j+i))
//          curSum += dist
//        }
//      db("- " + curSum)
////      } else {
////        curSum -= Math.abs(value(a, j) - value(b, j))
////      }
//      total += curSum
//
//    }

    def value(str:String, ind:Int) = if (str.charAt(ind) == '0') 0 else 1

    println(total)

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

  }

  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
    def hasNext = tok.hasMoreElements()
  }

  var debugV = false
  var is = System.in
  val 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 = """

"""

}

}

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

object B_336 {

  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 a = br.readLine()
    val b = br.readLine()

    val itN = b.length() - a.length() + 1
    db(itN+"")
    val sums = new Array[Int](b.length())

    var total = 0

    var curSum: Integer = 0
    for (i <- 0 until b.length()) {
      curSum += value(b, i)
      sums(i) = curSum
      db(i + " - " + sums(i))
    }

    for (i <-0 until a.length()) {
      val vv = value(a, i)
      var dSum = sums(itN-1+i)
      if (i > 0) {
        dSum -= sums(i-1)
      }
      var dif = 0
      if (vv == 0) {
        dif = dSum
      } else {
        dif = itN - dSum
      }
      total += dif
    }

    def value(str:String, ind:Int) = if (str.charAt(ind) == '0') 0 else 1

    println(total)

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

  }

  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
    def hasNext = tok.hasMoreElements()
  }

  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 = """
01
101
"""

val sa2 = """
0
101
"""

val sa3 = """
1
101
"""

}

}


Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!A password is an array $$$a$$$ of $$$n$$$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $$$i$$$ such that $$$1 \leq i < n$$$ and $$$a_{i} \neq a_{i+1}$$$, delete both $$$a_i$$$ and $$$a_{i+1}$$$ from the array and put $$$a_{i}+a_{i+1}$$$ in their place. For example, for array $$$[7, 4, 3, 7]$$$ you can choose $$$i = 2$$$ and the array will become $$$[7, 4+3, 7] = [7, 7, 7]$$$. Note that in this array you can't apply this operation anymore.Notice that one operation will decrease the size of the password by $$$1$$$. What is the shortest possible length of the password after some number (possibly $$$0$$$) of operations?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the password. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — the initial contents of your password. The sum of $$$n$$$ over all test cases will not exceed $$$2 \cdot 10^5$$$.

For each password, print one integer: the shortest possible length of the password after some number of operations.

NoteIn the first test case, you can do the following to achieve a length of $$$1$$$:Pick $$$i=2$$$ to get $$$[2, 4, 1]$$$Pick $$$i=1$$$ to get $$$[6, 1]$$$Pick $$$i=1$$$ to get $$$[7]$$$In the second test case, you can't perform any operations because there is no valid $$$i$$$ that satisfies the requirements mentioned above.

object CodeforcesRound1392A {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    val a = rll_int
    val allAreEqual = a.forall(_ == a(0))
    val res = if (allAreEqual) n else 1
    writer.println(res)
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextInts(n)
      val d = as.distinct.size
      val res = if (d == 1) n else 1

      out.println(res)
    }

    out.flush()
  }

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

object CodeforcesRound1392A {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    val a = rll_int
    val res = if (n == 2 && a(0) == a(1)) 2 else 1
    writer.println(res)
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}


This is an easier version of the problem. In this version $$$n \le 1000$$$The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought $$$n$$$ plots along the highway and is preparing to build $$$n$$$ skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from $$$1$$$ to $$$n$$$. Then if the skyscraper on the $$$i$$$-th plot has $$$a_i$$$ floors, it must hold that $$$a_i$$$ is at most $$$m_i$$$ ($$$1 \le a_i \le m_i$$$). Also there mustn't be integers $$$j$$$ and $$$k$$$ such that $$$j < i < k$$$ and $$$a_j > a_i < a_k$$$. Plots $$$j$$$ and $$$k$$$ are not required to be adjacent to $$$i$$$.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of plots. The second line contains the integers $$$m_1, m_2, \ldots, m_n$$$ ($$$1 \leq m_i \leq 10^9$$$) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.

Print $$$n$$$ integers $$$a_i$$$ — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible. If there are multiple answers possible, print any of them.

NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer $$$[10, 6, 6]$$$ is optimal. Note that the answer of $$$[6, 6, 8]$$$ also satisfies all restrictions, but is not optimal.

case class Solution(sum: Long, heights: List[Long])

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val n = stdin.next().toInt
  val data = stdin.next().split(' ').map(_.toLong).toList
  val s1 = solve(data)
  val s2 = solve(data.reverse)
  val max = (0 to n).map(i => solve(data, i)).maxBy(_.sum)
  println(max.heights.mkString(" "))

  def solve(data: List[Long], index: Int): Solution = {
    val firstPart = solve(data.take(index).reverse)
    val secondPart = solve(data.drop(index - 1))
    firstPart.heights match {
      case Nil => secondPart
      case _ => Solution(firstPart.sum + secondPart.sum - firstPart.heights.head, firstPart.heights.tail.reverse ::: secondPart.heights)
    }
  }

  def solve(data: List[Long]): Solution =
    data match {
      case Nil => Solution(0, Nil)
      case _ => val heights = data.tail.foldLeft(data.head, List(data.head)) {
        case ((max, list), nHeigh) => (Math.min(max, nHeigh), Math.min(max, nHeigh) :: list)
         }._2.reverse
        Solution(heights.sum, heights)
    }
}

case class Solution(sum: Long, heights: List[Long])

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val n = stdin.next().toInt
  val data = stdin.next().split(' ').map(_.toLong).toList
  val s1 = solve(data)
  val s2 = solve(data.reverse)
  val max = (0 to n).map(i => solve(data, i)).maxBy(_.sum)
  println(max.heights.mkString(" "))

  def solve(data: List[Long], index: Int): Solution = {
    val firstPart = solve(data.take(index).reverse)
    val secondPart = solve(data.drop(index - 1))
    firstPart.heights match {
      case Nil => secondPart
      case _ => Solution(firstPart.sum + secondPart.sum, firstPart.heights.tail.reverse ::: secondPart.heights)
    }
  }

  def solve(data: List[Long]): Solution =
    data match {
      case Nil => Solution(0, Nil)
      case _ => val heights = data.tail.foldLeft(data.head, List(data.head)) {
        case ((max, list), nHeigh) => (Math.min(max, nHeigh), Math.min(max, nHeigh) :: list)
         }._2.reverse
        Solution(heights.sum, heights)
    }
}

case class Solution(sum: Int, heights: List[Int])

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val n = stdin.next().toInt
  val data = stdin.next().split(' ').map(_.toInt).toList
  val s1 = solve(data)
  val s2 = solve(data.reverse)
  val max = (0 to n).map(i => solve(data, i)).maxBy(_.sum)
  println(max.heights.mkString(" "))

  def solve(data: List[Int], index: Int): Solution = {
    val firstPart = solve(data.take(index).reverse)
    val secondPart = solve(data.drop(index - 1))
    firstPart.heights match {
      case Nil => secondPart
      case _ => Solution(firstPart.sum + secondPart.sum, firstPart.heights.tail.reverse ::: secondPart.heights)
    }
  }

  def solve(data: List[Int]): Solution =
    data match {
      case Nil => Solution(0, Nil)
      case _ => val heights = data.tail.foldLeft(data.head, List(data.head)) {
        case ((max, list), nHeigh) => (Math.min(max, nHeigh), Math.min(max, nHeigh) :: list)
         }._2.reverse
        Solution(heights.sum, heights)
    }
}


Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.

The first line contains an integer N (1 ≤ N ≤ 1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000.

In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars.

object P037A extends App {
  val n = readInt
  val a = readLine.split(' ').map(_.toInt)
  val b = a.groupBy(identity).map(x => (x._1, x._2.size))
  printf("%d %d\n", b.maxBy(x => x._2)._2, b.size)
}

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

object Towers {
  def main(args: Array[String]): Unit = {
    val inputStream = System.in
    val outputStream = System.out
    val in = new InputReader(inputStream)
    val out = new PrintWriter(outputStream)
    val solver = new Task()
    solver.solve(in, out)
    out.close()
  }

  class Task {
    def solve(in: InputReader, out: PrintWriter): Unit = {
      val n = in.nextInt()
      val a = Array.ofDim[Int](n)
      for (i <- 0 until n) a(i) = in.nextInt()
      val group = a.groupBy(x => x).values
      out.println(group.maxBy(x => x.length).length + " " + group.size)
    }
  }

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

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens) {
        try {
          tokenizer = new StringTokenizer(reader.readLine())
        } catch {
          case _: IOException => throw new RuntimeException
        }
      }
      tokenizer.nextToken()
    }

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

}

import java.util.Scanner
object Towers {

  val scanner = new Scanner(System.in)
  def main(args: Array[String]): Unit = {
    val c = scanner.nextInt();
    val res = ((1 to c) map {i => scanner.nextInt()});
    var count = res.map(a => res.count(x => x==a));
    print((Int.MinValue/: res) {(m:Int,c:Int)=> m max(res.count(a => a == c))})
    print(" ")
    var filtered = res.toSet
    println(filtered.size)
  }

}

import java.util.StringTokenizer

object _37A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).groupBy(i => i)
  println("%d %d".format(a.map(g => g._2.length).max, a.size))
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  in.next()
  val data = in.next().split(" ").groupBy(t => t)

  println(data.maxBy(t => t._2.length)._2.length + " " + data.size)
}

object Main
{
	def sort(xs: Array[Int]): Array[Int] =
	  if (xs.length <= 1) xs
	  else {
		val pivot = xs(xs.length / 2)
		Array.concat(
		  sort(xs filter (pivot >)),
			   xs filter (pivot ==),
		  sort(xs filter (pivot <)))
	  }

	def main(args:Array[String])
	{
		readLine;
		val a1 = sort(readLine.split(" ").map(i => i.toInt)).toList;
		val counts = sort((1 to 1000).map(i => a1.count(j => i == j )).toArray).toList;
		println(counts.last + " " + counts.count(i => i > 0))
	}
}

object A37 {
  @inline def read = scala.io.StdIn.readLine

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)

    val max = input.groupBy(identity).mapValues(_.length).maxBy(_._2)._2

    val diff = input.toSet.size

    println(s"$max $diff")
  }
}

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

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

  val N = sc.nextInt
  val bars = List.fill(N)(sc.nextInt).groupBy(identity[Int])
  val highest = bars.map(_._2.length).max
  val towers = bars.size

  out.println(List(highest, towers).mkString(" "))
  out.close
}

import java.io._
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)

  reader.readLine()
  val ans = readInts.groupBy(x => x).values.map(_.size)

  def main(a: Array[String]) {
    println(ans.max + " " + ans.size)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(n => map(n) = map.getOrElse(n, 0) + 1)
    println(map.values.max + " " + map.size)
  }
}

object Andrei {
  def main (args : Array[String]) {
    val n = readInt
    var A = readLine().split(" ").map(_.toInt)

    val w = A.distinct
    val T = w.map(x => A.count(_ == x))
    println(T.max + " " + w.size)

  }

}

object Andrei {
  def main (args : Array[String]) {
    val n = readInt
    val A = readLine().split(" ").map(_.toInt)

    def swap(a : Int, b : Int) {
      val temp = A(a)
      A(a) = A(b)
      A(b) = temp
    }

    for(i <- 0 until n)
      for(j <- i until n)
        if(A(i) > A(j))
          swap(i, j)

    val w = A.distinct
    val T = w.map(x => A.count(_ == x))
    println(T.max + " " + w.size)

  }

}

object Andrei {
  class Heap {
    private type Node = Heap.Node
    private def Node(rank : Int, datum : Int, left : Node, right : Node) = new Node(rank, datum, left, right)
    private var root : Node = null

    private def mergeHeaps(a : Node, b : Node) : Node = {
      if(a == null) return b
      if(b == null) return a

      //keep the minimum up
      var x = a
      var y = b
      if(x.datum > y.datum) {
        val temp = x
        x = y
        y = temp
      }

      // completing the right part
      x.right = mergeHeaps(x.right, y)

      //keeping the balance
      if(x.left == null) {
        //left child doesn't exist we will therefore swap the 2
        x.left = x.right
        x.right = null
        x.rank = 1
      }
      else {
        //left child does exist, we therefore compare the 2 ranks
        if(x.left.rank < x.right.rank) {
          //we need to swap
          val temp = x.left
          x.left = x.right
          x.right = temp
        }
        x.rank = x.right.rank + 1
      }
      x
    }

    private def out(x : Node, level : Int) : Unit  = {
      if(x != null) {
        for(i <- 1 to level) print (" " )

        println(x.datum)
        if(x.left != null) {
          for(i <- 1 to level) print (" " )
          println("left")
          out(x.left, level + 1)
        }
        if(x.right != null) {
          println("right")
          for(i <- 1 to level) print (" " )
          out(x.right, level + 1)
        }
      }
    }

    def myprint = out(root, 0)

    def insert(x : Int) {
      root = mergeHeaps(root, Node(1, x, null, null))
    }

    def getMin : Int = {
      val min = root.datum
      root = mergeHeaps(root.right, root.left)
      min
    }
  }

  object Heap {
    private class Node(var rank : Int, var datum : Int, var left : Node, var right : Node)

    def apply(a : Array[Int]) = {
      val h = new Heap;
      a.foreach(h.insert(_))
      h
    }
  }

  def main (args : Array[String]) {
    val n = readInt
    val A = readLine().split(" ").map(_.toInt)

    val H = Heap(A)

    for(i <- 0 until n) A(i) = H.getMin

    var cnt = 1
    var nr = 1
    var max = 1
    for(i <- 1 until n)
      if(A(i - 1) != A(i)) {
        if(max < cnt) max = cnt
        cnt = 1
        nr += 1
      }
      else cnt += 1
    if(cnt > max) max = cnt
    println(max + " " + nr)

  }

}

object Andrei {
  class Heap {
    private type Node = Heap.Node
    private def Node(rank : Int, datum : Int, left : Node, right : Node) = new Node(rank, datum, left, right)
    private var root : Node = null

    private def mergeHeaps(a : Node, b : Node) : Node = {
      if(a == null) return b
      if(b == null) return a

      //keep the minimum up
      var x = a
      var y = b
      if(x.datum > y.datum) {
        val temp = x
        x = y
        y = temp
      }

      // completing the right part
      x.right = mergeHeaps(x.right, y)

      //keeping the balance
      if(x.left == null) {
        //left child doesn't exist we will therefore swap the 2
        x.left = x.right
        x.right = null
        x.rank = 1
      }
      else {
        //left child does exist, we therefore compare the 2 ranks
        if(x.left.rank < x.right.rank) {
          //we need to swap
          val temp = x.left
          x.left = x.right
          x.right = temp
        }
        x.rank = x.right.rank + 1
      }
      x
    }

    private def out(x : Node, level : Int) : Unit  = {
      if(x != null) {
        for(i <- 1 to level) print (" " )

        println(x.datum)
        if(x.left != null) {
          for(i <- 1 to level) print (" " )
          println("left")
          out(x.left, level + 1)
        }
        if(x.right != null) {
          println("right")
          for(i <- 1 to level) print (" " )
          out(x.right, level + 1)
        }
      }
    }

    def myprint = out(root, 0)

    def insert(x : Int) {
      root = mergeHeaps(root, Node(1, x, null, null))
    }

    def getMin : Int = {
      val min = root.datum
      root = mergeHeaps(root.right, root.left)
      min
    }
  }

  object Heap {
    private class Node(var rank : Int, var datum : Int, var left : Node, var right : Node)

    def apply(a : Array[Int]) = {
      val h = new Heap;
      a.foreach(h.insert(_))
      h
    }
  }

  def main (args : Array[String]) {
    val n = readInt
    val A = readLine().split(" ").map(_.toInt)

    val H = Heap(A)

    for(i <- 0 until n) A(i) = H.getMin

   val w = A.distinct
    val T = w.map(x => A.count(_ == x))
    println(T.max + " " + w.size)

  }
}

object Andrei {
  def main (args : Array[String]) {
    val n = readInt
    var A = readLine().split(" ").map(_.toInt)

    A = A.sortBy(x => x)
    var cnt = 1
    var nr = 1
    var max = 1
    for(i <- 1 until n)
      if(A(i - 1) != A(i)) {
        if(max < cnt) max = cnt
        cnt = 1
        nr += 1
      }
      else cnt += 1
    if(cnt > max) max = cnt
    println(max + " " + nr)

  }

}

object Main
{
	def sort(xs: Array[Int]): Array[Int] =
	  if (xs.length <= 1) xs
	  else {
		val pivot = xs(xs.length / 2)
		Array.concat(
		  sort(xs filter (pivot >)),
			   xs filter (pivot ==),
		  sort(xs filter (pivot <)))
	  }

	def main(args:Array[String])
	{
		readLine;
		val a1 = sort(readLine.split(" ").map(i => i.toInt)).toList;
		val counts = sort((1 to 1000).map(i => a1.count(j => i == j )).toArray).toList;
		println(counts.count(i => i > 0) + " " + counts.last)
	}
}

object Main
{
	def sort(xs: Array[Int]): Array[Int] =
	  if (xs.length <= 1) xs
	  else {
		val pivot = xs(xs.length / 2)
		Array.concat(
		  sort(xs filter (pivot >)),
			   xs filter (pivot ==),
		  sort(xs filter (pivot <)))
	  }

	def main(args:Array[String])
	{
		val a1 = sort(readLine.split(" ").map(i => i.toInt)).toList;
		val counts = sort((1 to 1000).map(i => a1.count(j => i == j )).toArray).toList;
		println(counts.count(i => i > 0) + " " + counts.last)
	}
}

object Andrei {
  def main (args : Array[String]) {
    val n = readInt
    var A = readLine().split(" ").map(_.toInt)

    A = A.sortBy(x => x)
    A.foreach(println(_))
    var cnt = 1
    var nr = 1
    var max = 1
    for(i <- 1 until n)
      if(A(i - 1) != A(i)) {
        if(max < cnt) max = cnt
        cnt = 1
        nr += 1
      }
      else cnt += 1

    println(max + " " + nr)

  }

}

object Andrei {
  def main (args : Array[String]) {
    val n = readInt
    var A = readLine().split(" ").map(_.toInt)

    A = A.sortBy(x => x)
    var cnt = 1
    var nr = 1
    var max = 1
    for(i <- 1 until n)
      if(A(i - 1) != A(i)) {
        if(max < cnt) max = cnt
        cnt = 1
        nr += 1
      }
      else cnt += 1

    println(max + " " + nr)

  }

}


Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the 2t pieces he ended up with t tickets, each of which was lucky.When Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest.Vasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123.What maximum number of tickets could Vasya get after that?

The first line contains integer n (1 ≤ n ≤ 104) — the number of pieces. The second line contains n space-separated numbers ai (1 ≤ ai ≤ 108) — the numbers on the pieces. Vasya can only glue the pieces in pairs. Even if the number of a piece is already lucky, Vasya should glue the piece with some other one for it to count as lucky. Vasya does not have to use all the pieces. The numbers on the pieces an on the resulting tickets may coincide.

Print the single number — the maximum number of lucky tickets that will be able to be restored. Don't forget that every lucky ticket is made of exactly two pieces glued together.

object P043C extends App {
  val n = readInt
  val a = readLine.split(' ').map(_.toInt)
  val r0 = a.count(_%3 == 0)
  val r1 = a.count(_%3 == 1)
  val r2 = a.count(_%3 == 2)
  println(r0/2 + math.min(r1, r2))
}


There are n stone quarries in Petrograd.Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik».

The first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.

Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise.

import java.util.Scanner

object Nim extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()
  val result = (0 until n).foldLeft(0L) {(acc, a) =>
    val xi = s.nextLong()
    val m = s.nextLong()
    val end = xi + m - 1
    acc ^ xoredSum(end) ^ xoredSum(xi - 1)
  }

  if (result > 0) {
    println("tolik")
  } else {
    println("bolik")
  }

  def xoredSum(a: Long): Long = {
    val b = a - 1
    (b - b % 4 to a).foldLeft(0L)(_ ^ _)
  }

}


The integers shop sells $$$n$$$ segments. The $$$i$$$-th of them contains all integers from $$$l_i$$$ to $$$r_i$$$ and costs $$$c_i$$$ coins.Tomorrow Vasya will go to this shop and will buy some segments there. He will get all integers that appear in at least one of bought segments. The total cost of the purchase is the sum of costs of all segments in it.After shopping, Vasya will get some more integers as a gift. He will get integer $$$x$$$ as a gift if and only if all of the following conditions are satisfied:   Vasya hasn't bought $$$x$$$.  Vasya has bought integer $$$l$$$ that is less than $$$x$$$.  Vasya has bought integer $$$r$$$ that is greater than $$$x$$$. Vasya can get integer $$$x$$$ as a gift only once so he won't have the same integers after receiving a gift.For example, if Vasya buys segment $$$[2, 4]$$$ for $$$20$$$ coins and segment $$$[7, 8]$$$ for $$$22$$$ coins, he spends $$$42$$$ coins and receives integers $$$2, 3, 4, 7, 8$$$ from these segments. He also gets integers $$$5$$$ and $$$6$$$ as a gift.Due to the technical issues only the first $$$s$$$ segments (that is, segments $$$[l_1, r_1], [l_2, r_2], \ldots, [l_s, r_s]$$$) will be available tomorrow in the shop.Vasya wants to get (to buy or to get as a gift) as many integers as possible. If he can do this in differents ways, he selects the cheapest of them.For each $$$s$$$ from $$$1$$$ to $$$n$$$, find how many coins will Vasya spend if only the first $$$s$$$ segments will be available.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of segments in the shop. Each of next $$$n$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$, $$$c_i$$$ ($$$1 \leq l_i \leq r_i \leq 10^9, 1 \leq c_i \leq 10^9$$$) — the ends of the $$$i$$$-th segments and its cost. It is guaranteed that the total sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case output $$$n$$$ integers: the $$$s$$$-th ($$$1 \leq s \leq n$$$) of them should be the number of coins Vasia will spend in the shop if only the first $$$s$$$ segments will be available.

NoteIn the first test case if $$$s = 1$$$ then Vasya can buy only the segment $$$[2, 4]$$$ for $$$20$$$ coins and get $$$3$$$ integers.The way to get $$$7$$$ integers for $$$42$$$ coins in case $$$s = 2$$$ is described in the statement.In the second test case note, that there can be the same segments in the shop.

object B extends App {
  val A = (1e9 + 1).toInt

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextInt()

    (0 until n).foldLeft((A, A), (0, A), (0, A)) { case (((l, lc), (r, rc), (s, sc)), _) =>
      val Array(li, ri, ci) = nextInts(3)
      val si                = ri - li + 1

      val (ln, lnc) =
        if (li < l) (li, ci)
        else if (li == l) (li, ci min lc)
        else (l, lc)

      val (rn, rnc) =
        if (ri > r) (ri, ci)
        else if (ri == r) (ri, ci min rc)
        else (r, rc)

      val (sn, snc) =
        if (si > s) (si, ci)
        else if (si == s) (si, ci min sc)
        else (s, sc)

      val cost =
        if (sn == rn - ln + 1) snc.min(lnc + rnc)
        else (lnc + rnc)

      out.println(cost)

      ((ln, lnc), (rn, rnc), (sn, snc))
    }

  }
  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {
  val A = (1e9 + 1).toInt

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextInt()

    (0 until n).foldLeft((A, A), (0, A), (0, A)) { case (((l, lc), (r, rc), (s, sc)), _) =>
      val Array(li, ri, ci) = nextInts(3)
      val si                = ri - li + 1

      val (ln, lnc) =
        if (li < l) (li, ci)
        else if (li == l) (li, ci min lc)
        else (l, lc)

      val (rn, rnc) =
        if (ri > r) (ri, ci)
        else if (ri == r) (ri, ri min rc)
        else (r, rc)

      val (sn, snc) =
        if (si > s) (si, ci)
        else if (si == s) (si, ci min sc)
        else (s, sc)

      val cost =
        if (sn == rn - ln + 1) snc min (lnc + rnc)
        else lnc + rnc

      out.println(cost)

      ((ln, lnc), (rn, rnc), (sn, snc))
    }

  }
  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {
  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextInt()

    val segments = Array.fill(n)((0, 0, 0))
    (0 until n).foreach { i =>
      val Array(li, ri, ci) = nextInts(3)
      segments(i) = (li, ri, ci)
    }

    val prefixes = segments.zipWithIndex.drop(1).scanLeft((0, 0)) {
      case ((p, q), ((li, ri, ci), i)) if p != q =>
        val (lp, _, cp) = segments(p)
        val (_, rq, cq) = segments(q)

        if (li == lp && ri == rq) if (ci <= cp + cq) (i, i) else (p, q)
        else if (li == lp && ri > rq || li < lp && ri == rq) (i, i)
        else
          (
            if (li < lp) i
            else if (li == lp) if (ci <= cp) i else p
            else p,
            if (ri > rq) i
            else if (ri == rq) if (ci <= cq) i else q
            else q
          )
      case ((j, _), ((li, ri, ci), i))           =>
        val (lj, rj, cj) = segments(j)

        if (li < lj && ri > rj) (i, i)
        else if (li < lj) (i, if (ri > rj) i else if (ri == rj) if (ci <= cj) i else j else j)
        else if (ri > rj) (if (li < lj) i else if (li == lj) if (ci <= cj) i else j else j, i)
        else (j, j)
    }

    val costs = prefixes.map {
      case (i, j) if i != j => segments(i)._3 + segments(j)._3
      case (i, _)           => segments(i)._3
    }

    costs.foreach(out.println)

  }
  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}


While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $$$H$$$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $$$L$$$ centimeters. Exactly at this point the flower touched the water surface.  Suppose that the lily grows at some point $$$A$$$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $$$A$$$. Also suppose that initially the flower was exactly above the point $$$A$$$, i.e. its stem was vertical. Can you determine the depth of the lake at point $$$A$$$?

The only line contains two integers $$$H$$$ and $$$L$$$ ($$$1 \le H < L \le 10^{6}$$$).

Print a single number — the depth of the lake at point $$$A$$$. The absolute or relative error should not exceed $$$10^{-6}$$$. Formally, let your answer be $$$A$$$, and the jury's answer be $$$B$$$. Your answer is accepted if and only if $$$\frac{|A - B|}{\max{(1, |B|)}} \le 10^{-6}$$$.

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 = {
    val H, L = ni()
    val a = (H.toDouble * H + L.toDouble * L) / 2 / H
    out.println(f"${a-H}%.13f")
  }
}

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

  override def apply(io: IO): io.type = {
    val h, l = io.read[Long]
    val a = (l*l - h*h)/(2.0 * h)
    io.write(a)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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

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


Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of n words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section).The rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph x (1 ≤ x ≤ c - 1) is replaced with hieroglyph (x + 1), and hieroglyph c is replaced with hieroglyph 1.Help archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically.

The first line of the input contains two integers n and c (2 ≤ n ≤ 500 000, 1 ≤ c ≤ 106) — the number of words, written on the lock, and the number of different hieroglyphs. Each of the following n lines contains the description of one word. The i-th of these lines starts with integer li (1 ≤ li ≤ 500 000), that denotes the length of the i-th word, followed by li integers wi, 1, wi, 2, ..., wi, li (1 ≤ wi, j ≤ c) — the indices of hieroglyphs that make up the i-th word. Hieroglyph with index 1 is the smallest in the alphabet and with index c — the biggest. It's guaranteed, that the total length of all words doesn't exceed 106.

If it is possible to open the door by rotating the round switch, print integer x (0 ≤ x ≤ c - 1) that defines the required number of clockwise rotations. If there are several valid x, print any of them. If it is impossible to open the door by this method, print  - 1.

NoteWord a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold:   at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character in the first position where they differ;  if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.In the first sample, after the round switch is rotated 1 position clockwise the words look as follows:1 323 1 23 1 2 3In the second sample, words are already sorted in lexicographical order.In the last sample, one can check that no shift of the alphabet will work.

import scala.io.StdIn

/**
  * Created by allen on 16-11-2.
  */
object Main {

  class SegT {
    var tag : Array[Int] = new Array[Int](1000002 * 2)
    var arr : Array[Int] = new Array[Int](1000002 * 2)
    def ida(l : Int, r : Int) : Int = (l + r) | (if(l != r) 1 else 0)
    def reset() : Unit = for(i <- 0 until 1000002*2) { arr(i) = 0; tag(i) = 0; }
    def pushdown(l : Int, r : Int) : Unit = {
      val id = ida(l, r)
      if(tag(id) != 0) {
        val mid = (l + r) >> 1
        val lc = ida(l, mid)
        if(lc != id) {
          tag(lc) += tag(id)
          arr(lc) += tag(id) * (mid - l + 1)
        }
        val rc = ida(mid + 1, r)
        if (mid + 1 <= r && rc != id) {
          tag(rc) += tag(id)
          arr(rc) += tag(id) * (r - mid)
        }
        tag(id) = 0
      }
    }
    def add(v : Int, ql : Int, qr : Int, l : Int, r : Int) : Unit = {
      val id = ida(l, r)
      pushdown(l, r)
      if(ql == l && qr == r) {
        tag(id) = tag(id) + v
        arr(id) = arr(id) + (r - l + 1) * v
        return
      }
      val m = l + r >> 1
      if(qr <= m) add(v, ql, qr, l, m)
      else if(m < ql) add(v, ql, qr, m + 1, r)
      else {
        add(v, ql, m, l, m)
        add(v, m + 1, qr, m + 1, r)
      }
    }

    def pushdownall(l : Int, r : Int) : Unit = {
      pushdown(l, r)
      if(l == r) return
      val m = l + r >> 1
      pushdownall(l, m)
      pushdownall(m + 1, r)
    }

    def query(l : Int, r : Int) : Int = arr(ida(l, r))

  }

  class Input(val n : Int, val c : Int, var arr : Array[Array[Int]]) {

  }

  def read(): Input = {
    val n::c::_ = StdIn.readLine().split(' ').map((a:String) => { a.toInt }).toList
    val arr = (for(i <- 0 until n) yield StdIn.readLine.split(' ').map((a:String) => { a.toInt }).drop(1)).toArray
    new Input(n, c, arr)
  }

  def alter(a1: Array[Int], a2: Array[Int]) : Unit = {
    val sz = if(a1.length < a2.length) a1.length else a2.length
    def x(): Boolean = {
      for (i <- 0 until sz) {
        //printf("%d vs %d \n", a1(i), a2(i))
        if (a1(i) != a2(i)) {
          if (a1(i) < a2(i)) {
            st.add(1, 0 + 1, dt.c - a2(i) + 1, 1, n + 1)
            //printf("[%d, %d]\n", 0, dt.c - a2(i))
            if (a1(i) > 1) {
              //printf("%d???", a1(i))
              st.add(1, 1 + dt.c - a1(i) + 1, 1 + dt.c - a1(i) + 1 + a1(i) - 2, 1, n + 1)
              //printf("[%d, %d]\n", dt.c - a1(i) + 1, dt.c - a1(i) + 1 + a1(i) - 2)
            }
            else Unit
          } else {
            val base = dt.c - a1(i) + 1; // base to 1
            st.add(1, 1 + base, 1 + dt.c - a2(i), 1, n + 1)

            //printf("[%d, %d]\n", base, dt.c - (a2(i)))
          }
          return true
        }
      }
      return false
    }
    if(!x && a1.length <= a2.length) {
      st.add(1, 1, n + 1, 1, n + 1)
      //printf("[%d, %d]\n", 0, n)
    }
    //printf("---\n")
  }

  var st = new SegT()
  val dt = read()
  val n = dt.c
  def main(args: Array[String]): Unit = {
    st.reset()
    for(i <- 1 until dt.n) {
      alter(dt.arr(i - 1), dt.arr(i))
    }
    st.pushdownall(1, n + 1)
    def x() : Unit = {
      for(i <- 1 to n + 1) {
        //printf("%d\n", st.query(i, i))
        if(st.query(i, i) == dt.n - 1) {
          printf("%d\n", i - 1)
          return
        }
      }
      printf("-1\n")
    }
    x()
  }
}

import scala.io.StdIn

/**
  * Created by allen on 16-11-2.
  */
object Main {

  class SegT {
    var tag : Array[Int] = new Array[Int](1000002 * 2)
    var arr : Array[Int] = new Array[Int](1000002 * 2)
    def ida(l : Int, r : Int) : Int = l + r | (if(l != r) 1 else 0)
    def reset() : Unit = for(i <- 0 until 1000002*2) { arr(i) = 0; tag(i) = 0; }
    def pushdown(l : Int, r : Int) : Unit = {
      val id = ida(l, r)
      if(tag(id) != 0) {
        val mid = l + r >> 1
        val lc = ida(l, mid)
        if(lc != id) {
          tag(lc) += tag(id)
          arr(lc) += tag(id) * (mid - l + 1)
        }
        val rc = ida(mid + 1, r)
        if (mid + 1 <= r && rc != id) {
          tag(rc) += tag(rc)
          arr(rc) += tag(id) * (r - mid)
        }
        tag(id) = 0
      }
    }
    def add(v : Int, ql : Int, qr : Int, l : Int, r : Int) : Unit = {
      val id = ida(l, r)
      pushdown(l, r)
      if(ql == l && qr == r) {
        tag(id) = tag(id) + v
        arr(id) = arr(id) + (r - l + 1) * v
        return
      }
      val m = l + r >> 1
      if(qr <= m) add(v, ql, qr, l, m)
      else if(m < ql) add(v, ql, qr, m + 1, r)
      else {
        add(v, ql, m, l, m)
        add(v, m + 1, qr, m + 1, r)
      }
    }

    def pushdownall(l : Int, r : Int) : Unit = {
      pushdown(l, r)
      val m = l + r >> 1
      pushdown(l, m)
      pushdown(m + 1, r)
      if(l == r) return
      pushdownall(l, m)
      pushdownall(m + 1, r)
    }

    def query(l : Int, r : Int) : Int = arr(ida(l, r))

  }

  class Input(val n : Int, val c : Int, var arr : Array[Array[Int]]) {

  }

  def read(): Input = {
    val n::c::_ = StdIn.readLine().split(' ').map((a:String) => { a.toInt }).toList
    val arr = (for(i <- 0 until n) yield StdIn.readLine.split(' ').map((a:String) => { a.toInt }).drop(1)).toArray
    new Input(n, c, arr)
  }

  def alter(a1: Array[Int], a2: Array[Int]) : Unit = {
    val sz = if(a1.length < a2.length) a1.length else a2.length
    def x(): Boolean = {
      for (i <- 0 until sz) {
        //printf("%d vs %d \n", a1(i), a2(i))
        if (a1(i) != a2(i)) {
          if (a1(i) < a2(i)) {
            st.add(1, 0 + 1, dt.c - a2(i) + 1, 1, n + 1)
            //printf("[%d, %d]\n", 0, dt.c - a2(i))
            if (a1(i) > 1) {
              //printf("%d???", a1(i))
              st.add(1, 1 + dt.c - a1(i) + 1, 1 + dt.c - a1(i) + 1 + a1(i) - 2, 1, n + 1)
              //printf("[%d, %d]\n", dt.c - a1(i), dt.c - a1(i) + 1 + a1(i) - 2)
            }
            else Unit
          } else {
            val base = dt.c - a1(i) + 1; // base to 1
            st.add(1, 1 + base, 1 + dt.c - a2(i), 1, n + 1)

            //printf("[%d, %d]\n", base, dt.c - (a2(i)))
          }
          return true
        }
      }
      return false
    }
    if(!x && a1.length <= a2.length) {
      st.add(1, 1, n + 1, 1, n + 1)
      //printf("[%d, %d]\n", 0, n)
    }
    //printf("---\n")
  }

  var st = new SegT()
  val dt = read()
  val n = dt.c
  def main(args: Array[String]): Unit = {
    st.reset()
    for(i <- 1 until dt.n) {
      alter(dt.arr(i - 1), dt.arr(i))
    }
    st.pushdownall(1, n + 1)
    def x() : Unit = {
      for(i <- 1 to n + 1) {
        //printf("%d\n", st.query(i, i))
        if(st.query(i, i) == dt.n - 1) {
          printf("%d\n", i - 1)
          return
        }
      }
      printf("-1\n")
    }
    x()
  }
}