object B1037 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val temp = stdin.readLine.trim.split(" ").map(_.toLong)
    val (n,s) = (temp(0), temp(1))
    val array = stdin.readLine.trim.split(" ").map(_.toLong).sorted
    val p = ((n-1)/2).toInt
    val ans: Long = if (array(p)-s > 0) {
      array.slice(0,p+1).filter(_ > s).map(x => x-s).sum
    } else {
      if (array(p)-s < 0) {
        array.slice(p,n.toInt).filter(_ < s).map(x => s-x).sum
      }  else 0L
    }
    print(ans)
  }
}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val s = in.nextInt
    val a: Array[Int] = Array.fill(n)(in.nextInt)
    util.Sorting.quickSort(a)
    var i = n / 2
    var ans: Long = 0

    if (a(n / 2) < s) {
      while (i < n && a(i) < s) {
        ans += s - a(i)
        i += 1
      }
    } else {
      while (i >= 0 && a(i) > s) {
        ans += a(i) - s
        i -= 1
      }
    }
    println(ans)

  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)

    Sorting.quickSort(A)
    var ans = 0L
    rep_r(N / 2 + 1, N / 2) { i =>
      val a = A(i)
      if (a < M) {
        ans += M - a
      }
    }

    rep_r(N / 2 + 1) { i =>
      val a = A(i)
      if (a > M) {
        ans += a - M
      }
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.StringTokenizer

import scala.io.StdIn

object B extends App with Reader {
  read()
  val n = int()
  val s = int()
  read()
  val a = Array.fill(n)(int()).sorted
  val m = n / 2

  var res = 0L

  for (i <- 0 to m) {
    if (a(i) > s) res += a(i) - s
  }
  for (i <- m until n) {
    if (a(i) < s) res += s - a(i)
  }

  println(res)
}

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

object Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)
  val sc = new InputReader(System.in)

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)

    Sorting.quickSort(A)
    var ans = 0L
    rep_r(N / 2 + 1, N / 2) { i =>
      val a = A(i)
      if (a < M) {
        ans += M - a
      }
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.StringTokenizer

import scala.io.StdIn

object B extends App with Reader {
  read()
  val n = int()
  val s = int()
  read()
  val a = Array.fill(n)(int()).sorted
  val m = n / 2

  var res = 0

  for (i <- 0 to m) {
    if (a(i) > s) res += a(i) - s
  }
  for (i <- m until n) {
    if (a(i) < s) res += s - a(i)
  }

  println(res)
}

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

object B1037 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val temp = stdin.readLine.trim.split(" ").map(_.toInt)
    val (n,s) = (temp(0), temp(1))
    val array = stdin.readLine.trim.split(" ").map(_.toInt).sorted
    val p = (n-1)/2
    val ans = if (array(p)-s > 0) {
      array.slice(0,p+1).filter(_ > s).map(x => x-s).sum
    } else if (array(p)-s < 0) {
      array.slice(p,n+1).filter(_ < s).map(x => s-x).sum
    }
    print(ans)
  }
}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val s = in.nextInt
    val a: Array[Int] = Array.fill(n)(in.nextInt)
    util.Sorting.quickSort(a)
    var i = n / 2
    var ans = 0

    if (a(n / 2) < s) {
      while (i < n && a(i) < s) {
        ans += s - a(i)
        i += 1
      }
    } else {
      while (i >= 0 && a(i) > s) {
        ans += a(i) - s
        i -= 1
      }
    }
    println(ans)

  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

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

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

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

  def solve(): Unit = {
    val N = ni()
    val A = na(2 * N)
    val sum = A.sum
    val half = A.take(N).sum
    if (half * 2 == sum) {
      REP(N) { i =>
        REP(N) { j =>
          if (A(i) != A(N + j)) {
            val t = A(i)
            A(i) = A(N + j)
            A(N + j) = t
            out.println(A.mkString(" "))
            return
          }
        }
      }
      out.println(-1)
    } else {
      out.println(A.mkString(" "))
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val arr = io.read[Seq, Int](2*n)
    val ans = arr.distinct.size match {
      case 1 => "-1"
      case _ => arr.sorted.mkString(" ")
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    val ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labelString(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    var cnt = input(0).split(" ").map(_.toInt)
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    var ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labelString(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    val labels = Array("S","M","L","XL","XXL","XXXL")
    val labelMap = labels.zipWithIndex.toMap
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelMap).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    val ans = new Array[Int](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = shirt._1.head
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = shirt._1.head
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = shirt._1.last
      }
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.map(labels).mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    var ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labelString(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    val labels = Array("S","M","L","XL","XXL","XXXL")
    val labelMap = labels.zipWithIndex.toMap
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelMap).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    val ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labels(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labels(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labels(shirt._1.last)
      }
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    var cnt = input(0).split(" ").map(_.toInt)
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    var ans = new Array[String](n)
    for(shirt <- single)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}


object B454 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readInts(n)
    var idx = -1
    for(i <- 1 until n if idx == -1)
      if(a(i-1) > a(i))
        idx = i
    if(idx != -1) {
      val newA = a.takeRight(n-idx) ++ a.take(idx)
      if(newA.zip(a.sorted).forall(arr => arr._1 == arr._2))
        println(n-idx)
      else
        println("-1")
    } else {
      if(a.sorted.zip(a).forall(arr => arr._1 == arr._2))
        println("0")
      else
        println("-1")
    }
  }

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

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

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

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

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

}

import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 01.08.14.
 */
object B extends App {

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    if (a.toList == a.sorted.toList) {
      out.println(0)
    } else {
      var r = -1
      for (i <- n - 1 to 1 by(-1) if r == -1) {
        if (a(i) < a(i - 1)) {
          r = i
        }
      }
      //out.println(r)
      val b = a.takeRight(n - r) ++ a.take(r)
      //out.println(b.toList)
      if (b.toList == b.sorted.toList) {
        out.println(n - r)
      } else {
        out.println(-1)
      }
    }

  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

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

object B {

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

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

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

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

  def smartSolver(n: Int, a: Array[Int]): Int = {
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev <= a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      else {
        prev = a(ind)
        ind = (ind + 1) % n
        terminate += 1
      }
    }
    if (flag) {
      return n - ind - 1
    } else {
      return -1
    }
  }

  def stupidSolver(n: Int, a: Array[Int]): Int = {
    var ans = 1000000
    for (i <- 0 until n) {
      var len = 0
      var ind = i
      var cnt = 0
      var prev = a(ind)
      while (len < n - 1) {
        ind = (ind + 1) % n
        if (prev <= a(ind)) {
          cnt += 1
        }
        len += 1
        prev = a(ind)
      }
      if (cnt == n - 1) {
        ans = Math.min(i, ans)
      }
    }
    return ans
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    //    val rand = new Random
    //    for (i <- 0 until n) {
    //      a(i) = rand.nextInt(5)
    //    }
    //    for (i <- 0 until n) {
    //      out.print(a(i) + " ")
    //    }
    //    out.println
    //    out.println("smart = " + smartSolver(n, a))
    //    out.println("stupid = " + stupidSolver(n, a))
    out.println(smartSolver(n, a))
    return 1
  }

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val min = data.min
  if (data.forall(_ == min))
    println(0)
  else {
    var start = data.indexOf(min)
    if (start == 0)
      if (data.last == min) {
        start = n - 1
        while (data(start - 1) == min)
          start = start - 1
      }
    val candidate = (start to start + n - 1).map(i => data(i % n))

    if (candidate.tail.foldLeft((false, min)){
      case((true, prev), el) => (true, el)
      case((false, prev), el) => (prev > el, el)
    }._1)
      println(-1)
    else
      println((n - start) % n)
  }
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object B extends App {

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

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

  var i = 1

  while (i < n && as(i) >= as(i - 1)) i += 1
  if (i == n) {
    println(0)
    System.exit(0)
  }

  if (as.last > as.head) {
    println(-1)
    System.exit(0)
  }
  //println(i)
  var j = n - 2
  while (j >= i && as(j) <= as(j + 1)) j -= 1
  //println(j)
  if (j < i && as(j + 1) <= as.head) println(n - j - 1)
  else println(-1)
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object B extends App {

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

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

  var i = 1

  while (i < n && as(i) >= as(i - 1)) i += 1
  if (i == n) {
    println(0)
    System.exit(0)
  }

  if (as.last > as.head) {
    println(-1)
    System.exit(0)
  }

  var j = n - 2
  while (j >= i && as(j) >= as(j + 1)) j -= 1

  if (j < i) println(n - j - 1)
  else println(-1)
}

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

object B {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev <= a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      prev = a(ind)
      ind = (ind + 1) % n
      terminate += 1
    }
    if (flag) {
      out.println(terminate - n + 1)
    } else {
      out.println(-1)
    }
    return 1
  }

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

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

object B {

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

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

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

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

  def smartSolver(n: Int, a: Array[Int]): Int = {
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev <= a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      else {
        prev = a(ind)
        ind = (ind + 1) % n
        terminate += 1
      }
    }
    if (flag) {
      return terminate - n + 2
    } else {
      return -1
    }
  }

  def stupidSolver(n: Int, a: Array[Int]): Int = {
    var ans = 1000000
    for (i <- 0 until n) {
      var len = 0
      var ind = i
      var cnt = 0
      var prev = a(ind)
      while (len < n - 1) {
        ind = (ind + 1) % n
        if (prev <= a(ind)) {
          cnt += 1
        }
        len += 1
        prev = a(ind)
      }
      if (cnt == n - 1) {
        ans = Math.min(i, ans)
      }
    }
    return ans
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    //    val rand = new Random
    //    for (i <- 0 until n) {
    //      a(i) = rand.nextInt(100)
    //    }
    //    for (i <- 0 until n) {
    //      out.print(a(i) + " ")
    //    }
    //    out.println
    //    out.println("smart = " + smartSolver(n, a))
    //    out.println("stupid = " + stupidSolver(n, a))
    out.println(smartSolver(n, a))
    return 1
  }

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

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

object B {

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

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

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

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

  def smartSolver(n: Int, a: Array[Int]): Int = {
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev < a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      else {
        prev = a(ind)
        ind = (ind + 1) % n
        terminate += 1
      }
    }
    if (flag) {
      return terminate - n + 2
    } else {
      return -1
    }
  }

  def stupidSolver(n: Int, a: Array[Int]): Int = {
    var ans = 1000000
    for (i <- 0 until n) {
      var len = 0
      var ind = i
      var cnt = 0
      var prev = a(ind)
      while (len < n - 1) {
        ind = (ind + 1) % n
        if (prev <= a(ind)) {
          cnt += 1
        }
        len += 1
        prev = a(ind)
      }
      if (cnt == n - 1) {
        ans = Math.min(i, ans)
      }
    }
    return ans
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
//    val rand = new Random
//    for (i <- 0 until n) {
//      a(i) = rand.nextInt(5)
//    }
//    for (i <- 0 until n) {
//      out.print(a(i) + " ")
//    }
//    out.println
//    out.println("smart = " + smartSolver(n, a))
//    out.println("stupid = " + stupidSolver(n, a))
        out.println(smartSolver(n, a))
    return 1
  }

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


import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {
    val a1 = s.nextLong()
    val k = s.nextLong()

    var i: Long = 1L
    var ai: Long = a1

    while(i < k && minDigit(ai) != 0) {
      i += 1
      ai = ai + minDigit(ai) * maxDigit(ai)
    }

    println(ai)
  }

  def minDigit(n: Long): Long = {
    n.toString.min - '0'
  }
  def maxDigit(n: Long): Long = {
    n.toString.max - '0'
  }

}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

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

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

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

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

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

  val t = in.nextInt()

  for (_ <- 1 to t) {
    var a1 = in.nextLong()
    var k = in.nextLong()

    while (k > 1) {
      k = k - 1
      a1 = a1 + (a1.toString.min.toInt - 48) * (a1.toString.max.toInt - 48)
      if (a1.toString.contains('0'))  k = 0
    }
    println(a1)
  }

}

import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {

  @tailrec
  private def perform(start: Long, element: Long, last: Long = -1): Long = {
    (start, element) match {
      case (s, 1) => s
      case (s, _) if s == last => s
      case (s, e) =>
        val sth = ((s.toString.max - '0').toLong * (s.toString.min - '0').toLong) + s
        perform(sth, e - 1, start)
    }
  }

  def foo(list: List[(Long, Long)]) = {
    list.map(x => perform(x._1, x._2))
  }

 val scan = new Scanner(System.in)
 val n = scan.nextLong()
 val seq = for {
   _ <- 0.toLong until n.toLong
   (x, y) = (scan.nextLong(), scan.nextLong())
 } yield x -> y

  foo(seq.toList).foreach(println)

}

import scala.collection.mutable.ArrayBuffer

object CodeforcesRound643a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

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

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

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    var Array(a1, k) = rll_long
    (2L to Math.min(k, 100L)).foreach(_ => a1 = a1 + minDigit(a1) * maxDigit(a1))
    writer.println(a1)
  }

  def minDigit(n: Long): Long = {
    digits(n).fold(9L) { case (a, b) => Math.min(a, b) }
  }

  def maxDigit(n: Long): Long = {
    digits(n).fold(0L) { case (a, b) => Math.max(a, b) }
  }

  // Allocates memory, but should work
  def digits(n: Long): Array[Long] = {
    val digits = ArrayBuffer[Long]()
    var nn = n
    while (nn > 0) {
      digits.append(nn % 10L)
      nn = nn / 10
    }
    if (digits.isEmpty) {
      Array(0L)
    } else {
      digits.toArray
    }
  }

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

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

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

}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C643A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

