import scala.io.Source

object Contest extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val arrays = new Array[Array[Long]](t)
  for (i <- 0 until t) {
    val n = input.next()
    arrays(i) = input.next().split(" ").map(_.toLong)
  }

  arrays.map(calc).foreach(println)

  def calc(arr: Array[Long]): Long = {
    val n = arr.length
    val scores = arr.map(x => if (x == 0) 2 else 1)
      .zipWithIndex.map(x => (x._2 + 1, x._1))
      .map(x => x._1 * (n - x._1 + 1) * x._2)

    scores.sum
  }
}

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val a = readInts()
    def findMax(i: Int, j: Int): Long = {
      val currentArray = a.slice(i, j + 1)
      currentArray.length + currentArray.count(_ == 0)
    }

    var answer: Long = 0
    0.until(size).foreach { i =>
      0.until(size).foreach { j =>
        if (i <= j) {
          answer += findMax(i, j)
        }
      }
    }

    println(answer)
  }

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

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


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

object Solution {
  def printMatrix(matrix: Array[Array[Int]], n: Int, m: Int, i: Int, j: Int): Unit = {
    (i < n) match {
      case false => Unit
      case true => {
        (j < m) match {
          case false => {
            println("")
            printMatrix(matrix, n, m, (i + 1), 0)
          }
          case true => {
            print(matrix(i)(j) + " ")
            printMatrix(matrix, n, m, i, (j + 1))
          }
        }
      }
    }
  }
  def getDiagList(matrix: Array[Array[Int]], currInds: Tuple2[Int, Int], amount: Int): List[Int] = {
    amount match {
      case 0 => Nil
      case _ => matrix(currInds._1)(currInds._2) :: getDiagList(matrix, (currInds._1 - 1, currInds._2 + 1), amount - 1)
    }
  }
  def compareList(aList: List[Int], bList: List[Int]): Boolean = {
    aList match {
      case a :: aRest => {
        bList match {
          case b :: bRest => (a == b) && compareList(aRest, bRest)
          case Nil => true
        }
      }
      case Nil => true
    }
  }
  def main(args: Array[String]): Unit = {
    val nM = StdIn.readLine().split(" ").map(x => x.toInt)
    val n = nM(0)
    val m = nM(1)

    val aMatrix = Array.range(0, n).map(x => StdIn.readLine().split(" ").map(y => y.toInt))
    val bMatrix = Array.range(0, n).map(x => StdIn.readLine().split(" ").map(y => y.toInt))

    val colStartInds = Array.range(0, n).map(x => (x, 0))
    val rowStartInds = Array.range(1, m).map(x => ((n - 1), x))

    val startInds = colStartInds ++ rowStartInds
    val aDiagLists = startInds.map(x => getDiagList(aMatrix, x, min(x._1 + 1, m - x._2)).sorted)
    val bDiagLists = startInds.map(x => getDiagList(bMatrix, x, min(x._1 + 1, m - x._2)).sorted)

    val res = Array.range(0, startInds.size).toList.foldLeft(true) { (acc, x) => acc && compareList(aDiagLists(x), bDiagLists(x)) }

    res match {
      case true => println("YES")
      case false => println("NO")
    }
  }
}

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 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, M = ni()
    val A = nm(N, M)
    val B = nm(N, M)

    def count(i: Int, mat: Array[Array[Int]]): mutable.Map[Int, Int] = {
      val cnt = mutable.Map[Int, Int]().withDefaultValue(0)
      var n = min(i, N - 1)
      var m = max(0, i - (N - 1))
      debug(s"$n $m")
      while(n >= 0 && m < M) {
        cnt(mat(n)(m)) = cnt(mat(n)(m)) + 1
        n -= 1
        m += 1
      }
      debug(cnt.mkString(" "))
      cnt
    }

    var ok = true
    REP(N + M - 1) { i =>
      ok &&= count(i, A) == count(i, B)
    }

    if (ok) out.println("YES")
    else out.println("NO")
  }

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


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

  val t = readInt()

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

    val i = (1 until (n - 1)).foldLeft(0) {
      case (i, j) if math.abs(hn(j) - hn(j + 1)) < math.abs(hn(i) - hn(i + 1)) => j
      case (i, _)                                                              => i
    }

    // h1 h2 h3 ... hi hi+1 ... hn
    //
    // The first variant (incorrect):
    //   hi+1 ... hn h1 h2 h3 ... hi
    //   Example:
    //     -> 1 3
    //     <- 3 1
    //
    // The second variant (correct):
    //  hi hi+2 ... hn h1 h2 ... hi+1
    //  Example
    //    -> 1 3
    //    <- 1 3

    val ans = hn(i) +: (((i + 2) until n).map(hn) ++ (0 until i).map(hn)) :+ hn(i + 1)

    println(ans.mkString(" "))
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted

    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index

    val heightsBeforeFirstPoint: ListBuffer[Int] = ListBuffer()
    for (i <- 0 until(skipIndex - 1)) {
      heightsBeforeFirstPoint.append(heights(i))
    }
    val heightsAfterFirstPoint: ListBuffer[Int] = ListBuffer()
    for (i <- (skipIndex + 1) until mountainsNumber) {
      heightsAfterFirstPoint.append(heights(i))
    }

    print(s"${heights(skipIndex - 1)} ")
    heightsAfterFirstPoint.foreach(h => print(s"$h "))
    heightsBeforeFirstPoint.foreach(h => print(s"$h "))
    println(s"${heights(skipIndex)} ")
  }

}

import scala.:+
import scala.+:
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted

    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index

    val heightsBeforeFirstPoint = heights.slice(0, skipIndex - 1).toList
    val heightsAfterFirstPoint = heights.slice(skipIndex + 1, mountainsNumber).toList

    val answer = heights(skipIndex - 1) +: (heightsAfterFirstPoint ++ heightsBeforeFirstPoint) :+ heights(skipIndex)

    println(answer.mkString(" "))
  }

}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted
    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index
    var remainingHeights: ListBuffer[Int] = ListBuffer()
    for (i <- 0 until(mountainsNumber)) {
      if (i != skipIndex - 1 && i != skipIndex) {
        val value = heights(i)
        remainingHeights.append(value)
      }
    }

    if (remainingHeights.size == 2 && (skipIndex == 2)) {
      remainingHeights = remainingHeights.reverse
    }

    print(s"${heights(skipIndex - 1)} ")
    remainingHeights.foreach(h => print(s"$h "))
    println(s"${heights(skipIndex)} ")
  }

}

import scala.collection.mutable
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

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

  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val mountainsNumber = readInt()
    val heights = readInts().sorted
    var index = 1
    var min = heights(1) - heights(0)
    for (i <- index.until(mountainsNumber)) {
      val tempMin = heights(i) - heights(i - 1)
      if (tempMin < min) {
        min = tempMin
        index = i
      }
    }
    val skipIndex = if (min == heights(mountainsNumber - 1) -
      heights(mountainsNumber - 2)) mountainsNumber - 1 else index
    print(s"${heights(skipIndex - 1)} ")
    for (i <- 0 until(mountainsNumber)) {
      if (i != skipIndex - 1 && i != skipIndex) print(s"${heights(i)} ")
    }
    println(s"${heights(skipIndex)} ")
  }

}


object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLineInt
    val prices@Array(a, b) = readLineInt
    val ar = (1L to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)
    val sort = ar.sortBy(_._2)
    val tr = sort.scanLeft((0L, 0L)){ (prev, t) => (t._1, prev._2 + t._2) }
    val taken = tr.takeWhile(_._2 <= d).drop(1)
    println(taken.size)
    println(taken.map(_._1).mkString(" "))
  }

  def readLineInt = readLine().split(" ").map(_.toLong)
}

import scala.io.Source
import scala.math._
import scala.collection.mutable.ListBuffer

object A extends App {
  def go = main(Array())
  val in = Source.stdin.getLines.toList

  val Array(n, d) = in.head.split(" ").map(_.toLong)
  val Array(a, b) = in.tail.head.split(" ").map(_.toLong)

