import scala.io.StdIn._

object C extends App {
  val n = readInt()
  val C = readLine().split(" ").map(_.toLong)
  val S = Array.ofDim[(String, String)](n)

  for (i <- 0 until n) {
    val w = readLine()
    S(i) = (w, w.reverse)
  }

  val D = Array.ofDim[Long](n, 2)
  D(0)(0) = 0
  D(0)(1) = C(0)

  if (isPossible) {
    println(Math.min(D(n - 1)(0), D(n - 1)(1)))
  } else {
    println(-1)
  }

  def isPossible: Boolean = {
    for (i <- 1 until n) {
      val A = S(i - 1)._1
      val Arev = S(i - 1)._2
      val B = S(i)._1
      val Brev = S(i)._2

      var min1 = Long.MaxValue
      if (isOrdered(A, B)) min1 = Math.min(min1, D(i - 1)(0))
      if (isOrdered(Arev, B)) min1 = Math.min(min1, D(i - 1)(1))
      D(i)(0) = min1

      var min2 = Long.MaxValue
      if (isOrdered(A, Brev) && D(i - 1)(0) != Long.MaxValue) min2 = Math.min(min2, D(i - 1)(0) + C(i))
      if (isOrdered(Arev, Brev) && D(i - 1)(1 ) != Long.MaxValue) min2 = Math.min(min2, D(i - 1)(1) + C(i))
      D(i)(1) = min2

      if (min1 == Long.MaxValue && min2 == Long.MaxValue) return false
    }

    true
  }

  def isOrdered(a: String, b: String): Boolean = {
    a <= b
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val c = in.next().split(' ').map(_.toInt)
  val (_, ans) = in.take(n).toList.zip(c).foldLeft((true, Map.empty[String, Long])) {
    case ((true, map), (str, price)) if str == str.reverse =>
      (false, Map(str -> 0))
    case ((true, map), (str, price)) =>
      (false, Map(str -> 0, str.reverse -> price))
    case ((false, map), _ ) if map.isEmpty => (false, Map.empty)
    case ((false, map), (str, price)) if str == str.reverse =>
      val v = map.filter { case(a, b) => a <= str }.values
      (false, if (v.isEmpty) Map.empty else Map(str -> v.min))
    case ((false, map), (str, price)) =>
      val nMap = map.filter { case(a, b) => a <= str }.values
      val nMap2 = map.filter { case(a, b) => a <= str.reverse}.values
      if (nMap.isEmpty && nMap2.isEmpty)
        (false, Map.empty)
      else if (nMap.nonEmpty && nMap2.nonEmpty)
        (false, Map(str -> nMap.min, str.reverse -> (nMap2.min + price)))
      else if (nMap.nonEmpty)
        (false, Map(str -> nMap.min))
      else
        (false, Map(str.reverse -> (nMap2.min + price)))
  }
  if (ans.isEmpty)
    println(-1)
  else
    println(ans.values.min)
}

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

object _706C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val costs = read[Vector[Int]]

    var choices = Iterable("" -> 0L)

    costs foreach {cost =>
      val s = read[String]
      val r = s.reverse
      val next = map[String] to Long.MaxValue
      for {
        (s1, c1) <- choices
        (s2, c2) <- Iterable(s -> 0, r -> cost)
        if s1.isEmpty || s1 <= s2
      } next(s2) = next(s2) min (c1 + c2)
      choices = next.toSeq
    }

    val ans = choices.map(_._2).whenNonEmpty(_.min)
    write(ans getOrElse -1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
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 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
  }
  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 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")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val inputit:Iterator[String] = input.getLines()
  var lineit:Iterator[String] = List.empty.iterator
  def rs() : String = {
    if (lineit.hasNext) lineit.next
    else {
      lineit = inputit.next.split(" ").iterator
      rs()
    }
  }
  def ri(): Int = rs().toInt
  def rl(): Long = rs().toLong
  val n = ri ()
  val c = Array.fill(n)(rl())
  val s = Array.fill(n)(rs())
  val t = s.map { _.reverse }
  var q = Array(0l, c(0))
  val inf = Long.MaxValue / 2
  for (i <- 1 until n) {
    val w = Array.fill(2)(inf)
    if (s(i-1) <= s(i) && w(0) > q(0)) w(0) = q(0)
    if (s(i-1) <= t(i) && w(1) > q(0) + c(i)) w(1) = q(0) + c(i)
    if (t(i-1) <= s(i) && w(0) > q(1)) w(0) = q(1)
    if (t(i-1) <= t(i) && w(1) > q(1) + c(i)) w(1) = q(1) + c(i)
    q = w
  }
  val r = q.min
  println(if (r >= inf) -1l else r)
}

object Solution {

  import scala.math._

