Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.

The first line contains two integers n and f (1 ≤ n ≤ 105, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out. Each line of the following n subsequent lines contains two integers ki, li (0 ≤ ki, li ≤ 109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.

Print a single integer denoting the maximal number of products that shop can sell.

NoteIn the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out.

object B extends App {

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

  val Array(n, f) = readInts(2)
  case class Day(k: Long, l: Long)

  def sell(k: Long, l: Long) = {
    Math.min(k, l)
  }

  val days = Array.fill(n) {
    val Array(k, l) = readLongs(2)
    Day(k, l)
  }.sortBy {
    case Day(k, l) =>
      sell(2 * k, l) - sell(k, l)
  }.reverse

  val sale = days.take(f)
  val rest = days.drop(f)
  val res1 = sale.map {
    case Day(k, l) =>
      sell(2 * k, l)
  }.sum
  val res2 = rest.map {
    case Day(k, l) =>
      sell(k, l)
  }.sum

  println(res1 + res2)
}

object B extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toLong))
  val Array(n, f) = input(0).map(_.toInt)
  val days = input.drop(1)
  def doublingDiff(a: Array[Long]): Long = a match {
    case Array(prod, cust) =>
      val normalSale = cust min prod
      val doubleSale = cust min (prod * 2)
      doubleSale - normalSale
  }
  val fSum = if (f >= (n / 2))
    -days.view.map(a => -doublingDiff(a)).sorted.take(f).sum
  else
    days.view.map(a => doublingDiff(a)).sorted.drop(n - f).sum
  val normSum = days.map(_.min).sum
  print(fSum + normSum)
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, f = read[Int]

    val data = read[Seq, (Long, Long)](n) map {
      case (p, c) =>
        val sold = p min c
        val soldIfSale = 2*p min c
        (soldIfSale, sold, soldIfSale - sold)
    }

    val (sale, regular) = data.sortBy(_._3)(desc).splitAt(f)

    val ans = sale.sumWith(_._1) + regular.sumWith(_._2)

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

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

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

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

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

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

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

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

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

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

/**
  * @author tdx
  */
object Main {
  import scala.collection.mutable.ArrayBuffer
  import scala.io.StdIn._
  import scala.math._

  def parts(line : String) = {
    line.split(" ").map(_.toInt)
  }

  def cost(pair: (Int, Int)) = min(pair._1, pair._2)

  def main(args: Array[String]): Unit = {
    val p = parts(readLine())
    val (n, f) = (p(0), p(1))
    val arr = ArrayBuffer[(Int, Int)]()

    for (_ <- 1 to n) {
      val p = parts(readLine())
      val (ki, li) = (p(0), p(1))
      arr.append((ki, li))
    }

    val sorted = arr.sortBy {
      case (ki, li) => -(cost(2*ki, li) - cost(ki, li))
    }

    val all = arr.foldLeft(0L)((total, pair) => total + cost(pair)) +
      sorted.take(f).foldLeft(0L)((total, pair) => total + cost((2 * pair._1, pair._2)) - cost(pair))

    println(all)
  }

}

object B extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(n, f) = input(0)
  val days = input.drop(1)
  val sorted = days.sortBy{ case Array(prod, cust) =>
    val normalSale = cust min prod
    val doubleSale = cust min (prod * 2)
    -(doubleSale - normalSale)
  }

  val sumOne = sorted.take(f).map { case Array(prod, cust) =>
    cust min (prod * 2)
  }.sum

  val sumTwo = sorted.drop(f).map { case Array(prod, cust) =>
    cust min prod
  }.sum
  print(sumOne + sumTwo)
}

object B extends App {

  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toLong))
  val Array(n, f) = input(0).map(_.toInt)
  val days = input.drop(1)
  val normSum = days.map(_.min).sum
  if (f >= (n / 2)) {
    val fSumNeg = days.view.map{ case Array(prod, cust) =>
      val normalSale = cust min prod
      val doubleSale = cust min (prod * 2)
      -(doubleSale - normalSale)
    }.sorted.take(f).sum
    print(-fSumNeg + normSum)
  } else {
    val fSum = days.view.map{ case Array(prod, cust) =>
      val normalSale = cust min prod
      val doubleSale = cust min (prod * 2)
      doubleSale - normalSale
    }.sorted.drop(f).sum
    print(fSum + normSum)
  }
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, f = read[Int]

    val data = read[Seq, (Int, Int)](n) map {
      case (p, c) =>
        val sold = p min c
        val soldIfSale = 2*p min c
        (soldIfSale, sold)
    }

    val (sale, regular) = data.sorted(desc[(Int, Int)]).splitAt(f)

    val ans = sale.sumWith(_._1) + regular.sumWith(_._2)

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

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

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

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

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

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

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

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

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

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

/**
  * @author tdx
  */
object Main {
  import scala.collection.mutable.ArrayBuffer
  import scala.io.StdIn._
  import scala.math._

  def parts(line : String) = {
    line.split(" ").map(_.toInt)
  }

  def cost(pair: (Int, Int)) = min(pair._1, pair._2)