  val req = in.tail.tail.map (s => {
    val Array (low, hi) = s.split(" ").map(_.toLong)

    low * a + hi * b
  }).zipWithIndex.sortBy (_._1)

  def solve: List[Int] = {
    val q = req.foldLeft ((List[Int](), 0l)) { case ((res, sum), (reqs, index)) => if (sum + reqs > d) return res else ((index+1)::res, sum+reqs)}

    q._1
  }

  val solution = solve

  println (solution.size)
  println (solution.mkString(" "))
}

import scala.io.Source
import scala.math._
import scala.collection.mutable.ListBuffer

object A extends App {
  def go = main(Array())
  val in = Source.stdin.getLines.toList

  val Array(n, d) = in.head.split(" ").map(_.toInt)
  val Array(a, b) = in.tail.head.split(" ").map(_.toInt)

  val req = in.tail.tail.map (s => {
    val Array (low, hi) = s.split(" ").map(_.toInt)

    low * a + hi * b
  }).zipWithIndex.sortBy (_._1)

  def solve: List[Int] = {
    val q = req.foldLeft ((List[Int](), 0)) { case ((res, sum), (reqs, index)) => if (sum + reqs > d) return res else ((index+1)::res, sum+reqs)}

    q._1
  }

  val solution = solve

  println (solution.size)
  println (solution.mkString(" "))
}

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLineInt
    val prices@Array(a, b) = readLineInt
    val ar = (1 to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)
    val sort = ar.sortBy(_._2)
    val tr = sort.scanLeft((0, 0)){ (prev, t) => (t._1, prev._2 + t._2) }
    val taken = tr.takeWhile(_._2 <= d)
    println(taken.size)
    println(taken.map(_._1).drop(1).mkString(" "))
  }

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

object Main {
  def main(args: Array[String]) {
    val Array(n, d) = readLineInt
    val prices@Array(a, b) = readLineInt
    val ar = (1 to n).map(i => i -> readLineInt.zip(prices).map(t => t._1 * t._2).sum)
    val sort = ar.sortBy(_._2)
    val tr = sort.scanLeft((0, 0)){ (prev, t) => (t._1, prev._2 + t._2) }
    val taken = tr.takeWhile(_._2 <= d).drop(1)
    println(taken.size)
    println(taken.map(_._1).mkString(" "))
  }

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


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(" ")).toList
  println(
    (data.filter(_.last == "rat") ::: data.filter(j => j.last == "woman" || j.last == "child")
      ::: data.filter(j => j.last == "man") ::: data.filter(j => j.last == "captain")).map(_.head).mkString("\n"))
}

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

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

  // rats < women == children < men < captain
  // rats 0
  // women 1
  // children 1
  // men 2
  // captain 3

  val priority = Map("rat" -> 0,
                     "woman" -> 1,
                     "child" -> 1,
                     "man" -> 2,
                     "captain" -> 3)

  val N = sc.nextInt
  sc.nextLine
  val crewList: List[(String, Int)] = List.fill(N)(sc.nextLine).map {
      case s: String => {
        val List(name, status) = s.split(" ").toList
        (name, priority(status))
      }
    }.sortBy(_._2)

  crewList.foreach { tpl =>
    out.println(tpl._1)
  }
  out.close
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" "))

    val bs = scala.collection.mutable.Buffer[Array[String]]()

    bs ++= a.filter(_.apply(1) == "rat")
    bs ++= a.filter(a0 => a0(1) == "woman" || a0(1) == "child")
    bs ++= a.filter(_.apply(1) == "man")
    bs ++= a.filter(_.apply(1) == "captain")

    bs.foreach(s => println(s.toSeq.apply(0)))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(" "))
  println(data.filter(_.last == "rat").map(_.head).mkString("\n"))
  println(data.filter(j => j.last == "woman" || j.last == "child").map(_.head).mkString("\n"))
  println(data.filter(j => j.last == "man").map(_.head).mkString("\n"))
  println(data.filter(j => j.last == "captain").map(_.head).mkString("\n"))

}


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[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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
  }
}

object Workspace {
  import Main._
}

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve1(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N)
    val used = Array.ofDim[Boolean](N + 1)
    var p = 1
    var mx = 0
    REP(N) { i =>
      if (A(i) > mx) {
        mx = A(i)
        B(i) = A(i)
        used(A(i)) = true
      } else {
        while(p <= mx && used(p)) p += 1
        if (p > mx) {
          out.println(-1)
          return
        }
        B(i) = p
        used(p) = true
      }
    }
    out.println(B.mkString(" "))
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve1()
    }
  }
}

import scala.io.StdIn._
import scala.collection.mutable.ArrayBuffer
object Main extends App{
    // Your code here!
    val t = readInt()
    for (i <- 1 to t) {
        val n = readInt()
        val arr = readLine().split(" ").map(_.toInt)
        var curr = 1
        val vis = new Array[Boolean](n+1)
        val res = ArrayBuffer[Int]()
        var flag = false
        for (j <- 0 until arr.length) {
            vis(arr(j)) = true
            if (j > 0 && arr(j) == arr(j-1)) {
                while(vis(curr)) curr += 1
                if (curr >= arr(j)) {
                    flag = true
                } else {
                    res += curr
                    vis(curr) = true
                    curr += 1
                }
            } else {
                res += arr(j)
            }
        }
        if (flag) {
            print(-1)
        } else {
            for (k <- 0 until n) print(s"${res(k)} ")
        }
        println()
    }
}


object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var a = arr.sorted
		var i = n-1
		var sum = 0
		for (i <- 0 until n)
			sum += a(i)
		i = n-1
		var rez = sum
		var najmal = a(0)

		while (i > 0)
		{
			for (j <- 1 to a(i))
				if (a(i) % j == 0)
				{
					var new_rez = min(rez, sum - a(i) - a(0) + a(i) / j + a(0)*j)
					rez = new_rez
				}
			i -= 1
		}

		println(rez)
	}
}

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 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)
    val B = Array.ofDim[Boolean](101)
    REP(N) { i =>
      B(A(i)) |= true
    }
//    debug(B)

    val sum = A.sum
    var diff = 0
    val ms = A.min
//    debug(ms)
    REP_r(101) { a =>
      if (B(a) && ms < a) {
        val D = divisors(a)
        REP(D.length) { i =>
          val d = D(i)
          val gain = a / d - a + ms * d - ms
//          debug(s"$a $d $gain")
          diff = min(diff, gain)
        }
      }
    }

    val ans = sum + min(0, diff)
    out.println(ans)
  }

  /**
    * O(√x)
    */
  def divisors(x: Int): Array[Int] = {
    val pre = ArrayBuffer[Int]()
    val post = ArrayBuffer[Int]()
    REP(math.sqrt(x).toInt, 1) { d =>
      if (x % d == 0) {
        pre += d
        if (d * d != x) post += x / d
      }
    }

    val res = Array.ofDim[Int](pre.length + post.length)
    REP(pre.length)(i => res(i) = pre(i))
    val preLen = pre.length
    val postLen = post.length
    REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))
    res
  }

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

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

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

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

  def debug(num: Long): Unit = {
    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 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
  }
}

object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var a = arr.sorted
		var i = n-1
		var sum = 0
		for (i <- 0 until n)
			sum += a(i)
		i = n-1
		var rez = sum
		var najmal = a(0)

		while (i > 0)
		{
			for (j <- 1 to a(i))
				if (a(i) % j == 0)
				{
					var new_rez = min(rez, rez - a(i) - a(0) + a(i) / j + a(0)*j)
					rez = new_rez
				}
			i -= 1
		}

		println(rez)
	}
}


import scala.collection.mutable
import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ").map(_.toLong)
  val q = new mutable.PriorityQueue[Long].reverse
  val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>
    val (curResult, curSum) = state;
    if (next + curSum >= 0) {
      q.enqueue(next)
      (curResult + 1, next + curSum)
    } else if (q.nonEmpty && q.head < next) {
      val old = q.dequeue()
      q.enqueue(next)
      (curResult, curSum - old + next)
    } else {
      (curResult, curSum)
    }
  }

  println(result)
}