  def main(args: Array[String]) {

    val sc = new java.util.Scanner(System.in)

    val n = sc.nextInt()
    val energy = Array.fill(n)(sc.nextInt().toLong)
    val strs = Array.fill(n)(sc.next())

    println(calc(strs, energy))
  }
  def calc(strs: Array[String], energy: Array[Long]): Long = {

    val n = strs.length
    val dp = Array.fill(n)(Array.fill(2)(-1L))

    dp(0)(0) = 0L
    dp(0)(1) = energy(0)

    for (i <- (1 until n)) {

      if (dp(i-1)(0) == -1 && dp(i-1)(1) == -1) return -1

      else if(dp(i-1)(0) == -1) {

        val prev_str_reversed = strs(i-1).reverse

        if (prev_str_reversed <= strs(i)) dp(i)(0) = dp(i-1)(1)

        if (prev_str_reversed <= strs(i).reverse) dp(i)(1) = dp(i-1)(1) + energy(i)
      }
      else if (dp(i-1)(1) == -1) {

        val prev_str = strs(i-1)

        if (prev_str <= strs(i)) dp(i)(0) = dp(i-1)(0)

        if (prev_str <= strs(i).reverse) dp(i)(1) = dp(i-1)(0) + energy(i)
      }
      else {

        val prev_str = strs(i-1)
        val prev_str_reversed = strs(i-1).reverse

        if (prev_str <= strs(i) && prev_str_reversed <= strs(i))
          dp(i)(0) = min(dp(i-1)(0), dp(i-1)(1))
        else if (prev_str <= strs(i))
          dp(i)(0) = dp(i-1)(0)
        else if (prev_str_reversed <= strs(i))
          dp(i)(0) = dp(i-1)(1)

        if (prev_str <= strs(i).reverse && prev_str_reversed <= strs(i).reverse)
          dp(i)(1) = min(dp(i-1)(0), dp(i-1)(1)) + energy(i)
        else if (prev_str <= strs(i).reverse)
          dp(i)(1) = dp(i-1)(0) + energy(i)
        else if (prev_str_reversed <= strs(i).reverse)
          dp(i)(1) = dp(i-1)(1) + energy(i)
      }
    }
    if(dp(n-1)(0) > -1 && dp(n-1)(1) > -1) min(dp(n-1)(0), dp(n-1)(1))
    else if (dp(n-1)(0) > -1) dp(n-1)(0)
    else if (dp(n-1)(1) > -1) dp(n-1)(1)
    else -1
  }
}

object Solution {

  import scala.math._