  def main(args: Array[String]): Unit = {
    val p = parts(readLine())
    val (n, f) = (p(0), p(1))
    val arr = ArrayBuffer[(Int, Int)]()

    for (_ <- 1 to n) {
      val p = parts(readLine())
      val (ki, li) = (p(0), p(1))
      arr.append((ki, li))
    }

    val sorted = arr.sortBy {
      case (ki, li) => -(cost(2*ki, li) - cost(ki, li))
    }

    val all = arr.foldLeft(0)((total, pair) => total + cost(pair)) +
      sorted.take(f).foldLeft(0)((total, pair) => total + cost((2 * pair._1, pair._2)) - cost(pair))

    println(all)
  }

}


Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made. Value of x is calculated as maximum of p·ai + q·aj + r·ak for given p, q, r and array a1, a2, ... an such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.

First line of input contains 4 integers n, p, q, r ( - 109 ≤ p, q, r ≤ 109, 1 ≤ n ≤ 105). Next line of input contains n space separated integers a1, a2, ... an ( - 109 ≤ ai ≤ 109).

Output a single integer the maximum value of p·ai + q·aj + r·ak that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.

NoteIn the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.

//http://codeforces.com/contest/855/problem/B
object B extends App {

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

  val Array(_n, p, q, r) = readLongs(4)
  val n = _n.toInt
  val as = readInts(n)

  var dp, dq, dr = Long.MinValue

  for (a <- as) {
    dp = dp max (p * a)
    dq = dq max (dp + q * a)
    dr = dr max (dq + r * a)
  }

  println(dr)
}


In an ICPC contest, balloons are distributed as follows:   Whenever a team solves a problem, that team gets a balloon.  The first team to solve a problem gets an additional balloon.  A contest has 26 problems, labelled $$$\textsf{A}$$$, $$$\textsf{B}$$$, $$$\textsf{C}$$$, ..., $$$\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.

For each test case, output a single integer — the total number of balloons that the teams received.

6

3

ABA

1

A

3

ORZ

5

BAAAA

4

BKPT

10

CODEFORCES

NoteIn the first test case, $$$5$$$ balloons are given out:   Problem $$$\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.  Problem $$$\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{B}$$$.  Problem $$$\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\textsf{A}$$$.  The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.

import scala.io.StdIn._
object Main extends App{
  var x=readInt()
  Range(0,x).foreach{_=>
    val y=readInt()
    val z=readLine()
    println(z.length+z.distinct.length)
  }
}


Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Polo the Penguin have two positive integers l and r (l < r), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other.Let's assume that n is the number of distinct lucky numbers, each of them cannot be greater than r or less than l, and ai is the i-th (in increasing order) number of them. Find a1·a2 + a2·a3 + ... + an - 1·an. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).

The first line contains a positive integer l, and the second line contains a positive integer r (1 ≤ l < r ≤ 10100000). The numbers are given without any leading zeroes. It is guaranteed that the lengths of the given numbers are equal to each other and that both of them are lucky numbers.

In the single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).

import io.Source
import java.io.PrintWriter

object CF288E {

  val MOD = 1000000007L

  case class D(u: Long, v: Long, w: Long, first: Long, last: Long) {
    def combine(o: D) = {
      D(
        (u + o.u + 1) % MOD,
        (v + o.v + last + o.first) % MOD,
        (w + o.w + last * o.first) % MOD,
        first,
        o.last
      )
    }

    def shift(add: Long) = {
      D(u, (v + 2 * (u * add % MOD)) % MOD, (w + (u * (add * add % MOD) % MOD) + v * add) % MOD, (first + add) % MOD, (last + add) % MOD)
    }
  }

