Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met:  i-th box is not put into another box;  j-th box doesn't contain any other boxes;  box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!

The first line contains one integer n (1 ≤ n ≤ 5000) — the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the side length of i-th box.

Print the minimum possible number of visible boxes.

NoteIn the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1.

import java.io.FileReader
import java.util
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object Solution {
  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val boxes = readIntLine().sorted.reverse

    var piles : ArrayBuffer[List[Int]] = new ArrayBuffer[List[Int]]()

    for (box <- boxes) {
      var placed = false
      for (i <- piles.indices) {
        if (!placed && piles(i).head > box) {
          piles(i) = box :: piles(i)
          placed = true
        }
      }
      if (!placed) {
        piles.append(List(box))
      }
    }
    println(piles.length)
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    readLine().split(" ").map(BigInt.apply)
  }
}

object C extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val b = a.sorted.foldLeft(List.empty[Int]) ((l, i) => {
    if (l.isEmpty) i :: l
    else if (l.head < i) l.tail :+ i
    else i :: l
  })

  println(b.length)
}

object C extends App {
  val n = scala.io.StdIn.readInt()
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val b = a.sorted.foldLeft(List.empty[Int]) ((l, i) => {
    if (l.isEmpty) i :: l
    else if (l.head < i) i :: l.tail
    else i :: l
  })

  println(b.length)
}


Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.  Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.

If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print  - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.

NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is  - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is  - 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().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 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)
}

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 {

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


Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of days. The second line contains n space-separated integers m1, m2, ..., mn (0 ≤ mi < i) — the number of marks strictly above the water on each day.

Output one single integer — the minimum possible sum of the number of marks strictly below the water level among all days.

NoteIn the first example, the following figure shows an optimal case.  Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0 + 0 + 2 + 0 + 3 + 1 = 6.In the second example, the following figure shows an optimal case.

object D extends App {

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

  val Array(n) = readInts(1)
  val ms = readInts(n)

  var res = 0L

  val totals = Array.ofDim[Int](n)

  totals(0) = ms(0) + 1
  for (i <- 1 until n) {
    totals(i) = Math.max(totals(i - 1), ms(i) + 1)
  }

  var total = totals.last

  for (i <- ms.indices.reverse) {
    total = Math.max(totals(i), total - 1)
    res += (total - ms(i) - 1)
    //println(i + 1, total - ms(i) - 1, res, total)
    //if (total > i) total = i
  }

  println(res)
}


Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.  There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ..., an and p1, ..., pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

The first line of input contains integer n (1 ≤ n ≤ 105), the number of days. In the next n lines, i-th line contains two integers ai and pi (1 ≤ ai, pi ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

Print the minimum money needed to keep Duff happy for n days, in one line.

NoteIn the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

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

}

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

}

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)

}


VK news recommendation system daily selects interesting publications of one of $$$n$$$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $$$i$$$ batch algorithm selects $$$a_i$$$ publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $$$i$$$-th category within $$$t_i$$$ seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.

The first line of input consists of single integer $$$n$$$ — the number of news categories ($$$1 \le n \le 200\,000$$$). The second line of input consists of $$$n$$$ integers $$$a_i$$$ — the number of publications of $$$i$$$-th category selected by the batch algorithm ($$$1 \le a_i \le 10^9$$$). The third line of input consists of $$$n$$$ integers $$$t_i$$$ — time it takes for targeted algorithm to find one new publication of category $$$i$$$ ($$$1 \le t_i \le 10^5)$$$.

Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.