  def main(args: Array[String]) {

    val sc = new java.util.Scanner(System.in)

    val n = sc.nextInt()
    val energy = Array.fill(n)(sc.nextInt())
    val strs = Array.fill(n)(sc.next())

    println(calc(strs, energy))
  }
  def calc(strs: Array[String], energy: Array[Int]): Int = {

    val n = strs.length
    val dp = Array.fill(n)(Array.fill(2)(-1))

    dp(0)(0) = 0
    dp(0)(1) = energy(0)

    for (i <- (1 until n)) {

      if (dp(i-1)(0) == -1 && dp(i-1)(1) == -1) return -1

      else if(dp(i-1)(0) == -1) {

        val prev_str_reversed = strs(i-1).reverse

        if (prev_str_reversed <= strs(i)) dp(i)(0) = dp(i-1)(1)

        if (prev_str_reversed <= strs(i).reverse) dp(i)(1) = dp(i-1)(1) + energy(i)
      }
      else if (dp(i-1)(1) == -1) {

        val prev_str = strs(i-1)

        if (prev_str <= strs(i)) dp(i)(0) = dp(i-1)(0)

        if (prev_str <= strs(i).reverse) dp(i)(1) = dp(i-1)(0) + energy(i)
      }
      else {

        val prev_str = strs(i-1)
        val prev_str_reversed = strs(i-1).reverse

        if (prev_str <= strs(i) && prev_str_reversed <= strs(i))
          dp(i)(0) = min(dp(i-1)(0), dp(i-1)(1))
        else if (prev_str <= strs(i))
          dp(i)(0) = dp(i-1)(0)
        else if (prev_str_reversed <= strs(i))
          dp(i)(0) = dp(i-1)(1)

        if (prev_str <= strs(i).reverse && prev_str_reversed <= strs(i).reverse)
          dp(i)(1) = min(dp(i-1)(0), dp(i-1)(1)) + energy(i)
        else if (prev_str <= strs(i).reverse)
          dp(i)(1) = dp(i-1)(0) + energy(i)
        else if (prev_str_reversed <= strs(i).reverse)
          dp(i)(1) = dp(i-1)(1) + energy(i)
      }
    }
    if(dp(n-1)(0) > -1 && dp(n-1)(1) > -1) min(dp(n-1)(0), dp(n-1)(1))
    else if (dp(n-1)(0) > -1) dp(n-1)(0)
    else if (dp(n-1)(1) > -1) dp(n-1)(1)
    else -1
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val c = in.next().split(' ').map(_.toInt)
  val (_, ans) = in.take(n).toList.zip(c).foldLeft((true, Map.empty[String, Int])) {
    case ((true, map), (str, price)) if str == str.reverse =>
      (false, Map(str -> 0))
    case ((true, map), (str, price)) =>
      (false, Map(str -> 0, str.reverse -> price))
    case ((false, map), _ ) if map.isEmpty => (false, Map.empty)
    case ((false, map), (str, price)) if str == str.reverse =>
      val v = map.filter { case(a, b) => a <= str }.values
      (false, if (v.isEmpty) Map.empty else Map(str -> v.min))
    case ((false, map), (str, price)) =>
      val nMap = map.filter { case(a, b) => a <= str }.values
      val nMap2 = map.filter { case(a, b) => a <= str.reverse}.values
      if (nMap.isEmpty && nMap2.isEmpty)
        (false, Map.empty)
      else if (nMap.nonEmpty && nMap2.nonEmpty)
        (false, Map(str -> nMap.min, str.reverse -> (nMap2.min + price)))
      else if (nMap.nonEmpty)
        (false, Map(str -> nMap.min))
      else
        (false, Map(str.reverse -> (nMap2.min + price)))
  }
  if (ans.isEmpty)
    println(-1)
  else
    println(ans.values.min)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val c = in.next().split(' ').map(_.toInt)
  val (_, ans) = in.take(n).toList.zip(c).foldLeft((true, Map.empty[String, Int])) {
    case ((true, map), (str, price)) if str == str.reverse =>
      (false, Map(str -> 0))
    case ((true, map), (str, price)) =>
      (false, Map(str -> 0, str.reverse -> price))
    case ((false, map), _ ) if map.isEmpty => (false, Map.empty)
    case ((false, map), (str, price)) if str == str.reverse =>
      val v = map.filter { case(a, b) => a <= str }.values
      (false, if (v.isEmpty) Map.empty else Map(str -> v.min))
    case ((false, map), (str, price)) =>
      val nMap = map.filter { case(a, b) => a <= str }.values
      val nMap2 = map.filter { case(a, b) => a <= str.reverse}.values
      if (nMap.isEmpty && nMap2.isEmpty)
        (false, Map.empty)
      else if (nMap.nonEmpty && nMap2.nonEmpty)
        (false, Map(str -> nMap.min, str.reverse -> nMap2.min))
      else if (nMap.nonEmpty)
        (false, Map(str -> nMap.min))
      else
        (false, Map(str.reverse -> nMap2.min))
  }
  if (ans.isEmpty)
    println(-1)
  else
    println(ans.values.min)
}

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

object _706C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val n = read[Int]
    val cost = read[Vector, Int](n)

    var choices = Iterable(Choice("", 0))

    0 until n foreach {i =>
      val s = read[String]
      val r = s.reverse
      val next = mutable.Map.empty[String, Int]
      for {
        (s2, c2) <- Seq(s -> 0, r -> cost(i))
        c1 <- choices
        c <- c1.next(s2, c2)
        if c.cost < next.getOrElse(s2, Int.MaxValue)
      } next(s2) = c.cost

      choices = next.map(p => Choice(p._1, p._2))
    }