  def solve(in: In, out: PrintWriter) {
    val s1, s2 = in()
    if (s1 == s2) {
      out.println(0)
      return
    }
    val n = s1.size
    val d = Array.ofDim[D](n)
    d(0) = D(0, 0, 0, 0, 0)
    val pow10 = Array.ofDim[Long](n + 1)
    pow10(0) = 1
    for (i <- 1 to n) {
      pow10(i) = (pow10(i - 1) * 10) % MOD
    }
    for (i <- 1 until n) {
      d(i) = d(i - 1).shift((4 * pow10(i - 1)) % MOD).combine(d(i - 1).shift((7 * pow10(i - 1)) % MOD))
    }
    def ss(s: String) = {
      val r = Array.ofDim[Long](n + 1)
      for (i <- 0 until n) {
        r(i + 1) = (r(i) * 10 + s(i) - '0') % MOD
      }
      for (i <- 0 to n) {
        r(i) = (r(i) * pow10(n - i)) % MOD
      }
      r
    }
    val s1s = ss(s1)
    val s2s = ss(s2)
    var ans: D = D(0, 0, 0, s1s(n), s1s(n))
    var fd = 0
    while (s1(fd) == s2(fd)) {
      fd += 1
    }
//    out.println(d.deep, s1s.deep, s2s.deep, ans)
    assert(s1(fd) == '4' && s2(fd) == '7')
    for (i <- (n - 1).until(fd, -1)) {
      if (s1(i) == '4') {
        val shift: D = d(n - i - 1).shift((s1s(i) + 7 * pow10(n - i - 1)) % MOD)
        ans = ans.combine(shift)
//        out.println(shift, ans)
      }
    }
    val it4 = Array.ofDim[Long](n + 1)
    it4(0) = 0
    for (i <- 1 to n) {
      it4(i) = (it4(i - 1) * 10 + 4) % MOD
    }
    for (i <- (fd + 1) until n) {
      if (s2(i) == '7') {
        val shift: D = d(n - i - 1).shift((s2s(i) + 4 * pow10(n - i - 1)) % MOD)
        ans = ans.combine(shift)
//        out.println(shift, ans)
      }
    }
    val shift: D = D(0, 0, 0, s2s(n), s2s(n))
    ans = ans.combine(shift)
//    out.println(shift, ans)
    out.println(ans.w)
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

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

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

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

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

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

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

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

    def apply() = tokenIterator.next()

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

import io.Source
import java.io.PrintWriter

object CF288E {

  val MOD = 1000000007L

  case class D(u: Long, v: Long, w: Long, count: Long, first: Long, last: Long) {
    def combine(o: D) = {
      D(
        (u + o.u + 1) % MOD,
        (v + o.v + last + o.first) % MOD,
        (w + o.w + last * o.first) % MOD,
        (count + o.count) % MOD,
        first,
        o.last
      )
    }

    def shift(add: Long) = {
      D(u, (v + 2 * u * add) % MOD, (w + u * (add * add % MOD) + v * add) % MOD, count, (first + add) % MOD, (last + add) % MOD)
    }
  }

  def solve(in: In, out: PrintWriter) {
    val s1, s2 = in()
    if (s1 == s2) {
      out.println(0)
      return
    }
    val n = s1.size
    val d = Array.ofDim[D](n)
    d(0) = D(0, 0, 0, 1, 0, 0)
    val pow10 = Array.ofDim[Long](n + 1)
    pow10(0) = 1
    for (i <- 1 to n) {
      pow10(i) = (pow10(i - 1) * 10) % MOD
    }
    for (i <- 1 until n) {
      d(i) = d(i - 1).shift(4 * pow10(i - 1)).combine(d(i - 1).shift(7 * pow10(i - 1)))
    }
    def ss(s: String) = {
      val r = Array.ofDim[Long](n + 1)
      for (i <- 0 until n) {
        r(i + 1) = (r(i) * 10 + s(i) - '0') % MOD
      }
      for (i <- 0 to n) {
        r(i) = (r(i) * pow10(n - i)) % MOD
      }
      r
    }
    val s1s = ss(s1)
    val s2s = ss(s2)
    var ans: D = D(0, 0, 0, 1, s1s(n), s1s(n))
    var fd = 0
    while (s1(fd) == s2(fd)) {
      fd += 1
    }
//    out.println(d.deep, s1s.deep, s2s.deep, ans)
    assert(s1(fd) == '4' && s2(fd) == '7')
    for (i <- (n - 1).until(fd, -1)) {
      if (s1(i) == '4') {
        val shift: D = d(n - i - 1).shift((s1s(i) + 7 * pow10(n - i - 1)) % MOD)
        ans = ans.combine(shift)
//        out.println(shift, ans)
      }
    }
    val it4 = Array.ofDim[Long](n + 1)
    it4(0) = 0
    for (i <- 1 to n) {
      it4(i) = (it4(i - 1) * 10 + 4) % MOD
    }
    for (i <- (fd + 1) until n) {
      if (s2(i) == '7') {
        val shift: D = d(n - i - 1).shift((s2s(i) + 4 * pow10(n - i - 1)) % MOD)
        ans = ans.combine(shift)
//        out.println(shift, ans)
      }
    }
    val shift: D = D(0, 0, 0, 1, s2s(n), s2s(n))
    ans = ans.combine(shift)
//    out.println(shift, ans)
    out.println(ans.w)
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

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

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

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

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

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

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

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

    def apply() = tokenIterator.next()

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


A big football championship will occur soon! $$$n$$$ teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game:  the game may result in a tie, then both teams get $$$1$$$ point;  one team might win in a game, then the winning team gets $$$3$$$ points and the losing team gets $$$0$$$ points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case is described by one line containing one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of teams.

For each test case, print $$$\frac{n(n - 1)}{2}$$$ integers describing the results of the games in the following order: the first integer should correspond to the match between team $$$1$$$ and team $$$2$$$, the second — between team $$$1$$$ and team $$$3$$$, then $$$1$$$ and $$$4$$$, ..., $$$1$$$ and $$$n$$$, $$$2$$$ and $$$3$$$, $$$2$$$ and $$$4$$$, ..., $$$2$$$ and $$$n$$$, and so on, until the game between the team $$$n - 1$$$ and the team $$$n$$$. The integer corresponding to the game between the team $$$x$$$ and the team $$$y$$$ should be $$$1$$$ if $$$x$$$ wins, $$$-1$$$ if $$$y$$$ wins, or $$$0$$$ if the game results in a tie. All teams should get the same score, and the number of ties should be the minimum possible. If there are multiple optimal answers, print any of them. It can be shown that there always exists a way to make all teams have the same score.

NoteIn the first test case of the example, both teams get $$$1$$$ point since the game between them is a tie.In the second test case of the example, team $$$1$$$ defeats team $$$2$$$ (team $$$1$$$ gets $$$3$$$ points), team $$$1$$$ loses to team $$$3$$$ (team $$$3$$$ gets $$$3$$$ points), and team $$$2$$$ wins against team $$$3$$$ (team $$$2$$$ gets $$$3$$$ points).

//package codeforces.contests._1487

object MinimumTies {

  def main(args: Array[String]): Unit = {
    println({
      for (_ <- 1 to io.StdIn.readInt()) yield {
        val n = io.StdIn.readInt()

        val EachTeamWins = (n - 1) / 2

        val teamWins = Array.fill(n + 1)(0)

        def drawCheck(i: Int, j: Int): Boolean = n % 2 == 0 && (j - i) == n / 2

        {
          for {
            i <- 1 to n
            j <- i + 1 to n
          } yield {
            if (drawCheck(i, j)) 0
            else if (teamWins(i) < EachTeamWins) {
              teamWins(i) += 1
              1
            } else if (teamWins(j) < EachTeamWins) {
              teamWins(j) += 1
              -1
            } else {
              0
            }
          }
        }.mkString(" ")
      }
    }.mkString("\n"))
  }
}

object C {
  import scala.io.{StdIn => in}

  def main(args: Array[String]): Unit = {
    val tests = in.readInt()
    (1 to tests).foreach { _ =>
      val n = in.readInt() - 1
      val wins = (0 until n/2).map(_ => 1) ++ (if (n % 2 == 0) Seq() else Seq(0)) ++ (0 until n/2).map(_ => -1)
      println((0 to n).map(i => wins.dropRight(i).mkString(" ")).mkString(" "))
    }
  }
}

import scala.collection.mutable.ArrayBuffer

object C {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val games = Array.fill(n, n)(0)
      val scores = ArrayBuffer.empty[Int]
      for (i <- 0 until n) {
        var res = if (i % 2 == 0) 1 else -1
        for (j <- 0 until n) {
          if (i != j) {
            var r = 0
            if ((n % 2 == 1 || (i != n - j - 1))) {
              r = res
              res = -res
            }
            if (i < j) scores += r
            games(i)(j) = r
          }
        }
      }

      out.println(scores.mkString(" "))
    }

    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
  }

}

//package codeforces.contests._1487

object MinimumTies {

  def main(args: Array[String]): Unit = {
    println({
      for (_ <- 1 to io.StdIn.readInt()) yield {
        val n = io.StdIn.readInt()

        val EachTeamWins = (n - 1) / 2

        val teamWins = Array.fill(n + 1)(0)

        {
          for {
            i <- 1 to n
            j <- i + 1 to n
          } yield {
            if (teamWins(i) < EachTeamWins) {
              teamWins(i) += 1
              1
            } else if (teamWins(j) < EachTeamWins) {
              teamWins(j) += 1
              -1
            } else {
              0
            }
          }
        }.mkString(" ")
      }
    }.mkString("\n"))
  }
}


Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by 2. Fangy knows that for any positive integer number the process ends in finite time.How many actions should Fangy perform to get a number one from number x?

The first line contains a positive integer x in a binary system. It is guaranteed that the first digit of x is different from a zero and the number of its digits does not exceed 106.

NoteLet's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1.

import scala.collection.mutable
object BinaryNumber extends App {
  val input = io.Source.stdin.getLines.next

  var numOps = 0
  var tail = 0
  var specialOnes = -1
  input foreach { char =>
    if(char == '0') {
      if(specialOnes == 0) specialOnes = 1 // we are in the first thing of zeros after single 1
      numOps += 2
      tail += 1
    } else {
      if(specialOnes == -1) specialOnes = 0 // we have processed a single 1, that's all
      else if(specialOnes == 0) specialOnes = -2 // fail: more than one 1 at beginning
      else if(specialOnes == 1) specialOnes = -2 // fail: more ones after zeros
      numOps += 1
      tail = 0
    }
  }
  numOps -= (tail - 1)
  if(specialOnes != -2) numOps -= 2
  println(numOps)
}

import scala.collection.mutable
object BinaryNumber extends App {
  val input = io.Source.stdin.getLines.next
  var numOps = -1
  var tail = -1
  input foreach { char =>
    numOps += 2
    if(char == '0') tail = math.max(tail + 1, 1)
    else {
      if(tail == 0) numOps -= 1
      tail = 0
    }
  }
  numOps -= math.max(1, tail)
  println(numOps)
}

import scala.collection.mutable
object BinaryNumber extends App {
  val input = io.Source.stdin.getLines.next

  var numOps = 0
  var tail = 0
  var moreOnes = -1
  input foreach { char =>
    if(char == '0') {
      if(moreOnes == -1) moreOnes = 0
      numOps += 2
      tail += 1
    } else {
      if(moreOnes == 0) moreOnes = 1
      numOps += 1
      tail = 0
    }
  }
  numOps -= (tail - 1)
  if(moreOnes != 1) numOps -= 2
  println(numOps)
}

import scala.collection.mutable
object BinaryNumber extends App {
  val input = io.Source.stdin.getLines.next

  var numOps = -1
  var tail = -1
  var hasZero = false
  input foreach { char =>
    numOps += 2
    if(char == '0') {
      tail = math.max(tail + 1, 1)
      hasZero = true
    } else {
      if(tail == 0) numOps -= 1
      tail = 0
    }
  }
  numOps -= math.max(1, tail)
  if(!hasZero) numOps += 2
  println(numOps)
}

import scala.collection.mutable
object BinaryNumber extends App {
  val input = io.Source.stdin.getLines.next

  if(input == "1") println("0")
  else {
    var numOps = 0
    var tail = 0
    input foreach { char =>
      if(char == '0') {
        numOps += 2
        tail += 1
      } else {
        numOps += 1
        tail = 0
      }
    }
    numOps -= (tail - 1)
    println(numOps)
  }
}


And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, vb, vs) = in.next().split(' ').map(_.toInt)
  val xs = in.next().split(' ').map(_.toInt)
  val Array(xu, yu) = in.next().split(' ').map(_.toDouble)