class C643A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val a = nl()
      val k = nl()

      var continue = true
      var run = 1
      var vl = a
      while (continue && run < k) {
        val x = vl + minE(vl) * maxE(vl)
        if(x == vl) continue = false
        run += 1
        vl = x
      }

      out.println(vl)
    }
  }

  def minE(u: Long): Int = {
    var v = u
    var rt = 10

    while (v > 0) {
      if(v % 10 < rt) rt = (v % 10).toInt
      v /= 10
    }
    rt
  }

  def maxE(u: Long): Int = {
    var v = u
    var rt = -1

    while (v > 0) {
      if(v % 10 > rt) rt = (v % 10).toInt
      v /= 10
    }
    rt
  }
}

object A extends App {
  private def an(a1: Long, n: Long): Long = {
    def go(a1: String, n: Long): String =
      if (a1.contains('0') || n == 1) a1
      else go((a1.toLong + (a1.min - 48) * (a1.max - 48)).toString(), n - 1)

    go(a1.toString, n).toLong
  }

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a1, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val ai = an(a1, k)

    println(ai)
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a1, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    var i  = 1L
    var ai = a1
    var ds = (a1 % 10, a1 % 10)

    while (i < k && ds._1 != 0) {
      var a = ai
      ds = (a % 10, a % 10)
      while (a != 0 && ds._1 != 0) {
        val d = a % 10
        a /= 10
        ds = (if (d < ds._1) d else ds._1, if (d > ds._2) d else ds._2)
      }

      i += 1L
      ai += ds._1 * ds._2
    }