    val ans = choices.map(_.cost).whenNonEmpty(_.min) getOrElse -1
    write(ans)
  }

  case class Choice(s: String, cost: Int) {
    def next(s2: String, c2: Int) = when(s.isEmpty || s <= s2) {
      Choice(s2, cost + c2)
    }
  }
}
/****************************[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 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
  }
  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 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")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

//296 мс    38900
object Main extends App {
  import scala.io._
  val input = Source.stdin
  val inputit:Iterator[String] = input.getLines()
  var lineit:Iterator[String] = List.empty.iterator
  def rs() : String = {
    if (lineit.hasNext) lineit.next
    else {
      lineit = inputit.next.split(" ").iterator
      rs()
    }
  }
  def ri(): Int = rs().toInt
  def rl(): Long = rs().toLong
  val n = ri ()
  val c = Array.fill(n)(rl())
  val s = Array.fill(n)(rs())
  val t = s.map { _.reverse }
  var q = Array(0l, c(0))
  val inf = Long.MaxValue / 2
  for (i <- 1 until n) {
    val w = Array.fill(2)(inf)
    if (s(i-1) < s(i) && w(0) > q(0)) w(0) = q(0)
    if (s(i-1) < t(i) && w(1) > q(0) + c(i)) w(1) = q(0) + c(i)
    if (t(i-1) < s(i) && w(0) > q(1)) w(0) = q(1)
    if (t(i-1) < t(i) && w(1) > q(1) + c(i)) w(1) = q(1) + c(i)
    q = w
  }
  val r = q.min
  println(if (r >= inf) -1l else r)
}

import scala.io.StdIn._

object C extends App {
  val n = readInt()
  val C = readLine().split(" ").map(_.toInt)
  val S = (for {
    _ <- 1 to n
    s = readLine()
  } yield (s, s.reverse)).toList

  val D = Array.ofDim[Int](n, 2)
  D(0)(0) = 0
  D(0)(1) = C(0)

  if (isPossible) {
    println(Math.min(D(n - 1)(0), D(n - 1)(1)))
  } else {
    println(-1)
  }

  def isPossible: Boolean = {
    for (i <- 1 until n) {
      val A = S(i - 1)._1
      val Arev = S(i - 1)._2
      val B = S(i)._1
      val Brev = S(i)._2

      var min1 = Int.MaxValue
      if (isOrdered(A, B)) min1 = Math.min(min1, D(i - 1)(0))
      if (isOrdered(Arev, B)) min1 = Math.min(min1, D(i - 1)(1))
      D(i)(0) = min1

      var min2 = Int.MaxValue
      if (isOrdered(A, Brev)) min2 = Math.min(min2, D(i - 1)(0) + C(i))
      if (isOrdered(Arev, Brev)) min2 = Math.min(min2, D(i - 1)(1))
      D(i)(1) = min2

      if (min1 == Int.MaxValue && min2 == Int.MaxValue) return false
    }

    true
  }

  def isOrdered(a: String, b: String): Boolean = {
    a <= b
  }
}

import scala.io.StdIn._

object C extends App {
  val n = readInt()
  val C = readLine().split(" ").map(_.toInt)
  val S = Array.ofDim[(String, String)](n)

  for (i <- 0 until n) {
    val w = readLine()
    S(i) = (w, w.reverse)
  }

  val D = Array.ofDim[Int](n, 2)
  D(0)(0) = 0
  D(0)(1) = C(0)

  if (isPossible) {
    println(Math.min(D(n - 1)(0), D(n - 1)(1)))
  } else {
    println(-1)
  }

  def isPossible: Boolean = {
    for (i <- 1 until n) {
      val A = S(i - 1)._1
      val Arev = S(i - 1)._2
      val B = S(i)._1
      val Brev = S(i)._2

      var min1 = Int.MaxValue
      if (isOrdered(A, B)) min1 = Math.min(min1, D(i - 1)(0))
      if (isOrdered(Arev, B)) min1 = Math.min(min1, D(i - 1)(1))
      D(i)(0) = min1

      var min2 = Int.MaxValue
      if (isOrdered(A, Brev) && D(i - 1)(0) != Int.MaxValue) min2 = Math.min(min2, D(i - 1)(0) + C(i))
      if (isOrdered(Arev, Brev) && D(i - 1)(1 ) != Int.MaxValue) min2 = Math.min(min2, D(i - 1)(1) + C(i))
      D(i)(1) = min2

      if (min1 == Int.MaxValue && min2 == Int.MaxValue) return false
    }

    true
  }

  def isOrdered(a: String, b: String): Boolean = {
    a <= b
  }
}


import java.util

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val max = 1000000007;
    val n = readInt()

    val  A:Array[(Int,Int)] = Array.fill(n)(readTuple())

    println(A.foldLeft((101,0)) {
      (sm,a)=> {
        if(a._2 < sm._1)
          (a._2, sm._2 + a._1 * a._2)
        else
          (sm._1, sm._2 + a._1 * sm._1)
      }
    }._2)

  }

  def readInt(): Int = StdIn.readInt()

  def readInts(): Array[Int] = StdIn.readLine().split(" ").map(_.toInt)

  def readTuple(): (Int, Int) = {
    val line = readInts
    (line(0), line(1))
  }

}

import scala.collection.mutable.ArrayBuffer

object Solve extends App with fastIO{
  val n = nextInt
  val a = new ArrayBuffer[Int]
  val p = new ArrayBuffer[Int]
  for(i <- 0 until n){
    a += nextInt
    p += nextInt
  }

  var minp = p(0)
  var res = p(0)*a(0)
  for(i <- 1 until n){
    if(p(i)>minp) res+=minp*a(i)
    else {
      minp = p(i)
      res+=minp*a(i)
    }
  }
  println(res)
  flush
}

trait fastIO {
  import java.io._
  val isFile = false
  val input = "file.in"
  val output = "file.out"
  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }
  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }
  def nextLong:Long ={
    in.nextToken()
    in.nval.toLong
  }
  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }
  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  var n = in.nextInt()
  var a = Array.ofDim[Int](n + 1)
  var p = Array.ofDim[Int](n + 1)
  for (i <- 0 until n) {
    a(i) = in.nextInt()
    p(i) = in.nextInt()
  }
  for (i <- 1 until n) {
    if (p(i) > p(i - 1)) {
      p(i) = p(i - 1);
    }
  }
  var res = 0
  for (i <- 0 until n) {
    res += a(i) * p(i)
  }
  println(res)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data = (1 to n).map(_ => in.next().split(" ").map(_.toInt))
  var sum = 0
  while (data.nonEmpty) {
    val min = data.minBy(_.last)
    val index = data.indexOf(min)
    sum += data.drop(index).map(_.head).sum * min.last
    data = data.take(index)
  }
  println(sum)
}

object A588 {
  @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 = Array.fill(n)(readLongs(2))
    var min = input(0)(1)
    var res = input(0)(0) * min
    for(i <- 1 until n) {
      if(input(i)(1) < min) {
        min = input(i)(1)
      }
      res += input(i)(0) * min
    }
    println(res)
  }
}

// So you like object Task
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

object Task {

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        var answer = 0l
        var curMin = Int.MaxValue
        for (i <- 0 until n) {
            val a = in.nextInt()
            curMin = curMin min in.nextInt()
            answer += a * curMin
        }
        out.println(answer)
    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

    def nextDouble(): Double = {
        next().toDouble
    }

    def close(): Unit = {
        inputStream.close()
    }
}

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

import CodeForcesApp._

object _588A extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val input = List.fill(n)((nextInt(), nextInt()))

    var curPrice = Int.MaxValue
    var ans = 0

    for {
      (a, p) <- input
    } {
      curPrice = curPrice min p
      ans += a*curPrice
    }

    ans
  }

  override def format(result: Result) = super.format(result)
}
/**************************************[Ignore]***************************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
import java.io.{File, BufferedReader, Reader, InputStream, InputStreamReader, StringReader}
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: BufferedReader) extends AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val tokens = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    start = new StringTokenizer(line)
    tokenizer <- Iterator.continually(start).takeWhile(_.hasMoreTokens)
  } yield tokenizer.nextToken()

  def next(): String = tokens.next()
  def nextInt(): Int = next().toInt

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

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

import CodeForcesApp._

object _588A extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val input = List.fill(n)((nextInt(), nextInt()))

    var curPrice = Int.MaxValue
    var ans = 0

    for {
      (a, p) <- input
    } {
      curPrice = curPrice min p
      ans += a*curPrice
    }

    ans
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/********************************[Scala Scanner]*********************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  def tokens: Iterator[String] = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokenizer.nextToken()

  private[this] var current = tokens
  override def hasNext = current.hasNext
  @inline override def next() = current.next()

  /**
   * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line
   */
  def nextLine(): String = {
    current = tokens   // reset
    reader.readLine()
  }
  def lineNumber: Int = reader.getLineNumber
  def nextString(): String = next()
  def nextChar(): Char = next().head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

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