  val res = xs.indices.tail.foldLeft(-1, 0d, 0d) {
    case ((-1, _, _), i) =>
      val dx: Double = xs(i) - xu
      (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
    case (acc@(sum, index, length), i) =>
      val dx: Double = xs(i) - xu
      val candidate = (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
      if (candidate._2 < acc._2 || (candidate._2 == acc._2 && candidate._3 < acc._3)) {
        candidate
      }
      else acc
  }

  println(res._1)

}

//package me.jetblack.cf

import java.util.Scanner

object BusStop extends App {

  val s = new Scanner(System.in)

  import s._

  val n = nextInt()
  val (vb, vs) = (nextInt().toDouble, nextInt().toDouble)

  val stops = (0 until n).map { _ =>
    (nextInt().toDouble, 0.0)
  }.toArray

  val univ = (nextInt().toDouble, nextInt().toDouble)

  def dist(a: (Double, Double), b: (Double, Double)): Double = math.sqrt((a._1 - b._1) * (a._1 - b._1) + (a._2 - b._2) * (a._2 - b._2))

  var result = Integer.MAX_VALUE.toDouble
  val start = (0.0, 0.0)
  var stopNum = 1
  var sun = Integer.MAX_VALUE.toDouble

  stops.tail.zipWithIndex.map { case (stop, i) =>
    val d = dist(start, stop) / vb + dist(stop, univ) / vs
    val curs = dist(stop, univ)
    if (d <= result && curs < sun) {
      result = d
      stopNum = i + 2
    }
  }

  println(stopNum)

}

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)
    out.println(processedStations(0)._2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    (Math.sqrt(dist(station, 0, x, y)) * busSpeed + Math.abs(station) * manSpeed, dist(station, 0, x, y))
  }