import scala.collection.mutable
import scala.io.StdIn

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ").map(_.toLong)

  def slowSolution(n: Int, a: Array[Long]): Long = {
    val init = (0 to n).map {i => if (i == 0) 0l else -1l }
    val results = a.foldLeft(init) { (v, next) =>
      (0 to n).map { i =>
        if (i == 0)
          0
        else if (v(i - 1) == -1)
          -1
        else
          Math.max(v(i), v(i - 1) + next)
      }
    }
    (0 to n).filter(results(_) != -1).max
  }

  def fastSolution(n: Int, a: Array[Long]): Long = {
    val q = new mutable.PriorityQueue[Long].reverse
    val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>
      val (curResult, curSum) = state;
      if (next + curSum >= 0) {
        q.enqueue(next)
        (curResult + 1, next + curSum)
      } else if (q.nonEmpty && q.head < next) {
        val old = q.dequeue()
        q.enqueue(next)
        (curResult, curSum - old + next)
      } else {
        (curResult, curSum)
      }
    }
    result
  }

  println(fastSolution(n, a))
}


import scala.io.StdIn._
object Main{
  def main(args: Array[String]): Unit ={
    val N = readInt()
    for(_ <- 0 until N){
      val line = readLine().split(" ").map(_.toInt)
      val a = line(0)
      val b = line(1)
      def valid(a: Int) = a % 3 == 0 && a >= 0
      println(if(valid(2*b - a) && valid(2*a - b)) "YES" else "NO")
    }
  }
}

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[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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
  }
}

object Workspace {
  import Main._
}

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      var a, b = ni()
      val ok =
        a == 0 && b == 0 || {
          // a <= b にする
          if (a > b) {
            val t = a
            a = b
            b = t
          }

          if (a * 2 < b)
            false
          else {
            val ccc = 2 * a - b
            debug(s"ccc:$ccc")
            ccc % 3 == 0 && {
              val c = ccc / 3
              debug(s"c:$c")
              (a - 2 * c) * 2 == b - c
            }
          }
        }

      if (ok) out.println("YES")
      else out.println("NO")
    }
  }
}


import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
      val t: Int = readInt()
      for (_ <- 1 to t){
          val n: Int = readInt()
          val a: Array[Int] = readLine().split(" ").map(_.toInt)
          val b: Array[Int] = Array.fill(n)(0)
          val parity_arr: Array[Int] = Array.fill(n)(-1)
            for (j <- 0 until n){
                val curr_color: Int = a(j)
                val last_parity: Int = parity_arr(a(j)-1)
                if (last_parity == -1 || (last_parity == 0 && j%2 == 1) || (last_parity == 1 && j%2 == 0)) {
                    b(a(j)-1) += 1
                    parity_arr(a(j)-1) = j%2
                }
            }
        println(b.mkString(" "))
        }
    }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = new Array[Int](n)
      val B = new Array[Int](n)
      for (i <- 0 until n) {
        A(i) = 0
        B(i) = -1
      }
      tokenizer = new StringTokenizer(input.readLine())
      var pr = 0
      var now = 0
      var count = 0
      for (i <- 1 to n) {
        pr = now
        now = tokenizer.nextToken().toInt
        if (pr == now) {
          B(pr-1) = i
          A(pr-1) += 1
        }
        else if (B(now-1) == -1) {
          B(now-1) = i
          A(now-1) += 1
        }
        else if ((i - B(now-1) ) % 2 == 1) {
          B(now-1) = i
          A(now-1) += 1
        }
        else {
          B(now-1) = i
        }
      }
      println(A.mkString(" "))
    }
  }
}


import scala.annotation.tailrec

object F670 {
  var t = 0L
  def findLength(finalLength: Int) = {
    var left = 0
    var right = finalLength

    // left <= finalLength, right > finalLength
    while (right - left > 1) {
      val mid = (left + right) / 2

      val len = mid + mid.toString.length

      if (len <= finalLength) left = mid else right = mid
    }

    left
  }
  def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {
    left
      .flatMap {
        case (key, value) if (right.contains(key) && value == right(key)) => None
        case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))
        case (key, value) => Some(key -> value)
      }
      .toMap
  }

  def digitMapToString(digitsMap: Map[Char, Int]) = {
    val ret = ('0' to '9').map { case c =>
      c.toString * digitsMap.getOrElse(c, 0)
    }.mkString("")

    ret
  }

  def getPartition(digitsMap: Map[Char, Int], subString: String) = {
    val nonZero = digitsMap - '0'

    nonZero.size match {
      case 0 => Seq[String](subString + digitMapToString(digitsMap))
      case _ =>
        val (head, count) = nonZero.min
        val trimmedDigitsMap = if (count == 1)
            digitsMap - head
          else
            digitsMap.updated(head, count - 1)
        trimmedDigitsMap.map { case (key, _) =>
          val (before, equalOrAfter) = trimmedDigitsMap.partition { case (iKey, _) => iKey < key }

          head + digitMapToString(before) + subString + digitMapToString(equalOrAfter)
        } ++ Seq(
          head + digitMapToString(trimmedDigitsMap) + subString
        )
    }
  }

  def main(args: Array[String]) {
          t -= System.nanoTime()
    val unOrderedString = readLine
    val subString = readLine

    val length = findLength(unOrderedString.length)

    def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}

    val lengthMap = stringToMap(length.toString)
    val fullMap = stringToMap(unOrderedString)
    val subStringMap = stringToMap(subString)
    val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)

    val candidates = Seq(
      subString + digitMapToString(digitsMap),
      digitMapToString(digitsMap) + subString
    ) ++ getPartition(digitsMap, subString)

    val result = candidates.sorted.filter{ case str => str(0) != '0' }.headOption match {
      case Some(str) => str
      case _ => candidates(0)
    }

          t += System.nanoTime()
    println(result)
    //println(t / 1000000)
  }
}

object F670 {
  def findLength(finalLength: Int, length: Int): Int = {
    if (length + length.toString.length == finalLength) length
    else findLength(finalLength, length - 1)
  }

  def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {
    left.flatMap {
        case (key, value) if (right.contains(key) && value == right(key)) => None
        case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))
        case (key, value) => Some(key -> value)
      }
      .toMap
  }

  def digitMapToString(digitsMap: Map[Char, Int]) = ('0' to '9').map { case c => c.toString * digitsMap.getOrElse(c, 0) }.mkString("")

  def getPartition(digitsMap: Map[Char, Int], subString: String) = {
    val nonZero = digitsMap - '0'

    nonZero.size match {
      case 0 => Seq[String](subString + digitMapToString(digitsMap))
      case _ =>
        val (head, count) = nonZero.min
        val trimmedDigitsMap = if (count == 1) digitsMap - head else digitsMap.updated(head, count - 1)
        trimmedDigitsMap.map { case (key, _) =>
          val (before, equalOrAfter) = trimmedDigitsMap.partition { case (iKey, _) => iKey < key }
          head + digitMapToString(before) + subString + digitMapToString(equalOrAfter)
        } ++ Seq(
          head + digitMapToString(trimmedDigitsMap) + subString
        )
    }
  }

  def main(args: Array[String]) {
    val unOrderedString = readLine
    val subString = readLine

    val length = findLength(unOrderedString.length, unOrderedString.length)

    def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}

    val lengthMap = stringToMap(length.toString)
    val fullMap = stringToMap(unOrderedString)
    val subStringMap = stringToMap(subString)
    val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)

    val candidates = Seq(
      subString + digitMapToString(digitsMap),
      digitMapToString(digitsMap) + subString
    ) ++ getPartition(digitsMap, subString)

    val result = candidates.sorted.filter{ case str => str(0) != '0' }.headOption match {
      case Some(str) => str
      case _ => candidates(0)
    }

    println(result)
  }
}

import scala.annotation.tailrec

object F670 {
  def findLength(finalLength: Int) = {
    var left = 0
    var right = finalLength

    // left <= finalLength, right > finalLength
    while (right - left > 1) {
      val mid = (left + right) / 2

      val len = mid + mid.toString.length

      if (len <= finalLength) {
        left = mid
      } else {
        right = mid
      }
    }

    left
  }