    println(ai)
  }
}

import scala.io.StdIn._

object solver {
    def main(args:Array[String]) = {
        val t:Int = readInt()

        (1 to t).foreach(_=>{
            val Array(a1,k) = readLine.split(" ").map(_.toLong)
            def transform(a:Long,k:Long):Long = {
                val x = a.toString.split("").map(_.toLong).toList
                if(x.min==0) a
                else if(k==1) a
                else transform(x.min*x.max+a,k-1)
            }

            println(transform(a1,k))
            ()
        })
    }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(a1, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    var i  = 1L
    var ai = a1
    var ds = (a1 % 10, a1 % 10)

    do {
      var a = ai
      ds = (a % 10, a % 10)
      while (a != 0 && (ds._1 != 0 || ds._2 != 9)) {
        val d = a % 10
        a /= 10
        ds = (if (d < ds._1) d else ds._1, if (d > ds._2) d else ds._2)
      }

      i += 1L
      ai += ds._1 * ds._2
    } while (i < k && (ds._1 != 0 || ds._2 != 9))

    println(ai)
  }
}

import scala.io.StdIn._

object solver {
    def main(args:Array[String]) = {
        val t:Int = readInt()

        (1 to t).foreach(_=>{
            val Array(a1,k) = readLine.split(" ").map(_.toInt)
            def transform(a:Int,k:Int):Int = {
                val x = a.toString.split("").map(_.toInt).toList
                if(x.min==0) 0
                else if(k==1) a
                else transform(x.min*x.max+a,k-1)
            }

            println(transform(a1,k))
            ()
        })
    }
}