  def dist(x: Double, y: Double, x1: Double, y1: Double): Double = {
    (x - x1) * (x - x1) + (y - y1) * (y - y1)
  }

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

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, vb, vs) = readLine.split(" ").map(_.toDouble);
    var x = readLine.split(" ").map(_.toDouble);
    var Array(xu, yu) = readLine.split(" ").map(_.toDouble);
    for (i <- 1 until x.length - 1) {
      var tc = math.sqrt(math.pow(xu - x(i), 2) + math.pow(yu, 2)) / vs;
      var tn = (x(i + 1) - x(i)) / vb + math.sqrt(math.pow(xu - x(i + 1), 2) + math.pow(yu, 2)) / vs;
      if (tc < tn) {
        println(i + 1);
        return;
      }
    }
    println(x.length);
  }

}

object P9B {
    import io.StdIn._
    import Math._

    def main(args:Array[String]) {
        val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}
        val a = readLine.split(' ').map{_.toDouble}
        val Array(xu, yu) = readLine.split(' ').map{_.toDouble}
        println(1.to(a.size - 1).minBy{i => {
            val xs = xu - a(i)
            a(i) / vb + sqrt(xs * xs + yu * yu) / vs - i * 1e-6
        }} + 1)
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, vb, vs) = in.next().split(' ').map(_.toInt)
  val xs = in.next().split(' ').map(_.toInt)
  val Array(xu, yu) = in.next().split(' ').map(_.toDouble)

  val res = xs.indices.tail.foldLeft(-1, 0d, 0d) {
    case ((-1, _, _), i) =>
      val dx: Double = xs(i) - xu
      (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
    case (acc@(sum, index, length), i) =>
      val dx: Double = xs(i) - xu
      val candidate = (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
      println(acc)
      println(candidate)
      if (candidate._2 < acc._2 || (candidate._2 == acc._2 && candidate._3 < acc._3)) {
        candidate
      }
      else acc
  }

  println(res._1)

}

//package me.jetblack.cf

import java.util.Scanner

object BusStop extends App {

  val s = new Scanner(System.in)

  import s._

  val n = nextInt()
  val (vb, vs) = (nextInt().toDouble, nextInt().toDouble)

  val stops = (0 until n).map { _ =>
    (nextInt().toDouble, 0.0)
  }.toArray

  val univ = (nextInt().toDouble, nextInt().toDouble)

  def dist(a: (Double, Double), b: (Double, Double)): Double = math.sqrt((a._1 - b._1) * (a._1 - b._1) + (a._2 - b._2) * (a._2 - b._2))

  var result = Integer.MAX_VALUE.toDouble
  val start = (0.0, 0.0)
  var stopNum = 1

  stops.tail.zipWithIndex.map { case (stop, i) =>
    val d = dist(start, stop) / vb + dist(stop, univ) / vs
    if (d < result) {
      result = d
      stopNum = i + 2
    }
  }

  println(stopNum)

}

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)
    out.println(processedStations(0)._2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    ((dist(station, 0, x, y) * busSpeed + Math.abs(station) * manSpeed) / (busSpeed * manSpeed), dist(station, 0, x, y))
  }

  def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {
    Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
  }

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

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)
    out.println(processedStations(0)._2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    if (!dist(station, 0, x, y).isNaN) ((dist(station, 0, x, y) * busSpeed + Math.abs(station) * manSpeed) / (busSpeed * manSpeed), dist(station, 0, x, y))
    else (Double.MAX_VALUE, Double.MAX_VALUE)
  }

  def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {
    Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
  }

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

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zipWithIndex.sortWith(customComparator)
    out.println(processedStations(0)._2 + 2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    (dist(station, 0, x, y) / manSpeed + station / busSpeed, dist(station, 0, x, y))
  }

  def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {
    Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
  }

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

object P9B {
    import io.StdIn._
    import Math._