  def findHead(
    digitsMap: Map[Char, Int],
    head: Char,
    result: String
  ): (String, Map[Char, Int]) = {
    if (digitsMap.size == 0)
      (result, digitsMap)
    else {
      val (smallestKey, smallestValue) = digitsMap.min
      if (smallestKey > head) {
        (result, digitsMap)
      } else {
        findString(digitsMap, result, '1', head)
      }
    }
  }

  def consumeDigit(digitsMap: Map[Char, Int], start: Char) = {
    if (digitsMap(start) == 1)
      digitsMap - start
    else
      digitsMap.updated(start, digitsMap(start) - 1)
  }

  @tailrec def findString(
    digitsMap: Map[Char, Int],
    result: String,
    start: Char,
    top: Char
  ): (String, Map[Char, Int]) = {
    //println(s"findString with $result, $start, $top")
    if (start > '9' || digitsMap.size == 0 || digitsMap.min._1 > top)
      (result, digitsMap)
    else if (result.length == 0) {
      if (digitsMap.contains(start)) {
        findString(
          consumeDigit(digitsMap, start),
          result + start.toString,
          '0',
          top)
      } else {
        findString(
          digitsMap,
          result,
          (start + 1).asInstanceOf[Char],
          top)
      }
    } else {
      if (digitsMap.contains(start)) {
        val newDigitsMap = digitsMap - start
        findString(newDigitsMap, result + List.fill(digitsMap(start))(start).mkString(""), start, top)
      } else {
        findString(digitsMap, result, (start + 1).asInstanceOf[Char], top)
      }
    }
  }

  @tailrec def findTail(digitsMap: Map[Char, Int], result: String): String = {
    if (digitsMap.size == 0) {
      return result
    } else {
      val (digit, count) = digitsMap.min
      findTail(digitsMap - digit, result + List.fill(count)(digit).mkString(""))
    }
  }

  def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {
    left
      .flatMap {
        case (key, value) if (right.contains(key) && value == right(key)) => None
        case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))
        case (key, value) => Some(key -> value)
      }
      .toMap
  }

  def shouldEqual(subString: String): Boolean = {
    if (subString.length == 0)
      true
    else if (subString.length == 1)
      true
    else {
      if (subString(0) == subString(1)) {
        shouldEqual(subString.tail)
      } else {
        subString(0) < subString(1)
      }
    }
  }

  var tt = 0

  def main(args: Array[String]) {
    val unOrderedString = readLine
    val subString = readLine

    val length = findLength(unOrderedString.length)

    def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}

    val lengthMap = stringToMap(length.toString)
    val fullMap = stringToMap(unOrderedString)
    val subStringMap = stringToMap(subString)
    val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)

    val top = if (shouldEqual(subString)) {
      subString(0)
    } else {
      (subString(0) - 1).asInstanceOf[Char]
    }
    val (prefix, updatedMap) = findHead(digitsMap, top, "")

    val (prefixPlus, tailDigitsMap) = if (updatedMap.size == 0) {
        (prefix + subString, updatedMap)
      }
      else if (prefix.length == 0 && subString(0) == '0') {
        val (head, size) = updatedMap.min
        (head + subString, consumeDigit(updatedMap, head))
      } else {
        (prefix + subString, updatedMap)
      }

    println(prefixPlus + findTail(tailDigitsMap, ""))
  }
}

import scala.annotation.tailrec

object F670 {
  def findLength(finalLength: Int) = {
    var left = 0
    var right = finalLength

    // left <= finalLength, right > finalLength
    while (right - left > 1) {
      val mid = (left + right) / 2

      val len = mid + mid.toString.length

      if (len <= finalLength) {
        left = mid
      } else {
        right = mid
      }
    }

    left
  }

  def findHead(
    digitsMap: Map[Char, Int],
    head: Char,
    top: Char,
    result: String
  ): (String, Map[Char, Int]) = {
    if (digitsMap.size == 0)
      (result, digitsMap)
    else {
      val (smallestKey, smallestValue) = digitsMap.min
      if (smallestKey > head) {
        (result, digitsMap)
      } else {
        findString(digitsMap, result, '1', if (head == '0') '9' else top)
      }
    }
  }

  def consumeDigit(digitsMap: Map[Char, Int], start: Char) = {
    if (digitsMap(start) == 1)
      digitsMap - start
    else
      digitsMap.updated(start, digitsMap(start) - 1)
  }

  @tailrec def findString(
    digitsMap: Map[Char, Int],
    result: String,
    start: Char,
    top: Char
  ): (String, Map[Char, Int]) = {
    // println(s"findString with $result, $start, $top")
    if (start > top || digitsMap.size == 0 || digitsMap.min._1 > top)
      (result, digitsMap)
    else if (result.length == 0) {
      if (digitsMap.contains(start)) {
        findString(
          consumeDigit(digitsMap, start),
          result + start.toString,
          '0',
          top)
      } else {
        findString(
          digitsMap,
          result,
          (start + 1).asInstanceOf[Char],
          top)
      }
    } else {
      if (digitsMap.contains(start)) {
        val newDigitsMap = digitsMap - start
        findString(newDigitsMap, result + List.fill(digitsMap(start))(start).mkString(""), start, top)
      } else {
        findString(digitsMap, result, (start + 1).asInstanceOf[Char], top)
      }
    }
  }

  @tailrec def findTail(digitsMap: Map[Char, Int], result: String): String = {
    if (digitsMap.size == 0) {
      return result
    } else {
      val (digit, count) = digitsMap.min
      findTail(digitsMap - digit, result + List.fill(count)(digit).mkString(""))
    }
  }

  def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {
    left
      .flatMap {
        case (key, value) if (right.contains(key) && value == right(key)) => None
        case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))
        case (key, value) => Some(key -> value)
      }
      .toMap
  }

  def shouldEqual(subString: String): Boolean = {
    if (subString.length == 0)
      true
    else if (subString.length == 1)
      true
    else {
      if (subString(0) == subString(1)) {
        shouldEqual(subString.tail)
      } else {
        subString(0) < subString(1)
      }
    }
  }

  var tt = 0

  def main(args: Array[String]) {
    val unOrderedString = readLine
    val subString = readLine

    val length = findLength(unOrderedString.length)

    def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}

    val lengthMap = stringToMap(length.toString)
    val fullMap = stringToMap(unOrderedString)
    val subStringMap = stringToMap(subString)
    val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)

    val top = if (shouldEqual(subString)) {
      subString(0)
    } else {
      (subString(0) - 1).asInstanceOf[Char]
    }
    val (prefix, updatedMap) = findHead(digitsMap, subString(0), top, "")

    // println(top + ", " + prefix)

    val (prefixPlus, tailDigitsMap) = if (updatedMap.size == 0) {
        (prefix + subString, updatedMap)
      }
      else if (prefix.length == 0 && subString(0) == '0') {
        val (head, size) = updatedMap.min
        (head + subString, consumeDigit(updatedMap, head))
      } else {
        (prefix + subString, updatedMap)
      }

    println(prefixPlus + findTail(tailDigitsMap, ""))
  }
}

import scala.annotation.tailrec

object F670 {
  def findLength(finalLength: Int) = {
    var left = 0
    var right = finalLength

    // left <= finalLength, right > finalLength
    while (right - left > 1) {
      val mid = (left + right) / 2

      val len = mid + mid.toString.length

      if (len <= finalLength) left = mid else right = mid
    }

    left
  }

  def findHead(
    digitsMap: Map[Char, Int],
    head: Char,
    top: Char,
    result: String
  ): (String, Map[Char, Int]) = {
    if (digitsMap.size == 0)
      (result, digitsMap)
    else {
      val (smallestKey, smallestValue) = digitsMap.min
      if (head == '0') {
        val lowest = (digitsMap - '0').min._1
        (lowest + List.fill(digitsMap.getOrElse('0', 0))('0').mkString(""), consumeDigit(digitsMap, lowest) - '0')
      } else if (smallestKey >= head){
        (result, digitsMap)
      } else {
        findString(digitsMap, result, '1', top)
      }
    }
  }