import CodeForcesApp._

object _588A extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val input = List.fill(n)((nextInt(), nextInt()))

    var curPrice = Int.MaxValue
    var ans = 0

    for {
      (a, p) <- input
    } {
      curPrice = curPrice min p
      ans += a*curPrice
    }

    ans
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/********************************[Scala Scanner]*********************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines: Iterator[String] = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  def tokens: Iterator[String] = for {
    line <- lines
    tokenizer = new StringTokenizer(line)
    _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokenizer.nextToken()

  private[this] var current = tokens
  override def hasNext = current.hasNext
  @inline override def next() = current.next()

  /**
   * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line
   */
  def nextLine(): String = {
    current = tokens   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def nextString(): String = next()
  def nextChar(): Char = next().head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

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

import CodeForcesApp._

object _588A extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val input = List.fill(n)((nextInt(), nextInt()))

    var curPrice = Int.MaxValue
    var ans = 0

    for {
      (a, p) <- input
    } {
      curPrice = curPrice min p
      ans += a*curPrice
    }

    ans
  }

  override def format(result: Result) = super.format(result)
}
/**************************************[Ignore]***************************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
import java.io.{File, BufferedReader, Reader, InputStream, InputStreamReader, StringReader}
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: BufferedReader) extends Iterable[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  override def iterator = for {
    line <- Iterator.continually(reader.readLine()).takeWhile(_ != null)
    tokenizer = new StringTokenizer(line)
    tokens <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokens.nextToken()

  private[this] var current = iterator

  def hasNext = current.hasNext
  @inline def next() = current.next()

  def nextLine(): String = {
    val line = reader.readLine()
    current = iterator
    line
  }
  def nextString(): String = next()
  def nextBoolean(): Boolean = nextString().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(nextString(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(nextString(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(nextString(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(nextString(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(nextString(), radix)
  def nextFloat(): Float = nextString().toFloat
  def nextDouble(): Double = nextString().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(nextString())

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

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _588A extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val input = List.fill(n)((nextInt, nextInt))

  var curPrice = Int.MaxValue
  var ans = 0

  for {
    (a, p) <- input
  } {
    curPrice = curPrice min p
    ans += a*curPrice
  }

  ans
}) {
  override def format(result: Result) = super.format(result)
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

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

import CodeForcesApp._

object _588A extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val input = List.fill(n)((nextInt(), nextInt()))

    var curPrice = Int.MaxValue
    var ans = 0

    for {
      (a, p) <- input
    } {
      curPrice = curPrice min p
      ans += a*curPrice
    }

    ans
  }

  override def format(result: Result) = super.format(result)
}
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(line => new StringTokenizer(line))
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def nextTokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = tokenizers.find(_.hasMoreTokens)
    current
  }

  override def hasNext: Boolean = nextTokenizer().exists(_.hasMoreTokens)

  override def next(): String = nextTokenizer().get.nextToken()
  def nextInt(): Int = next().toInt

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

/**
  * Created by armanmac on 3/22/17.
  */