    def main(args:Array[String]) {
        val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}
        val a = readLine.split(' ').map{_.toDouble}
        val Array(xu, yu) = readLine.split(' ').map{_.toInt}
        println(1.to(a.size - 1).minBy{i => {
            val xs = xu - a(i)
            a(i) / vb + sqrt(xs * xs + yu * yu) / vs
        }} + 1)
    }
}

object P9B {
    import io.StdIn._
    import Math._

    def main(args:Array[String]) {
        val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}
        val a = readLine.split(' ').map{_.toInt}
        val Array(xu, yu) = readLine.split(' ').map{_.toInt}
        println(1.to(a.size - 1).minBy{i => {
            val xs = xu - a(i)
            a(i).toDouble / vb + sqrt(xs * xs + yu * yu) / vs
        }} + 1)
    }
}


It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?

The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow. The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.

Print the maximum total happiness that can be achieved.

NoteIn the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.

//package codeforce.c0867

import scala.io.StdIn

object C {
  def main(args: Array[String]): Unit = {
    val Array(eaters, slices) = StdIn.readLine().split(' ').map(_.toInt)
    val eater = Array.ofDim[Eater](eaters)
    for {
      e <- 0 until eaters
    } {
      eater(e) = Eater(StdIn.readLine().split(' ').map(_.toInt))
    }
    println(new Greedy(slices, eater).maxValue())
  }

  case class Eater(slices: Int, value1: Int, value2: Int) extends Ordered[Eater] {
    override def compare(that: Eater): Int = that.diff() compare diff()
    def diff(): Int = Math.abs(value1 - value2)
  }

  object Eater {
    def apply(input: Array[Int]): Eater = Eater(input(0), input(1), input(2))
  }

  class Greedy(slices: Int, eaters: Array[Eater]) {
    def maxValue(): Long = {
      var maxValue: Long = 0L
      var slices1: Long = 0L
      var slices2: Long = 0L
      val pq1 = collection.mutable.PriorityQueue[Eater]()
      val pq2 = collection.mutable.PriorityQueue[Eater]()

      eaters.foreach(e => if (e.value1 > e.value2) {
        maxValue += 1L * e.slices * e.value1
        slices1 += e.slices
        pq1.enqueue(e)
      } else {
        maxValue += 1L * e.slices * e.value2
        slices2 += e.slices
        pq2.enqueue(e)
      })

      val incomplete1 = slices1 % slices
      val incomplete2 = slices2 % slices

      if (incomplete1 + incomplete2 <= slices) {
        val diff1 = diff(pq1, incomplete1)
        val diff2 = diff(pq2, incomplete2)
        maxValue -= Math.min(diff1, diff2)
      }
      maxValue
    }

    def diff(pq: collection.mutable.PriorityQueue[Eater], n: Long): Long = {
      var diff: Long = 0
      var i = n
      while (i > 0) {
        val e = pq.dequeue()
        diff += Math.min(e.slices, i) * e.diff()
        i -= e.slices
      }
      diff
    }
  }
}


Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — the length of the song and the number of questions.  The second line contains one string $$$s$$$ — the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — the bounds of the question.

Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.

NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to $$$4$$$. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is $$$7$$$. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length $$$11$$$.

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

  val Array(n, q) = readLine().split(" ").map(_.toInt)
  val s           = readLine()
  val ps          = s.scanLeft(0L) { case (p, c) => p + c - 'a' + 1 }
  (0 until q).foreach { _ =>
    val Array(l, r) = readLine().split(" ").map(_.toInt)

    val ans = ps(r) - ps(l - 1)

    println(ans)
  }
}


You have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.It takes t1 minutes to wash one piece of laundry in a washing machine, t2 minutes to dry it in a drying machine, and t3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.

The only line of the input contains seven integers: k, n1, n2, n3, t1, t2, t3 (1 ≤ k ≤ 104; 1 ≤ n1, n2, n3, t1, t2, t3 ≤ 1000).

Print one integer — smallest number of minutes to do all your laundry.

NoteIn the first example there's one instance of each machine, each taking 5 minutes to complete. You have only one piece of laundry, so it takes 15 minutes to process it.In the second example you start washing first two pieces at moment 0. If you start the third piece of laundry immediately, then by the time it is dried, there will be no folding machine available, so you have to wait, and start washing third piece at moment 2. Similarly, you can't start washing next piece until moment 5, since otherwise there will be no dryer available, when it is washed. Start time for each of the eight pieces of laundry is 0, 0, 2, 5, 10, 10, 12 and 15 minutes respectively. The last piece of laundry will be ready after 15 + 10 + 5 + 2 = 32 minutes.

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import java.lang.Math

object D extends App {

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

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

  val Array(k, nX, nY, nZ, tX, tY, tZ) = readInts(7)

  val g = gcd(gcd(tX, tY), tZ)

  val T = k * (tX + tY + tZ) / g
  val availX = Array.ofDim[Short](T - k * (tY + tZ) / g + 3) // { nZ.toShort }
  val availY = Array.ofDim[Short](T - k * tZ / g + 3) // { nY.toShort }
  val availZ = Array.ofDim[Short](T + 3) // { nX.toShort }

  var t = 0
  var remain = k.toShort