  def consumeDigit(digitsMap: Map[Char, Int], start: Char) = {
    if (digitsMap(start) == 1)
      digitsMap - start
    else
      digitsMap.updated(start, digitsMap(start) - 1)
  }

  @tailrec def findString(
    digitsMap: Map[Char, Int],
    result: String,
    start: Char,
    top: Char
  ): (String, Map[Char, Int]) = {
    // println(s"findString with $result, $start, $top")
    if (start > top || digitsMap.size == 0 || digitsMap.min._1 > top)
      (result, digitsMap)
    else if (result.length == 0) {
      if (digitsMap.contains(start)) {
        findString(
          consumeDigit(digitsMap, start),
          result + start.toString,
          '0',
          top)
      } else {
        findString(
          digitsMap,
          result,
          (start + 1).asInstanceOf[Char],
          top)
      }
    } else {
      if (digitsMap.contains(start)) {
        val newDigitsMap = digitsMap - start
        findString(newDigitsMap, result + List.fill(digitsMap(start))(start).mkString(""), start, top)
      } else {
        findString(digitsMap, result, (start + 1).asInstanceOf[Char], top)
      }
    }
  }

  @tailrec def findTail(digitsMap: Map[Char, Int], result: String): String = {
    if (digitsMap.size == 0) {
      return result
    } else {
      val (digit, count) = digitsMap.min
      findTail(digitsMap - digit, result + List.fill(count)(digit).mkString(""))
    }
  }

  def minusMap(left: Map[Char, Int], right: Map[Char, Int]): Map[Char, Int] = {
    left
      .flatMap {
        case (key, value) if (right.contains(key) && value == right(key)) => None
        case (key, value) if (right.contains(key)) => Some(key -> (value - right(key)))
        case (key, value) => Some(key -> value)
      }
      .toMap
  }

  def shouldEqual(subString: String): Boolean = {
    if (subString.length == 0)
      true
    else if (subString.length == 1)
      true
    else {
      if (subString(0) == subString(1)) {
        shouldEqual(subString.tail)
      } else {
        subString(0) < subString(1)
      }
    }
  }

  var tt = 0

  def main(args: Array[String]) {
    val unOrderedString = readLine
    val subString = readLine

    val length = findLength(unOrderedString.length)

    def stringToMap(str: String) = str.toString.groupBy{c => c}.map { case (key, value) => (key, value.length)}

    val lengthMap = stringToMap(length.toString)
    val fullMap = stringToMap(unOrderedString)
    val subStringMap = stringToMap(subString)
    val digitsMap = minusMap(minusMap(fullMap, lengthMap), subStringMap)

    val top = if (shouldEqual(subString)) {
      subString(0)
    } else {
      (subString(0) - 1).asInstanceOf[Char]
    }
    val (prefix, updatedMap) = findHead(digitsMap, subString(0), top, "")

    // println(top + ", " + prefix)

    val (prefixPlus, tailDigitsMap) = if (updatedMap.size == 0) {
        (prefix + subString, updatedMap)
      }
      else if (prefix.length == 0 && subString(0) == '0') {
        val (head, size) = updatedMap.min
        (head + subString, consumeDigit(updatedMap, head))
      } else {
        (prefix + subString, updatedMap)
      }

    println(prefixPlus + findTail(tailDigitsMap, ""))
  }
}


import scala.io.StdIn

object Main extends App {
  val t = StdIn.readInt()
  for(i <- 0 until t){
    val n = StdIn.readLine().split(" ").map(_.toInt)
    for(i <- 0 until n(0)) {
      for(j <- 0 until n(1)){
        var ans = i&3 ^ j&3
        ans = (ans&1) ^ (ans>>1)
        print(ans + " ")
      }
      println()
    }
  }
}

import scala.collection.mutable

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {
  import java.util.StringTokenizer
  def run() {
    def str1(m:Int): String = {
      var l = new StringBuilder
      l ++=  "1"
      if ((m % 4) == 2) {
        if (m!=2) {
          for (i <- 1 to (m-2)/4 ) {
            l++= " 0 0 1 1"
          }
        }

        l++= " 0"
      }
      else {
        if (m != 4) {
          for (i <- 1 to (m - 4) / 4) {
            l ++= " 0 0 1 1"
          }
      }
        l ++= " 0 0 1"
      }
      l.toString
    }
    def str2(m:Int): String = {
      val l = new StringBuilder
      l++= "0"
      if ((m % 4) == 2) { if (m!=2) {
        for (i <- 1 to (m-2)/4 ) {
          l++= " 1 1 0 0"
        }
      }
        l++= " 1"
      }
      else {
        if (m!=4) {
          for (i <- 1 to (m - 4) / 4) {
          l ++= " 1 1 0 0"
        }
      }
      l ++= " 1 1 0"
      }
      l.toString
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q){
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val m = tokenizer.nextToken().toInt
      val ch = str1(m)
      val ne = str2(m)
      if ((n % 4) == 0) {
        for (j <-1 to (n)/4) {
          output.println(ch)
          output.println(ne)
          output.println(ne)
          output.println(ch)
        }
      }
      else {
        if (n!=2){
          for (j <-1 to (n-2)/4) {
            output.println(ch)
            output.println(ne)
            output.println(ne)
            output.println(ch)
          }
        }

        output.println(ch)
        output.println(ne)
      }
    }
  }

}

import scala.io.StdIn

object Main extends App {
  val t = StdIn.readInt()
  for(i <- 0 until t){
    val n = StdIn.readLine().split(" ").map(_.toInt)
    for(i <- 0 until n(0)) {
      for(j <- 0 until n(1)){
        print(((i ^ j) ^ ((i ^ j) >> 1)) & 1 )
      }
      println()
    }
  }
}


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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readInts(3)
    val input = Array.fill(m+1)(readBigs(1)).map{ x =>
      val s = x(0).toString(2)
      Array.fill[Char](n - s.length)('0') ++  s.toCharArray
    }
    val compare = input(m)

    var res = 0
    for(i <- 0 until m) {
      var diff = 0
      for (j <- 0 until n) {
        if(input(i)(j) != compare(j))
          diff += 1
      }
      if(diff <= k)
        res += 1
    }

    println(res)
  }
}

import scala.io.StdIn._

object FedorandNewGame extends App {
  val n :: m :: k :: Nil = readLine().split(" ").map(_.toInt).toList
  val a = Array.ofDim[Int](m)
  for (i <- 0 until m) {
    a(i) = readInt()
  }
  val p = readInt()
  val result = a.foldLeft(0) { (acc, x) =>
    val g = p ^ x
    if (Integer.bitCount(g) <= k) acc + 1
    else acc
  }
  println(result)
}

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

/**
 * Created by arseny on 18.09.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 m = nextInt
    val k = nextInt
    val xs = Array.fill(m + 1)("")
    for(i <- 0 until m + 1) {
      xs(i) = nextInt.toBinaryString.reverse
    }
    def countDiff(s: String, t: String): Int = {
      var diff = 0
      for(i <- 0 until math.min(s.length, t.length)) {
        if(s(i) != t(i)) {
          diff += 1
        }
      }
      if(s.length < t.length) {
        for(i <- s.length until t.length) {
          if(t(i) == '1') {
            diff += 1
          }
        }
      } else {
        for(i <- t.length until s.length) {
          if(s(i) == '1') {
            diff += 1
          }
        }
      }
      diff
    }
    val nFriends = (for(i <- 0 until xs.length - 1) yield countDiff(xs(i), xs(m)) <= k).count(_ == true)
    out.print(nFriends)
  }

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

import java.util.StringTokenizer

object _467B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val m = next.toInt
  val k = next.toInt
  val a = (0 to m).map(i => next.toInt)
  val ans = for {
    i <- 0 until m
    if (Integer.bitCount((a(i) ^ a(m))) <= k)
  } yield 1
  println(ans.sum)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(" ").map(_.toInt)
  val data = Range(0, m).map(_ => in.next().toInt)
  val f = in.next().toInt

  println(data.map(_ ^ f).map(_.toBinaryString.count(_ == '1')).count(_ <= k))
}

import scala.io.StdIn

object A extends App {

  val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
  val arr = (1 to m).map( _ => StdIn.readInt())
  val a = StdIn.readInt()
  val res = arr.map { x =>
    if((x ^ a).toBinaryString.filter(_ == '1').length <= k) 1 else 0
  }.sum
  println(res)
}

import scala.io.StdIn

/**
 * @author unit7
 */