NoteIn the first example, it is possible to find three publications of the second type, which will take 6 seconds.In the second example, all news categories contain a different number of publications.

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val aC = (1 to n).map{ _ => in.nextInt()}
    val aT = (1 to n).map{ _ => in.nextLong()}
    val aCT = (aC.zip(aT)).sorted.toArray
    val limits = Array.fill(n+1)(0)
    val v = Array.fill(n+1)(0)
    var M = 0
    aCT.indices.foreach{ i =>
      val (c,_) = aCT(i)
      if(i == 0){
        limits(M) = i
        v(M) = c
        M += 1
      }else{
        if(v(M-1) == c){
          limits(M-1) = i
        }else{
          limits(M) = i
          v(M) = c
          M += 1
        }
      }
    }
    val m2i = (0 to M).map{ i =>
      v(i) -> i
    }.toMap

    val arST: Array[Long] = aCT.map{case (_,tt) => tt}
    val st = new SegmentTree(n+2)
    st.build(arST)
    var ans = 0L

    var pos = 0

    while(pos < n){
      //doing here is bc all prev was good
      var indx = m2i(aCT(pos)._1)
      val startingValue = v(indx)
      val start = pos
      var end = limits(indx)

      var currentValue = startingValue
      var loopsNeeded = end-start
      while(loopsNeeded>0){

        val (i,sum) = st.query(start,end+1)
        ans += sum-arST(i)

        st.update(i,0L)
        currentValue += 1
        loopsNeeded -= 1
        if(indx+1 < M && currentValue == v(indx+1)){
          //increase range
          indx += 1
          end = limits(indx)
          loopsNeeded += limits(indx)-limits(indx-1)
        }
      }
      pos = end+1

    }

    out.println(ans)

  }

  trait Node[T]{
      def + (other: Node[T]): Node[T]
      def value: T
    }

    case class MaxSum(value: (Int,Long,Long)) extends Node[(Int,Long,Long)]{
      override def +(other: Node[(Int,Long,Long)]): Node[(Int,Long,Long)] = {
        val (i,a,b) = value
        val (j,x,y) = other.value
        MaxSum((if(a>x) i else j,Math.max(a,x),b+y))
      }
    }
    class SegmentTree(maxN: Int){

      val sumRange: Array[Long] = Array.fill(maxN*4+2)(0L)
      val indxMaxValue: Array[Int] = Array.fill(maxN*4+2)(0)
      var actualValues: Array[Long] = Array.empty[Long]
      var N: Int = 0
      def build(nodes: Array[Long]): Unit = {
        N = nodes.length
        actualValues = nodes
        build(nodes,0,N,0)
      }
      private def build(nodes: Array[Long], left: Int, right: Int, n: Int): Unit ={
        if(left+1 == right){
          sumRange(n) = nodes(left)
          indxMaxValue(n) = left

        }else{
          val m = (left+right)/2
          build(nodes,left,m,n*2+1)
          build(nodes,m,right,n*2+2)
          sumRange(n) = sumRange(n*2+1)+sumRange(n*2+2)
          indxMaxValue(n) = {
            if(actualValues(indxMaxValue(n*2+1)) > actualValues(indxMaxValue(n*2+2))){
              indxMaxValue(n*2+1)
            }else{
              indxMaxValue(n*2+2)
            }
          }
        }
      }

      def query(left: Int, right: Int): (Int,Long) = query(0,0,N,left,right)
      private def query(n: Int,n0: Int, nn: Int, left: Int, right: Int): (Int,Long) = {

        if(n0 == left && nn == right) {
          (indxMaxValue(n),sumRange(n))
        } else{
          val m = (n0+nn)/2
          if(left >= m){
            query(n*2+2,m,nn,left,right)
          }else{
            if( right <= m){
              query(n*2+1,n0,m,left,right)
            }else{
              val (i,sumLeft) = query(n*2+1,n0,m,left,m)
              val (j,sumRight) = query(n*2+2,m,nn,m,right)
              val k = {
                if(actualValues(i) > actualValues(j)){
                  i
                }else{
                  j
                }
              }
              (k,sumLeft+sumRight)
            }
          }
        }
      }

      def update(i: Int, value: Long): Unit = update(0,i,0,N,value)

      private def update(n: Int, pos: Int, left: Int, right: Int, v: Long): Unit = {
        if(pos >= left && pos < right){
          if (left + 1 == right) {
            sumRange(n) = v
            actualValues(left) = v
          } else {
            val m = (left + right) / 2
            update(n*2+1,pos,left,m,v)
            update(n*2+2,pos,m,right,v)
            sumRange(n) = sumRange(n * 2 + 1) + sumRange(n * 2 + 2)
            indxMaxValue(n) = {
              if(actualValues(indxMaxValue(n*2+1)) > actualValues(indxMaxValue(n*2+2))){
                indxMaxValue(n*2+1)
              }else{
                indxMaxValue(n*2+2)
              }
            }
          }
        }
      }

    }

  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?

The first line contains a single integer n (1 ≤  n ≤ 100).  The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a1, a2, ..., ap (1 ≤ ai ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.

If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).

NoteIn the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.In the second sample, no one can pass level 4.

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 (((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
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.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.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!")
    }

  }

}