import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {

  @tailrec
  private def perform(start: Long, element: Long, last: Long = -1): Long = {
    (start, element) match {
      case (s, 0) => s
      case (s, _) if s == last => s
      case (s, e) =>
        val sth = ((s.toString.max - '0').toLong * (s.toString.min - '0').toLong) + s
        perform(sth, e - 1, start)
    }
  }

  def foo(list: List[(Long, Long)]) = {
    list.map(x => perform(x._1, x._2))
  }

 val scan = new Scanner(System.in)
 val n = scan.nextLong()
 val seq = for {
   _ <- 0.toLong until n.toLong
   (x, y) = (scan.nextLong(), scan.nextLong())
 } yield x -> y

  foo(seq.toList).foreach(println)

}


import io.StdIn._

import scala.collection.mutable._

object Solution {

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

  def main(args: Array[String]) {
    val n = readLine().toInt

    val a = readInts(n)

    val s = HashSet.empty[Int]
    val sb = ArrayBuilder.make[(Int, Int)]()

    var k = 0
    var b = 0

    for (i <- 0 to n-1) {
      if (s.contains(a(i))) {
        k += 1
        sb += ((b + 1, i + 1))
        s.clear()
        b = i + 1
      } else {
        s.add(a(i))
      }
    }

    if (k == 0) println(-1)
    else {
      println(k)
      val res = sb.result()
      res(res.length-1) = (res.last._1, n)
      res.foreach{ case (x, y) => println(x + " " + y)}
    }

//    Console.withOut(new java.io.BufferedOutputStream(Console.out))
//    println(res.mkString("\n"))
//    Console.flush
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val l = data.indices.foldLeft((Set.empty[Int], List.empty[(Int, Int)], 0)) {
    case ((set, list, start), i) if set.isEmpty => (set + data(i), list, i)
    case ((set, list, start), i) if set.contains(data(i)) => (Set.empty[Int], (start + 1, i + 1) :: list, i)
    case ((set, list, start), i) => (set + data(i), list, start)
  }._2
  if (l.isEmpty)
    println(-1)
  else {
    println(l.length)
    println(l.tail.reverse.map(i => s"${i._1} ${i._2}").mkString("\n"))
    println(s"${l.head._1} ${data.length}")
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val l = data.indices.foldLeft((Set.empty[Int], List.empty[(Int, Int)], 0)) {
    case ((set, list, start), i) if set.isEmpty => (set + data(i), list, i)
    case ((set, list, start), i) if set.contains(data(i)) => (Set.empty[Int], (start + 1, i + 1) :: list, i)
    case ((set, list, start), i) => (set + data(i), list, start)
  }._2
  if (l.length == 0)
    println(-1)
  else {
    println(l.length)
    println(l.reverse.map(i => s"${i._1} ${i._2}").mkString("\n"))
  }
}


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

  override def apply(io: IO): io.type = {
    val isRight = io.read[Vector[Int]].reverse

    def chop(x: Int) = isRight.length - isRight.prefixLength(_ == x)

    val ans = chop(1) min chop(0)

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn
import scala.math.min

object A1143 {
  def main(args: Array[String]): Unit = {
    StdIn.readLine
    val a = StdIn.readLine.filter(_!=' ').toArray
    println(1+min(a.lastIndexOf('0'),a.lastIndexOf('1')))
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer
  import java.util.Arrays

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    var L = A.count(_ == 0)
    var R = N - L

    var i = 0
    while(L > 0 && R > 0) {
      if (A(i) == 0) L -= 1
      else R -= 1
      i += 1
    }
    out.println(i)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

import scala.math._, scala.io.StdIn._

object A extends App {
  val Array(n) = readInts
  val a = readInts

  val ar = a.reverse

  println(n - max(ar.prefixLength(_==0), ar.prefixLength(_==1)))

  def readInts() = readLine.split(" ").map(_.toInt)
}

import scala.io.StdIn
import scala.util.control.Breaks._

object Hello extends App {

  val n = StdIn.readInt()
  val doors = StdIn.readLine().split(" ").map(_.trim.toInt)
  breakable {
    for (i <- n - 1 to 1 by -1) {
      if (doors(i) != doors(i - 1)) {
        println(i)
        break
      }
    }
  }
}


import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {
  val sc = new Scanner(System.in)

  val format = sc.nextInt()
  val s = sc.next().toCharArray
  if (format == 24) {
    if(s(1) < '4')
      s(0) = List(s(0), '2').min
    else
      s(0) = List(s(0), '1').min
  }
  else {
    if(s(1) < '3')
      s(0) = List(s(0), '1').min
    else
      s(0) = '0'
  }
  s(3) = List(s(3), '5').min
  if(format == 12 && s(0) == '0' && s(1) == '0')
    s(0) = '1'

  println(new String(s))
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    val hourHeadLimit : Int
    def predicate(hour: String): Boolean

    // "00:05"
    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else if(hour.last.toString.toInt == 0 && hour.head.toString.toInt > hourHeadLimit ) s"1${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    val hourHeadLimit = 1
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    val hourHeadLimit = 2
    def predicate(hour: String): Boolean = hour.toInt < 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object A extends App {

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

  val fmt = readLine
  val t = readLine.toCharArray

  if (fmt == "12") {
    if (t(0) == '0' && t(1) == '0') t(1) = '1'
    if (t(0) == '1' && t(1) > '2') t(1) = '1'
    if (t(0) > '1' && t(1) == '0') {
      t(0) = '1'
    }
    if (t(0) > '1' && t(1) > '0') t(0) = '0'
  } else {
    if (t(0) > '2') t(0) = '0'
    if (t(0) == '2' && t(1) > '3') t(0) = '0'
  }

  if (t(3) > '5') t(3) = '0'

  println(t.mkString)
}

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

object _722A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val f = read[Int]
    val input = read[String]

    val all = for {
      h <- if (f == 12) 1 to 12 else 0 to 23
      hh = if (h < 10) "0" + h else h.toString
      m <- 0 until 60
      mm = if (m < 10) "0" + m else m.toString
    } yield hh + ":" + mm

    val ans = all minBy {choice => choice.zip(input).count {case (a, b) => a != b}}

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  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): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

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

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

object test extends App {
	val sc = new Scanner(System.in)

	val format = sc.nextInt()
	val clockTime = sc.next().toCharArray

	if (clockTime(3) > '5')
		clockTime(3) = '5'
	if (format == 24) {
		if (clockTime(1) < '4')
			clockTime(0) = List(clockTime(0), '2').min
		else
			clockTime(0) = List(clockTime(0), '1').min
	}
	else {
		clockTime(0) = {
			if (clockTime(1) < '3')
				List(clockTime(0), '1').min
			else
				'0'
		}
		if (clockTime(1) == '0' && clockTime(0) == '0')
			clockTime(0) = '1'
	}

	println(new String(clockTime))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours =
    if (format == 12 && hours == "00") s"01"
    else if (format == 12 && hours.toInt > format && hours.last == '0') s"10"
    else if (format == 12 && hours.toInt > format) s"0${hours.last}"
    else if (hours.toInt >= 24) s"0${hours.last}" else hours

  println(s"$fixedHours:$fixedMinutes")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours =
    if (format == 12 && hours == "00") s"01"
    else if (format == 12 && hours.toInt > format && hours.last == 0) s"10"
    else if (format == 12 && hours.toInt > format) s"0${hours.last}"
    else if (hours.toInt >= 24) s"0${hours.last}" else hours

  println(s"$fixedHours:$fixedMinutes")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours =
    if (format == 12 && hours == "00") s"01"
    else if (hours.toInt >= format) s"0${hours.last}" else hours

  println(s"$fixedHours:$fixedMinutes")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val format = in.next().toInt
  val Array(hours, minutes) = in.next().split(":")
  val fixedMinutes = if (minutes.toInt >= 60) s"0${minutes.last}" else minutes
  val fixedHours = if (hours.toInt >= format) s"0${hours.last}" else hours
  println(s"$fixedHours:$fixedMinutes")
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {
  val sc = new Scanner(System.in)

  val format = sc.nextInt()
  val s = sc.next().toCharArray
  if (format == 24) {
    if(s(1) < '4')
      s(0) = List(s(0), '2').min
    else
      s(0) = List(s(0), '1').min
  }
  else {
    if(s(1) < '3')
      s(0) = List(s(0), '1').min
    else
      s(0) = '0'
  }
  if(s(4) == '0')
    s(3) = List(s(3), '6').min
  else
    s(3) = List(s(3), '5').min
  if(format == 12 && s(0) == '0' && s(1) == '0')
    s(0) = '1'

  println(new String(s))
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: String): Boolean

    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else s"0${hour.last}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt >= 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: String): Boolean

    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: Int): Boolean
    def repairHour(hour: Int): String = hour match {
      case hh if predicate(hh) => hh.toString
      case hh =>
        val (decena, unidad) = (hh.toString.head, hh.toString.last)
        s"0$unidad"
    }
    def repairMinutes(minutes: Int): String = minutes match {
      case mm if mm <= 59 && mm >= 0 => mm.toString
      case mm =>
        val unidad = mm.toString.last
        s"0$unidad"
    }
    def repair(): String = {
      val (hh, mm): Tuple2[Int, Int] = time.split(":").map(_.toInt).toList match {
        case x :: y :: Nil => (x, y)
        case _ => (0, 0)
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: Int): Boolean = hour <= 12 && hour >= 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: Int): Boolean = hour <= 24 && hour >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    val hourHeadLimit : Int
    def predicate(hour: String): Boolean

    // "00:05"
    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else if(hour.last.toString.toInt == 0 && hour.head.toString.toInt > hourHeadLimit ) s"1${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else s"0${minutes.last}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    val hourHeadLimit = 1
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    val hourHeadLimit = 2
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

object BrokenClock extends App {
  val format = Console.in.readLine().toInt
  val timeDisplayed = Console.in.readLine()

  abstract class Clock(time: String)  {
    def predicate(hour: String): Boolean

    def repairHour(hour: String): String =
      if(predicate(hour)) hour
      else if(hour.last.toString.toInt > 0 ) s"0${hour.last}"
      else s"0${hour.last.toString.toInt + 1}"

    def repairMinutes(minutes: String): String =
      if(minutes.toInt <= 59 && minutes.toInt >= 0)  minutes
      else if(minutes.last.toString.toInt > 0 ) s"0${minutes.last}"
      else s"0${minutes.last.toString.toInt + 1}"

    def repair(): String = {
      val (hh, mm): Tuple2[String, String] = time.split(":").toList match {
        case x :: y :: Nil => (x, y)
        case _ => ("00", "00")
      }
      s"${repairHour(hh)}:${repairMinutes(mm)}"
    }
  }
  case class Clock12Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 12 && hour.toInt > 0
  }
  case class Clock24Format(time: String) extends Clock(time) {
    def predicate(hour: String): Boolean = hour.toInt <= 24 && hour.toInt >= 0
  }

  object TimeFactory {
    def apply(format: Int, time: String): Clock = format match {
      case 12 => Clock12Format(time)
      case 24 => Clock24Format(time)
    }
  }

  def execute(fmt: Int, time: String): String = {
    val clock: Clock = TimeFactory(fmt, time)
    clock.repair()
  }

  println { execute(format, timeDisplayed) }
}

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

object _722A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val f = read[Int]
    var Array(h, m) = read[String].split(':')
    var ans = 0

    if(m.toInt > 59) {
      ans += 1
      m = "0" + m(1)
    }

    if(h.toInt > f) {
      ans += 1
      h = "0" + h(1)
    }

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

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

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

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

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

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

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

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

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