object Main {
  def main(args: Array[String]) {
    val counters = StdIn
                    .readLine()
                    .split("\\s")
                    .map(_.toInt)

    val m = counters(1)

    val armies = new Array[Int](m + 1)

    val k = counters(2)
    for (i <- 0 to m) {
      armies(i) = StdIn.readInt()
    }

    val fedor = armies(m)
    var canFriendCount = 0

    for (i <- 0 until m) {
      val differ = (fedor ^ armies(i))
                      .toBinaryString
                      .count(_ == '1')

      if (differ <= k)
        canFriendCount += 1
    }

    println(canFriendCount)
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readInts(3)
    val input = Array.fill(m+1)(readBigs(1)).map(_(0))
    var res = 0
    for(i <- 0 until m) {
      val bits = (input(i) & input(m)).bitCount
      if(bits >= n-k) {
        res += 1
      }
    }
    println(res)
  }
}

import scala.io.StdIn

object A extends App {

  val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
  val arr = (1 to m).map( _ => StdIn.readInt())
  val a = StdIn.readInt()
  val res = arr.map { x =>
    if(n - (x & a).toBinaryString.filter(_ == '1').length <= k) 1 else 0
  }.sum
  println(res)
}


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

  override def solve(io: IO) = {
    val s = io.read[String].toArray

    val table = ('a' to 'z').map(c => c -> new java.util.TreeSet[Int]).toMap
    s.zipWithIndex foreach {case (c, i) => table(c) add i}

    repeat(io.read[Int]) {
      io.read[Int] match {
        case 1 =>
          val pos = io.read[Int] - 1
          val c = io.read[String].head
          table(s(pos)) remove pos
          table(c) add pos
          s(pos) = c

        case _ =>
          val l = io.read[Int] - 1
          val r = io.read[Int] - 1
          val ans = table.values.count({ s => Option(s.ceiling(l)).exists(_ <= r)})
          io.writeLine(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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[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")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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 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 C590D(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 C590D(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val s: Array[Char] = ns().toCharArray
    val segment = new SegmentTree(s.length, s)
    segment.build(1, 0, s.length - 1)
    val q = ni()
    REP(q) { _ =>
      ni() match {
        case 1 =>
          val pos = ni()
          val c = nc()
          segment.update(1, 0, s.length - 1, pos - 1, c)
        case 2 =>
          val l = ni()
          val r = ni()
          out.println(segment.get(1, 0, s.length - 1, l-1, r-1).distinctCount)
      }

    }
  }

  case class Node (distinctCount: Int, bits: Long)

  private class SegmentTree(n: Int, s: Array[Char]) {

    private val tree: Array[Node] = Array.ofDim[Node](4 * n)

    private def combine(x: Node, y: Node): Node = {
      val z = x.bits | y.bits
      Node(java.lang.Long.bitCount(z), z)
    }

    def build(v: Int, tl: Int, tr: Int): Unit = {
      if(tl == tr) {
        tree(v) = Node(1, 1 << (s(tl) - 'a'))
      } else {
        val tm = tl + (tr - tl) / 2
        build(v << 1, tl, tm)
        build(v << 1 | 1, tm + 1, tr)
        tree(v) = combine(tree(v << 1), tree(v << 1 | 1))
      }
    }

    def update(v: Int, tl: Int, tr: Int, pos: Int, value: Char): Unit = {
      if(tl == tr) {
        tree(v) = Node(1, 1 << (value - 'a'))
      } else {
        val tm = tl + (tr - tl) / 2
        if(pos <= tm) {
          update(v << 1, tl ,tm, pos, value)
        } else {
          update(v << 1 | 1, tm + 1, tr, pos, value)
        }
        tree(v) = combine(tree(v << 1), tree(v << 1 | 1))
      }
    }

    def get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Node = {
      if(r < tl || l > tr || l > r) {
        Node(0, 0)
      }
      else if(l == tl && r == tr) tree(v)
      else {
        val tm = tl + (tr - tl) / 2
        combine(get(v << 1, tl, tm, l, Math.min(r, tm)), get(v << 1 | 1, tm+1, tr, Math.max(l, tm+1), r))
      }
    }
  }
}


import scala.io.StdIn.readLine
object Sum {

    def myFunc[T: Manifest](t: T): Manifest[T] = manifest[T]

    def solve_test() = {
        val a = readLine().split(' ').map(_.toInt).sorted
        if (a(0) + a(1) == a(2))
            println("YES")
        else
            println("NO")
    }

    def main(args: Array[String]): Unit = {
        val test = scala.io.StdIn.readInt()
        for(i <- 0 until test) solve_test()
    }
}

object HelloWorld {

  def main(args: Array[String]): Unit = {
    val tests = scala.io.StdIn.readInt()
    for (t <- 1 to tests) {
      val Array(a, b, c) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

      val works = a + b == c || a + c == b || b + c == a

      if (works) println("YES") else println("NO")
    }
  }
}


import scala.io._
import Array._
import collection.immutable.SortedMap

object lala {
  def main(args: Array[String]) {

    implicit val Ord = implicitly[Ordering[Int]]

    var totalApples = 0
    val numberOfTrees = readInt()
    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldPositive1: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()
      temp = line.split(" ") map (_.toInt)
      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    if (fieldPositive.size == fieldNegative.size) {
      totalApples += fieldPositive.foldLeft(0)(_ + _._2)
      totalApples += fieldNegative.foldLeft(0)(_ + _._2)
    } else if (fieldPositive.size > fieldNegative.size) {
        totalApples += fieldNegative.foldLeft(0)(_ + _._2)
        fieldPositive1 = fieldPositive.take(fieldNegative.size + 1)
        totalApples += fieldPositive1.foldLeft(0)(_ + _._2)
     } else if (fieldPositive.size < fieldNegative.size) {
          totalApples += fieldPositive.foldLeft(0)(_ + _._2)
          fieldNegative1 = fieldNegative.take(fieldPositive.size + 1)
          totalApples += fieldNegative1.foldLeft(0)(_ + _._2)
    }
    println(totalApples)
  }
}

//package c558.a

object Solution extends App {
  import scala.io.StdIn
  val n = StdIn.readInt()
  val (leftTree, rightTree) = (1 to n).map(_ ⇒ {
    val s = StdIn.readLine().split(" ")
    s(0).toInt → s(1).toLong
  }).partition(_._1 > 0)
  @scala.annotation.tailrec
  def eatApples(left: Seq[(Int, Long)], right: Seq[(Int, Long)], applesAcc: Long, direction: String): Long =
    if (direction == "left") {
      left match {
        case Nil ⇒ applesAcc
        case _ ⇒ eatApples(left.tail, right, applesAcc + left.head._2, "right")
      }
    } else {
      right match {
        case Nil ⇒ applesAcc
        case _ ⇒ eatApples(left, right.tail, applesAcc + right.head._2, "left")
      }
    }
  val sortedLeft = leftTree.sortBy(_._1)
  val sortedRight = rightTree.sortBy(_._1 * -1)
  val twoResults = Seq("left", "right").map(eatApples(sortedLeft, sortedRight, 0, _))
  println(scala.math.max(twoResults.head, twoResults.tail.head))
}

import scala.io._
import Array._
import collection.immutable.SortedMap

object lala {
  def main(args: Array[String]) {

    var numberOfTrees: Int = 0
    var walk = 0
    var totalApples = 0

    val line = readInt()
    numberOfTrees = line.toInt

    implicit val Ord = implicitly[Ordering[Int]]

    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldPositive1: SortedMap[Int, Int] = SortedMap()
    var fieldPositive2: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative2: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()

      temp = line.split(" ") map (_.toInt)

      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    if (fieldPositive.size == fieldNegative.size) {
      for (i <- fieldPositive) {
        totalApples += i._2
      }
      for (i <- fieldNegative) {
        totalApples += i._2
      }
    }

    if (fieldPositive.size > fieldNegative.size) {

      for (i <- fieldNegative) {
        totalApples += i._2
      }

      fieldPositive1 = fieldPositive.take(fieldNegative.size)

      for (i <- fieldPositive1) {
        totalApples += i._2
      }

      fieldPositive2 = fieldPositive.take(fieldNegative.size + 1)

      totalApples += fieldPositive2.last._2

    }

    if (fieldPositive.size < fieldNegative.size) {

      for (i <- fieldPositive) {
        totalApples += i._2
      }

      fieldNegative1 = fieldNegative.take(fieldPositive.size)

      for (i <- fieldNegative1) {
        totalApples += i._2
      }

      fieldNegative2 = fieldNegative.take(fieldPositive.size + 1)

      totalApples += fieldNegative2.last._2

    }

    println(totalApples)

  }
}

import scala.io._
import Array._
import collection.immutable.SortedMap

object lala {
  def main(args: Array[String]) {

    var numberOfTrees: Int = 0
    var totalApples = 0
    val line = readInt()
    numberOfTrees = line.toInt

    implicit val Ord = implicitly[Ordering[Int]]

    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldPositive1: SortedMap[Int, Int] = SortedMap()
    var fieldPositive2: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative1: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    var fieldNegative2: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()
      temp = line.split(" ") map (_.toInt)
      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    if (fieldPositive.size == fieldNegative.size) {
      totalApples += fieldPositive.foldLeft(0)(_ + _._2)
      totalApples += fieldNegative.foldLeft(0)(_ + _._2)
    }

    if (fieldPositive.size > fieldNegative.size) {
      totalApples += fieldNegative.foldLeft(0)(_ + _._2)
      fieldPositive1 = fieldPositive.take(fieldNegative.size)
      totalApples += fieldPositive1.foldLeft(0)(_ + _._2)
      fieldPositive2 = fieldPositive.take(fieldNegative.size + 1)
      totalApples += fieldPositive2.last._2
    }

    if (fieldPositive.size < fieldNegative.size) {
      totalApples += fieldPositive.foldLeft(0)(_ + _._2)
      fieldNegative1 = fieldNegative.take(fieldPositive.size)
      totalApples += fieldNegative1.foldLeft(0)(_ + _._2)
      fieldNegative2 = fieldNegative.take(fieldPositive.size + 1)
      totalApples += fieldNegative2.last._2
    }
    println(totalApples)
  }
}

import scala.io.StdIn.readLine
import scala.collection.mutable.PriorityQueue
import scala.annotation.tailrec

// PriorityQueue[Long]()(scala.math.Ordering.Long.reverse)

case class Tree(x : Int, a : Int)

object Main {
  object EnRich {
    implicit class AString(val self : String) extends AnyVal {
      def splitToIntArray = self.split(" ").map(_.toInt)
    }
  }
  import EnRich._
  def main(args : Array[String]) : Unit = {
    val n = readLine.toInt
    val trees = (1 to n).map(_ => {
                               val (x,a) = {
                                 val xa = readLine.splitToIntArray
                                 (xa(0),xa(1))
                               }
                               Tree(x,a)
                             }).toVector
    val left  = trees.filter({case Tree(x,a) => x < 0}).
                      sortBy({case Tree(x,a) => -x})
    val right = trees.filter({case Tree(x,a) => x > 0}).
                      sortBy({case Tree(x,a) => x})
    val m     = left.length min right.length
    val go_l  = left.take(m+1) ++ right.take(m)
    val go_r  = left.take(m)   ++ right.take(m+1)

    val ans1  = go_l.map({case Tree(x,a) => a}).sum
    val ans2  = go_r.map({case Tree(x,a) => a}).sum

    println(ans1 max ans2)
  }
}

object A558 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1))).sortBy(_._1)
    val neg = in.filter(_._1 < 0).map(_._2)
    val pos = in.filter(_._1 > 0).map(_._2)

    if(neg.length > pos.length) {
      println(pos.sum + neg.takeRight(pos.length+1).sum)
    } else {
      println(neg.sum + pos.take(neg.length+1).sum)
    }
  }

  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 scala.collection.mutable._