object Code {

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

    var days = scala.io.StdIn.readInt()
    var need: Array[Int] = new Array[Int](days)
    var price: Array[Int] = new Array[Int](days)

    for (i <- 0 to days - 1) {
      var str = scala.io.StdIn.readLine().split(' ')
      need(i) = str(0).toInt
      price(i) = str(1).toInt
    }

    var leastPrice = need(0) * price(0)
    var minPrice = price(0)

    for (i <- 1 to days - 1) {

      if(price(i)<minPrice)
        minPrice = price(i)

      if (price(i) < minPrice) {
        leastPrice += price(i) * need(i)
      }
      else {
        leastPrice += minPrice * need(i)

      }
    }

    println(leastPrice)

  }

}

import scala.io.StdIn._

object A extends App {
  val n = readInt()
  val A = Array.ofDim[(Int, Int)](n)

  for (i <- 0 until n) {
    val Array(a, p) = readLine().split(" ").map(_.toInt)
    A(i) = (a, p)
  }

  var day = 0
  var totalKg = 0
  var totalCost = 0
  while (day < n) {
    if (day + 1 >= n || A(day)._2 > A(day + 1)._2) {
      totalKg += A(day)._1
      totalCost += A(day)._1 * A(day)._2
      day += 1
    } else {
      var size = day + 1
      var localKg = A(day)._1
      while (size < n && A(day)._2 <= A(size)._2) {
        localKg += A(size)._1
        size += 1
      }
      totalKg += localKg
      totalCost += localKg * A(day)._2
      day = size
    }
  }

  println(totalCost)
}

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

object A_DuffAndMeat {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

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

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = br.readLine().trim().split(" ")
    val number = line1(0).toInt
    var data = new Array[(Int, Int)](number)
    for (i <- 0 until number) {
      val line = br.readLine().trim().split(" ")
      data(i) = (line(0).toInt, line(1).toInt)
    }
    //---------------------------- parameters reading end --------------------------------

    var minPrice = 101
    var result = 0
    for(i <- data) {
      if (minPrice > i._2) minPrice = i._2
      result += minPrice * i._1
    }

    println(result)
  }

//========================= samples ========================
val sa1 = """

"""

//========================= samples end ====================
}

import java.util

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val max = 1000000007;
    val n = readInt()

    val  A:Array[(Int,Int)] = Array.fill(n)(readTuple())

    var curPrice = 101
    var sum = 0;
    for(i <- 0 to n - 1) {
      if(A(i)._2 < curPrice) {
        sum+=A(i)._2 * A(i)._1
        curPrice = A(i)._2
      } else {
        sum+=curPrice * A(i)._1
      }
    }

    println(sum)

  }

  def readInt(): Int = StdIn.readInt()

  def readInts(): Array[Int] = StdIn.readLine().split(" ").map(_.toInt)

  def readTuple(): (Int, Int) = {
    val line = readInts
    (line(0), line(1))
  }

}

object Duff extends App {

  val n = scala.io.StdIn.readLine().toInt

  val inputs = for (ln <- 1 to n)
    yield scala.io.StdIn.readLine()

  val plans = inputs.map(_.split(" ").map(_.toInt).toList)

  val result = plans.map(e => (e(0), e(1), e(0) * e(1)))
    .reduce((e1, e2) => {
      val price = e1._2 min e2._2;
      (e2._1, price, e1._3 + e2._1 * price)
    })

  println(result._3)

}

object Duff extends App{

 val n =   scala.io.StdIn.readLine().toInt