  while (remain > 0) {
    val t2 = t + tX / g
    val t3 = t2 + tY / g
    val take = Math.min(Math.min(availX(t) + nX,
        availY(t2) + nY),
        Math.min(availZ(t3) + nZ, remain)).toShort
    if (take > 0) {

      var i = t
      var to = t2
      while (i < to) {
        availX(i) = (availX(i) - take).toShort
        i += 1
      }

      i = t2
      to = t3
      while (i < to) {
        availY(i) = (availY(i) - take).toShort
        i += 1
      }

      i = t3
      to = i + tZ / g
      while (i < to) {
        availZ(i) = (availZ(i) - take).toShort
        i += 1
      }

    }

    t += 1
    remain = (remain - take).toShort
  }

  println((t - 1) * g + tX + tY + tZ)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import java.lang.Math

object D extends App {

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

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

  val Array(k, nX, nY, nZ, tX, tY, tZ) = readInts(7)

  val g = gcd(gcd(tX, tY), tZ)

  val T = k * (tX + tY + tZ) / g
  val availX = Array.ofDim[Short](T - k * (tY + tZ) / g + 3) // { nZ.toShort }
  val availY = Array.ofDim[Short](T - k * tZ / g + 3) // { nY.toShort }
  val availZ = Array.ofDim[Short](T + 3) // { nX.toShort }

  var t = 0
  var remain = k.toShort

  while (remain > 0) {
    val t2 = t + tX / g
    val t3 = t2 + tY / g
    val take = Math.min(Math.min(availX(t) + nX,
        availY(t2) + nY),
        Math.min(availZ(t3) + nZ, remain)).toShort
    if (take > 0) {

      var i = t
      var to = t2
      while (i < to) {
        availX(i) = (availX(i) - take).toByte
        i += 1
      }

      i = t2
      to = t3
      while (i < to) {
        availY(i) = (availY(i) - take).toShort
        i += 1
      }

      i = t3
      to = i + tZ / g
      while (i < to) {
        availZ(i) = (availZ(i) - take).toShort
        i += 1
      }

    }

    t += 1
    remain = (remain - take).toShort
  }

  println((t - 1) * g + tX + tY + tZ)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import java.lang.Math

object D extends App {

  def gcd(x: Int, y: Int): Int = if (y == 0) x else gcd(y, x % y)

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

  val Array(k, nX, nY, nZ, tX, tY, tZ) = readInts(7)

  val g = gcd(gcd(tX, tY), tZ)

  val T = k * (tX + tY + tZ) / g
  val availX = Array.fill(T - k * (tY + tZ) / g + 3){ nX.toShort }
  val availY = Array.fill(T - k * tZ / g + 3){ nY.toShort }
  val availZ = Array.fill(T + 3){ nZ.toShort }

  var t = 0
  var remain = k.toShort

  while (remain > 0) {
    val t2 = t + tX / g
    val t3 = t2 + tY / g
    val take = Math.min(Math.min(availX(t),
        availY(t2)),
        Math.min(availZ(t3), remain)).toShort
    if (take > 0) {

      var i = t
      var to = t2
      while (i < to) {
        availX(i) = (availX(i) - take).toByte
        i += 1
      }

      i = t2
      to = t3
      while (i < to) {
        availY(i) = (availY(i) - take).toShort
        i += 1
      }

      i = t3
      to = i + tZ / g
      while (i < to) {
        availZ(i) = (availZ(i) - take).toShort
        i += 1
      }

    }

    t += 1
    remain = (remain - take).toShort
  }

  println((t - 1) * g + tX + tY + tZ)
}


A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.

Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.

object Main {
  def main(args: Array[String]) {
    val n = readLine().split(" ").map(_.toInt).head
    val b: Array[(Int,Int)] = readLine().split(" ").map(_.toInt).toArray.zipWithIndex
    val t = b.filter(x => x._1 == x._2).length
    var res = 0
    if (b.exists(x => b(x._1)._1 == x._2 && x._1 != x._2)) {
      res += 2
      res+=t
    } else {
      res={if (t == n) t else t+1}
    }
    println(res)
  }
}

object B {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val t = (Nil : Seq[Int]).toBuffer
    for (i <- 1 to n)
      t += sc.nextInt
    var fix = new Array[Boolean](n)
    for (i <- 0 until n)
      if (i == t(i))
        fix(i) = true
    val cnt = fix.filter(_ == true).size
    for (i <- 0 until n)
      if (!fix(i) && !fix(t(i)))
        if (i == t(t(i))) {
          println(cnt + 2)
          return
        }
    if (cnt >= n-1) {
      println(cnt)
      return
    }
    println(cnt + 1)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val res = data.indices.foldLeft((0, 0)) {
    case ((onPlace, add), i) if data(i) == i => (onPlace + 1, add)
    case ((onPlace, 2), i) => (onPlace, 2)
    case ((onPlace, 1), i) if data(data(i)) == i => (onPlace, 2)
    case ((onPlace, _), i) => (onPlace, 1)
  }
  println(res._1 + res._2)
}

object B347 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val map = input.zipWithIndex.toMap
    var res = map.count{case (x, y) => x == y}
    if(res == input.length) {
      println(res)
    } else {
      var i = 0
      var break = false
      while(!break && i < n) {
        val value = map(map(i))
        if(map(i) != i && value == i) {
          println(res + 2)
          break = true
        }
        i += 1
      }
      if(!break) {
        println(res + 1)
      }
    }
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  var n = 0
  var e = 1
  0 until N foreach { i =>
    if (A(i) == i) {
      n = n + 1
    }
    else if (A(A(i)) == i) {
      e = 2
    }
  }
  out.println((n + e) min N)
  out.close
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val f = a.zipWithIndex.find(t => t._1 != t._2 && t._2 == a(t._1))
    val count = a.zipWithIndex.count(t => t._1 == t._2)
    if (count == n) println(n)
    else f match {
      case None => println(count + 1)
      case Some(_) => println(count + 2)
    }
  }
}