object A extends App {
 val apples = new HashMap[Int, Int]()
 val n = readInt
 for(i <- 1 to n) {
  val str = readLine.split(" ").map(_.toInt)
  apples.put(str(0), str(1))
 }
  val pair = apples.groupBy({case (k, v) => k > 0})
                   .map({case (k, v) => (k, v.size)})
  val left  = pair.get(false).getOrElse(0)
  val right = pair.get(true).getOrElse(0)

  var takeLeft, takeRight = 0
  if(left <= right) {
  takeLeft = left
  takeRight = left + 1
  }
  else {
  takeLeft = right + 1
  takeRight = right
  }

  val leftRes = apples.filter({case (k, v) => k < 0}).toList.sortWith((i, j) => i._1 > j._1).take(takeLeft).foldLeft(0)((acc, elem) => acc + elem._2)
  val rightRes = apples.filter({case (k, v) => k > 0}).toList.sortWith((i, j) => i._1 < j._1).take(takeRight).foldLeft(0)( (acc, elem) => acc + elem._2)

  println(leftRes + rightRes)
}

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

  def solve(left: List[(Int, Int)], right: List[(Int, Int)]): Int = (left, right) match {
    case (Nil, Nil) => 0
    case (Nil, (_, b) :: _) => b
    case ((_, a) :: _, Nil) => a
    case ((_, a) :: ls, (_, b) :: rs) => a + b + solve(ls, rs)
  }

  val (l, r) = data.sortBy(_._1.abs).partition(_._1 < 0)
  solve(l, r)
})
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final def isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[B](x: Boolean)(f: => B): Option[B] = if (x) Some(f) else None
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: A): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}

import scala.collection.immutable.SortedMap

object LalaProblem {

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

    implicit val Ord = implicitly[Ordering[Int]]

    var listPos: SortedMap[Int, Int] = SortedMap()
    var listNeg: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    val n: Int = readInt()
    var count: Int = 0

    for (x <- 0 until n) {
      var line = readLine()
      var temp: Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ++ converToMap(temp(0), temp(1))
      } else {
        listPos = listPos ++ converToMap(temp(0), temp(1))
      }
    }

    if (listNeg.size == listPos.size) {
      listNeg.keys.foreach { x => count += listNeg(x) }
      listPos.keys.foreach { x => count += listPos(x) }
    } else {
      if (listNeg.size < listPos.size) {
        listNeg.keys.foreach { x => count += listNeg(x) }
        var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      } else {
        listPos.keys.foreach { x => count += listPos(x) }
        var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      }
    }
    println(count)
  }

  def converToMap(x: String, y: String): Map[Int, Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    Map(xc -> yc)
  }
}

import scala.io._
import Array._
import collection.immutable.SortedMap
import util.control.Breaks._

object lala {
  def main(args: Array[String]) {

    var numberOfTrees: Int = 0
    var walk = 0
    var totalApples = 0

    val line = readInt()
    numberOfTrees = line.toInt

    implicit val Ord = implicitly[Ordering[Int]]

    var field: Map[Int, Int] = Map()
    var fieldPositive: SortedMap[Int, Int] = SortedMap()
    var fieldNegative: SortedMap[Int, Int] = SortedMap()(Ord.reverse)

    for (a <- 0 until numberOfTrees) {
      var temp = new Array[Int](2)
      var line = readLine()

      temp = line.split(" ") map (_.toInt)

      for (b <- 0 until 2) {
        field += (temp(0) -> temp(1))
      }
    }

    for (a <- field) {
      if (a._1 < 0) {
        fieldNegative += (a._1 -> a._2)
      } else {
        fieldPositive += (a._1 -> a._2)
      }
    }

    breakable {
      for (i <- fieldPositive) {
        if (i._1 == walk + 1) {
          totalApples += i._2
          walk += 1
        } else {
          break
        }
      }
    }

    walk = 0

    breakable {
      for (i <- fieldNegative) {
        if (i._1 == walk - 1) {
          totalApples += i._2
          walk -= 1
        } else {
          break
        }
      }
    }

    println(totalApples)

  }
}