  val inputs = for (ln <- 1 to n)
    yield scala.io.StdIn.readLine()

  val plans =     inputs.map( _.split(" ").map(_.toInt).toList)
  val (List(ignore, lowestPrice ), lowestDay)  = plans.zipWithIndex.minBy( _._1(1))

  val initSum = plans.zipWithIndex.filter( _._2 <= lowestDay)
    .map( e => e._1(0) * e._1(1)).sum

  val restSum = plans.zipWithIndex.filter(_._2 > lowestDay)
    .map( e => e._1(0) * lowestPrice).sum

  println(initSum + restSum)

}


import scala.io.StdIn
object Main {
  def main(args: Array[String]) = {
    val n = StdIn.readInt()
    def read = StdIn.readLine().split(" ").tail.toSet
    if ((read ++ read).size == n) {
      println("I become the guy.")
    } else {
      println("Oh, my keyboard!")
    }
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val levels = readLine.split(" ").drop(1).map(_.toInt).toSet ++ readLine.split(" ").drop(1).map(_.toInt).toSet

    println(if (((1 to n).toSet -- levels).isEmpty) "I become the guy." else "Oh, my keyboard!")
  }
}

import scala.collection.immutable.HashSet

object A469 {
  @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 input1 = {
      val t = tokenizeLine
      val num1 = t.nextToken.toInt
      Array.fill(num1)(t.nextToken.toInt)
    }

    val input2 = {
      val t = tokenizeLine
      val num1 = t.nextToken.toInt
      Array.fill(num1)(t.nextToken.toInt)
    }

    val set = collection.mutable.HashSet.empty[Int]
    input1.foreach {set += _}
    input2.foreach {set += _}

    if(set.size == n) {
      println("I become the guy.")
    } else {
      println("Oh, my keyboard!")
    }
  }
}

object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    def solve(i: Int, s: Set[Int]):Set[Int]= {
      if (i == 0) {
        s
      } else {
        solve(i - 1, s.+(cin.nextInt()))
      }
    }
    val n = cin.nextInt()
    val a = cin.nextInt()
    lazy val b = cin.nextInt()
    var s: Set[Int] = Set()
    s = s ++ solve(a, s)
    if(solve(b, s).size == n) {
      println("I become the guy.")
    } else {
      println("Oh, my keyboard!")
    }
  }
}

import scala.io.StdIn
object Main {
  def main(args: Array[String]) = {
    val n = StdIn.readInt()
    def read = StdIn.readLine().split(" ").tail.map(_.toInt).toSet
    if ((read ++ read).size == n) {
      println("I become the guy.")
    } else {
      println("Oh, my keyboard!")
    }
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object WanneBeTheGuy {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val n = readInt
     val l1 = readInts
     val l2 = readInts
     if ((l1.tail.toSet ++ l2.tail).size >= n)
       println("I become the guy.")
     else
       println("Oh, my keyboard!")
   }

}

import java.util.Scanner

object Main2 extends App {
  val scanner = new Scanner(System.in)
  val levelNumber = scanner.nextInt()
  val xLevelNumber = scanner.nextInt()
  val xLevels = 0.until(xLevelNumber).map(_ => scanner.nextInt())
  val yLevelNumber = scanner.nextInt()
  val yLevels = 0.until(yLevelNumber).map(_ => scanner.nextInt())
  println(if ((xLevels ++ yLevels).distinct.size == levelNumber) "I become the guy." else "Oh, my keyboard!")
}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val n = StdIn.readLine().toInt
    val S1:Set[Int] = StdIn.readLine().split(" ").map(_.toInt).tail.toSet
    val S2:Set[Int] = StdIn.readLine().split(" ").map(_.toInt).tail.toSet

    if((S1 ++ S2).size == n) {
      println("I become the guy.")
    } else {
      println("Oh, my keyboard!")
    }

  }

}

import java.util.Scanner

object TEST extends App {
    val n = readInt
    val merge = readLine.split(" ").toList.tail ::: readLine.split(" ").toList.tail
    val ans = if(merge.groupBy(x=>x).size == n) "I become the guy." else "Oh, my keyboard!"
    print(ans)
}

object Solution extends App {
  val n = readInt
  val p = readLine.split(" ").map(_.toLong)
  val q = readLine.split(" ").map(_.toLong)

  if(n == (p.tail ++ q.tail).toSet.size)
    println("I become the guy.")
  else
    println("Oh, my keyboard!")
}

object Main extends App {
  val n = readInt

  def readLevels = readLine.split(" ").map(_.toInt).toList.tail

  val a = readLevels
  val b = readLevels

  def play(level: Int): String = {
    if (level > n)
      "I become the guy."
    else if (a.contains(level) || b.contains(level))
      play(level + 1)
    else
      "Oh, my keyboard!"
  }