import scala.io.StdIn
/**
  * http://codeforces.com/problemset/problem/347/B
  **/
object FixedPoints {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val numbers = StdIn.readLine().split(" ").map(_.toInt)
    println(nbFixedPoints(numbers))
  }

  private def nbFixedPoints(numbers: Array[Int]): Int = {
    val (same, different) = numbers.zipWithIndex.partition { case (elt, idx) => elt == idx }
    val additional =
      if (different.isEmpty) 0
      else if (different.exists { case (elt, idx) => numbers(elt) == idx }) 2
      else 1
    same.size + additional
  }

  def test() = {
    val inputs = Map(
      Array(0, 1, 3, 4, 2) -> 3,
      Array(0, 1, 5, 3, 4, 2, 7, 6) -> 6,
      Array(0, 1, 5, 3, 4, 2, 7, 6, 8, 9, 10) -> 9
    )
    for ((numbers, expected) <- inputs) {
      assert(nbFixedPoints(numbers) == expected)
    }
  }
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  var n = 0
  var e = 1
  0 until N foreach { i =>
    if (A(i) == i) {
      n = n + 1
    }
    else if (A(A(i)) == i) {
      e = 2
    }
  }
  out.println(n + e)
  out.close
}


This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 50$$$) — the number of electric poles. Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — the coordinates of the poles. It is guaranteed that all of these $$$n$$$ points are distinct.

Print a single integer — the number of pairs of wires that are intersecting.

NoteIn the first example:  In the second example:  Note that the three poles $$$(0, 0)$$$, $$$(0, 2)$$$ and $$$(0, 4)$$$ are connected by a single wire.In the third example:

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

  case class Coord(x: Int, y: Int)
  case class Line(a: Int, b: Int, c: Int) {
    def slope: Slope = Slope(a, b)
  }
  case class Slope(a: Int, b: Int)

  def toLine(c1: Coord, c2: Coord): Line = {
    var a = c2.y - c1.y
    var b = c1.x - c2.x

    if (a < 0) {
      a *= -1
      b *= -1
    }

    if (a != 0 && b != 0) {
      val g = gcd(a, b)
      a /= g
      b /= g
    }

    if (a == 0) b = 1
    else if (b == 0) a = 1

    val c = -(c1.x * a + c1.y * b)
    Line(a, b, c)
  }

  def gcd(a: Int, b: Int): Int = {
    if (b == 0) a
    else gcd(b, a % b)
  }

  def solve(): Unit = {
    val N = ni()
    val P = Array.ofDim[Coord](N)
    REP(N) { i =>
      val x, y = ni()
      P(i) = Coord(x, y)
    }

    val lines = mutable.Set[Line]()

    REP(N - 1) { i =>
      TO(i + 1, N - 1) { j =>
        lines += toLine(P(i), P(j))
      }
    }

    val slope = mutable.Map[Slope, Int]().withDefaultValue(0)
    lines.foreach { l =>
      val s = l.slope
      slope(s) = slope(s) + 1
    }

    val lineNum = lines.size
    var ans = 0L
    slope.foreach { case (_, num) =>
      ans += num.toLong * (lineNum - num)
    }
    out.println(ans / 2)
  }
}


You are given an array $$$a_1, a_2, \dots, a_n$$$ and an array $$$b_1, b_2, \dots, b_n$$$.For one operation you can sort in non-decreasing order any subarray $$$a[l \dots r]$$$ of the array $$$a$$$.For example, if $$$a = [4, 2, 2, 1, 3, 1]$$$ and you choose subbarray $$$a[2 \dots 5]$$$, then the array turns into $$$[4, 1, 2, 2, 3, 1]$$$. You are asked to determine whether it is possible to obtain the array $$$b$$$ by applying this operation any number of times (possibly zero) to the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). The third line of each query contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that $$$\sum n \le 3 \cdot 10^5$$$ over all queries in a test.

For each query print YES (in any letter case) if it is possible to obtain an array $$$b$$$ and NO (in any letter case) otherwise.

NoteIn first test case the can sort subarray $$$a_1 \dots a_5$$$, then $$$a$$$ will turn into $$$[1, 1, 4, 4, 7, 5, 6]$$$, and then sort subarray $$$a_5 \dots a_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 = {
    REP(ni()) { _ =>
      val N = ni()
      val A, B = na(N)
      val INF = 1e9.toInt
      val t = new SegmentTree(N, INF)(min)
      REP(N) { i =>
        t.update(i, A(i))
      }
      val ix = Array.fill[java.util.ArrayDeque[Int]](N + 1)(new java.util.ArrayDeque)
      REP(N) { i =>
        ix(A(i)).add(i)
      }

      var ok = true
      REP(N) { i =>
        val j = ix(B(i)).poll()
        ok &&= t.query(0, j + 1) == B(i)
        t.update(j, INF)
      }
      if (ok) out.println("YES")
      else out.println("NO")
    }
  }

  /**
    * @param n 個数 最大値じゃないぞ。
    * iの範囲は[0, n - 1]
    *
    * AがIntやLongのときは埋め込んでしまおう
    * type A = Int
    */
  class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      assert(i < n)
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }
}