object LalaProblem {

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

    var listPos = List[Int]()
    var listNeg = List[Int]()
    val n: Int = readInt()
    var count: Int = 0
    var xc = 1

    for(x <- 0 until n){
      var line = readLine()
      var temp : Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ::: converToList(temp(0), temp(1))
      }else{
        listPos = listPos ::: converToList(temp(0), temp(1))
      }
    }

    if (listNeg.size == listPos.size) {
      for(x <- 0 until listNeg.size){
        if(x % 2 == 0){
          xc = x
          count += listNeg(xc + 1)
          count += listPos(xc + 1)
        }
      }
    }else{
      if(listNeg.size < listPos.size){
        for(x <- 0 until listNeg.size) {
          if(x % 2 == 0){
            xc = x
            count += listNeg(xc + 1)
            count += listPos(xc + 1)
          }
        }
        count += listPos(listNeg.size + 1)
      }else{
         for(x <- 0 until listPos.size) {
          if(x % 2 == 0){
            xc = x
            count += listNeg(xc + 1)
            count += listPos(xc + 1)
          }
        }
        count += listNeg(listPos.size + 1)
      }
    }
    println(count)
  }

  def converToList(x: String, y: String): List[Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    List(xc, yc)
  }
}

import scala.io.StdIn.readLine
import scala.collection.mutable.PriorityQueue
import scala.annotation.tailrec

// PriorityQueue[Long]()(scala.math.Ordering.Long.reverse)

case class Tree(x : Int, a : Int)

object Main {
  object EnRich {
    implicit class AString(val self : String) extends AnyVal {
      def splitToIntArray = self.split(" ").map(_.toInt)
    }
  }
  import EnRich._
  def main(args : Array[String]) : Unit = {
    val n = readLine.toInt
    val trees = (1 to n).map(_ => {
                               val (x,a) = {
                                 val xa = readLine.splitToIntArray
                                 (xa(0),xa(1))
                               }
                               Tree(x,a)
                             }).toVector
    val left  = trees.filter({case Tree(x,a) => x < 0})
    val right = trees.filter({case Tree(x,a) => x > 0})
    val m     = left.length min right.length
    val go_l  = left.take(m+1) ++ right.take(m)
    val go_r  = left.take(m)   ++ right.take(m+1)

    val ans1  = go_l.map({case Tree(x,a) => a}).sum
    val ans2  = go_r.map({case Tree(x,a) => a}).sum

    println(ans1 max ans2)
  }
}

import scala.collection.immutable.SortedMap

object LalaProblem {

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

    implicit val Ord = implicitly[Ordering[Int]]

    var listPos: SortedMap[Int, Int] = SortedMap()
    var listNeg: SortedMap[Int, Int] = SortedMap()(Ord.reverse)
    val n: Int = readInt()
    var count: Int = 0

    for (x <- 0 until n) {
      var line = readLine()
      var temp: Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ++ converToMap(temp(0), temp(1))
      } else {
        listPos = listPos ++ converToMap(temp(0), temp(1))
      }
    }

    println(listNeg)
    println(listPos)

    if (listNeg.size == listPos.size) {
      listNeg.keys.foreach { x => count += listNeg(x) }
      listPos.keys.foreach { x => count += listPos(x) }
    } else {
      if (listNeg.size < listPos.size) {
        listNeg.keys.foreach { x => count += listNeg(x) }
        var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      } else {
        listPos.keys.foreach { x => count += listPos(x) }
        var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      }
    }
    println(count)
  }

  def converToMap(x: String, y: String): Map[Int, Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    Map(xc -> yc)
  }
}

object LalaProblem {

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

    var listPos: Map[Int, Int] = Map()
    var listNeg: Map[Int, Int] = Map()
    val n: Int = readInt()
    var count: Int = 0

    for (x <- 0 until n) {
      var line = readLine()
      var temp: Array[String] = line.split(" ")
      if (temp(0).toInt < 0) {
        listNeg = listNeg ++ converToMap(temp(0), temp(1))
      } else {
        listPos = listPos ++ converToMap(temp(0), temp(1))
      }
    }
    listNeg.toSeq.sortWith(_._1 > _._1)
    listPos.toSeq.sortWith(_._1 < _._1)

    if (listNeg.size == listPos.size) {
      listNeg.keys.foreach { x => count += listNeg(x) }
      listPos.keys.foreach { x => count += listPos(x) }
    } else {
      if (listNeg.size < listPos.size) {
        listNeg.keys.foreach { x => count += listNeg(x) }
        var newMap : Map[Int, Int] = listPos.take(listNeg.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      } else {
        listPos.keys.foreach { x => count += listPos(x) }
        var newMap : Map[Int, Int] = listNeg.take(listPos.size + 1)
        newMap.keys.foreach { x => count += newMap(x) }
      }
    }
    println(count)
  }

  def converToMap(x: String, y: String): Map[Int, Int] = {

    val xc: Int = x.toInt
    val yc: Int = y.toInt
    Map(xc -> yc)
  }
}


import scala.collection.mutable.ArrayBuilder

object P277D extends App {

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

  val MOD = 1000000007

  val Array(d, n) = readInts(2)
  val as = readInts(n)
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (i <- 1 until n) {
    val Array(u, v) = readInts(2)
    adjBuilders(u - 1) += v - 1
    adjBuilders(v - 1) += u - 1
  }

  val adj = adjBuilders.map(_.result)

  def dfs(origin: Int, u: Int, prev: Int, min: Int, max: Int): Long = {

    var cnt = 1L

    for (v <- adj(u)) if (v != prev && (as(v) > min || (as(v) == min && v > origin)) && as(v) <= max) {
      val cnt2 = dfs(origin, v, u, min, max)
      cnt = cnt * (cnt2 + 1) % MOD
    }

    cnt
  }

  var total = 0L
  for (u <- 0 until n) total += dfs(u, u, -1, as(u), as(u) + d)

  println(total % MOD)
}

import java.util.Scanner
import java.util.Arrays
import java.util.ArrayList

object Solution {
    var MOD = 1000 * 1000 * 1000 + 7
    var d: Integer = null
    var used: Array[Boolean] = null
    var graph: Array[ArrayList[Integer]] = null
    var a: Array[Integer] = null

    def bad(a1: Integer, i1: Integer, a2: Integer, i2: Integer): Boolean = {
	return (a1 < a2 || a1 == a2 && i1 < i2 || a1 - a2 > d)
    }

    def dfs(v: Integer, root: Integer): Long = {
	if (bad(a(v), v, a(root), root))
	    return 1
	used(v) = true
	var res: Long = 1
	var index = 0
	for (index <- 0 until graph(v).size()) {
	    val to = graph(v).get(index)
	    if (!used(to))
		res = res * dfs(to, root) % MOD
	}
	return res + 1
    }

    def main(args: Array[String]) = {
	val in = new Scanner(System.in)
	d = in.nextInt()
	val n = in.nextInt()
	a = new Array(n)
	graph = new Array(n)
	var i = 0
	for (i <- 0 until n) {
	    graph(i) = new ArrayList()
	    a(i) = in.nextInt()
	}
	for (i <- 0 until n - 1) {
	    val from = in.nextInt()
	    val to = in.nextInt()
	    graph(from - 1).add(to - 1)
	    graph(to - 1).add(from - 1)
	}
	var res: Long = 0
	used = new Array(n)
	for (i <- 0 until n) {
	    Arrays.fill(used, false)
	    res = (res + dfs(i, i) - 1 + MOD) % MOD
	}
	println(res)
    }
}