  println(play(1))
}

import scala.io.StdIn

object Task469A {
	def main(args: Array[String]) {
		val n = StdIn.readInt()
		val first = StdIn.readLine().split(" ").map(_.toInt)
		val second = StdIn.readLine().split(" ").map(_.toInt)
		if ((first.slice(1, first(0) + 1) ++ second.slice(1, second(0) + 1)).toSet.size == n) println("I become the guy.") else println("Oh, my keyboard!")
	}
}

object A extends App {
  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def nextInt = in.nextInt
  def nextDouble = in.nextDouble
  def nextString = in.next
  import scala.io.StdIn._
  val n = nextInt

  var i = 0
  var j = 0
  val m = scala.collection.mutable.Set[Int]()
  for (j <- 0 to 1) {
    val p = nextInt
      for (i <- 0 until p) {
        val x = nextInt
        m += x
        }
    }
    if (m.size == n)
        println("I become the guy.")
    else
        println("Oh, my keyboard!")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val first = in.next().split(" ").tail.map(_.toInt).toSet
  val second = in.next().split(" ").tail.map(_.toInt).toSet
  if (Range(1, n + 1).forall(t => first.contains(t) || second.contains(t)))
    println("I become the guy.")
  else
    println("Oh, my keyboard!")
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val levels = readLine.split(" ").drop(1).map(_.toInt).toSet ++ readLine.split(" ").drop(1).map(_.toInt).toSet

    println(if ((levels -- (1 to n)).isEmpty) "I become the guy." else "Oh, my keyboard!")
  }
}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val n = StdIn.readLine().toInt
    val A:Set[Int] = StdIn.readLine().split(" ").map(_.toInt).toSet
    val B:Set[Int] = StdIn.readLine().split(" ").map(_.toInt).toSet

    if((A ++ B).size == n) {
      println("I become the guy.")
    } else {
      println("Oh, my keyboard!")
    }

  }

}


import java.io.PrintWriter

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

object C {

  def main(args: Array[String]): Unit = {
    val in = io.Source.fromInputStream(System.in).getLines()
    //    val in = io.Source.fromFile("in.txt").getLines()
    val out = new PrintWriter(System.out)
    //    val out = new PrintWriter(new File("out.txt"))
    val n = in.next().toInt
    val a = in.next().split(" ").map(_.toInt).map(_ - 1)

    val g = ArrayBuffer.fill(n)(new ArrayBuffer[Int]())
    for (i<- 0 until n)
      g(i) = new ArrayBuffer[Int]()
    for (i <- 0 until n) {
      g(i) += a(i)
      g(a(i)) += i
    }

    val res = find_comps(n, g)
    out.println(res)

    out.flush()
    out.close()
  }

  def find_comps(n:Int, g: ArrayBuffer[ArrayBuffer[Int]]):Int = {
    val used = ArrayBuffer.fill(n)(false)
    var res = 0

    for (i<-0 until n) {
      if (!used(i)) {
        dfs(i,used, g)
        res+=1
      }
    }

    res
  }

  def dfs(v: Int, used: ArrayBuffer[Boolean], g: ArrayBuffer[ArrayBuffer[Int]]): Unit = {
    used(v) = true

    for (i <- g(v).indices) {
      if (!used(g(v)(i))) {
        dfs(g(v)(i), used, g)
      }
    }
  }
}

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

object _755C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val input = read[Vector[Int]]
    val ds = new UnionFind[Int]
    (1 to input.length).foreach(i => ds += i)

    input.zipWithIndex foreach {
      case (i, j) => ds.union(i, j + 1)
    }

    write(ds.sets.size)
  }

  class UnionFind[A] extends PartialFunction[A, A] with collection.generic.Growable[A] {
    private[this] val parent = mutable.Map.empty[A, A]

    private[this] def find(x: A): A = parent(x) match {
      case `x` => x
      case y =>
        parent(x) = find(y)
        parent(x)
    }

    override def isDefinedAt(x: A) = parent contains x

    override def apply(x: A) = find(x)

    override def +=(x: A) = {
      parent(x) = x
      this
    }

    override def clear() = parent.clear()

    def sets: Map[A, Iterable[A]] = parent.keys.groupBy(find)

    def union(x: A, y: A) = {
      // Randomized linking is O(an) too: http://www.cis.upenn.edu/~sanjeev/papers/soda14_disjoint_set_union.pdf
      // If input is randomized we don't need randomization anyway: http://codeforces.com/blog/entry/21476
      // Without any linking heuristics but only path compression, it is O(log n) too: http://stackoverflow.com/questions/2323351/
      if (scala.util.Random.nextBoolean()) parent(find(x)) = find(y) else parent(find(y)) = find(x)
    }
  }
}
/****************************[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
  }
  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")

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