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

  (0 until t).foreach { _ =>
    val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val (row, col) = (0 until n).foldLeft((List.fill(m)(0), List.empty[Int])) {
      case ((row, col), _) =>
        val a = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        (row.zip(a).map { case (p, q) => p + q }, a.sum :: col)
    }

    val free = row.count(_ == 0) min col.count(_ == 0)

    val ans =
      if (free % 2 == 0) "Vivek"
      else "Ashish"

    println(ans)
  }
}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {}

  for (_ <- 1 to nextInt) {
    val n, m = nextInt
    val xs = Array.fill(n)(nextInts(m))
    val ux = Array.fill(m)(false)
    val uy = Array.fill(n)(false)
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (xs(i)(j) == 1) {
          uy(i) = true
          ux(j) = true
        }
      }
    }

    val cx = m - ux.count(identity)
    val cy = n - uy.count(identity)
    val moves = Math.min(cx, cy)
    val res = if (moves % 2 == 1) "Ashish" else "Vivek"

    out.println(res)

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val mn = readIntLine()
      val grid = (1 to mn.head).map(_ => readIntLine()).toList
      val min = Math.min(mn.head - calc(grid), mn.last - calc(grid.transpose))
      println(if (min % 2 == 0) "Vivek" else "Ashish")
    }
  }

  def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))

  def calcCols(grid: List[List[Int]]): Int = {
    val arr = Array.ofDim[Boolean](grid.head.length)
    grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))
    arr.count(i => i)
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val mn = readIntLine()
      val grid = (1 to mn.head).map(_ => readIntLine()).toList
      val min = Math.min(calc(grid), calc(grid.transpose))
      println(if (min % 2 == 0) "Vivek" else "Ashish")
    }
  }

  def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))

  def calcCols(grid: List[List[Int]]): Int = {
    val arr = Array.ofDim[Boolean](grid.head.length)
    grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))
    arr.count(i => i)
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val mn = readIntLine()
      val grid = (1 to mn.head).map(_ => readIntLine()).toList
      val min = Math.min(calc(grid), calcCols(grid))
      println(if (min % 2 == 0) "Vivek" else "Ashish")
    }
  }

  def calc(grid: List[List[Int]]) = grid.count(row => row.contains(1))

  def calcCols(grid: List[List[Int]]): Int = {
    val arr = Array.ofDim[Boolean](grid.head.length)
    grid.foreach(row => row.zipWithIndex.foreach(tup => if (tup._1 == 1) arr(tup._2) = true))
    arr.count(i => i)
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}


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, D, M = ni()
    val F = Array.fill[Boolean](N + 1, N + 1)(true)
    rep(N + 1) { i =>
      val l = abs(D - i)
      val r = abs(N - D - i)
      rep(l) { j =>
        F(i)(j) = false
      }
      rep(r) { j =>
        F(i)(N - j) = false
      }
    }

    rep(M) { _ =>
      val x, y = ni()
      out.println(if (F(y)(x)) "YES" else "NO")
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

import scala.io.StdIn

object Problem1030B {
  def main(args: Array[String]): Unit = {
    val vals = StdIn.readLine().split(" ").map(_.toInt)
    val n = vals(0)
    val d = vals(1)
    val m = StdIn.readInt()
    val coords = for (i <- 0 until m) yield {
      val coords = StdIn.readLine().split(" ").map(_.toInt)
      (coords(0), coords(1))
    }
    print(solve(n, d, coords).mkString("\n"))
  }
  def solve(n: Int, d: Int, coords: Seq[(Int, Int)]): Seq[String] = {
    coords.map(coord => {
      val (x, y) = coord
      solve(n, d, x, y)
    }).map(if (_) {
      "YES"
    } else {
      "NO"
    })
  }

  def solve(n: Int, d: Int, x: Int, y: Int): Boolean = {
    if (x + y < d || x + y > 2 * n - d) {
      false
    } else if (x - y < -d || x - y > d) {
      false
    } else {
      true
    }
  }
}


object D extends App {

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

  val Array(n, m) = readInts

  val ys = Array.ofDim[(Char, Int)](n)
  val xs = Array.ofDim[Int](m)

  for (i <- 0 until n) ys(i) = readString.split(" ") match {
    case Array("ATK", x) => ('a', x.toInt)
    case Array("DEF", x) => ('d', x.toInt)
  }

  val yas = ys.filter(_._1 == 'a').map(_._2).sorted
  val yds = ys.filter(_._1 == 'd').map(_._2).sorted

  for (i <- 0 until m) xs(i) = readString.toInt

  var points1 = 0
  val xs1 = xs.sorted
  var di = 0
  var ai = 0

  for (x <- xs1) {
     if (di < yds.length && x > yds(di)) {
       di += 1
     } else if (ai < yas.length && x >= yas(ai)) {
       points1 += x - yas(ai)
       ai += 1
     } else points1 += x
  }

  if (di < yds.length || ai < yas.length) points1 = 0

  var points2 = 0
  ai = 0

  for (x <- xs1.reverse) {
    if (ai < yas.length && x >= yas(ai)) {
       points2 += x - yas(ai)
       ai += 1
     }
  }

  println(points1 max points2)
}

object D extends App {

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

  val Array(n, m) = readInts

  val ys = Array.ofDim[(Char, Int)](n)
  val xs = Array.ofDim[Int](m)

  for (i <- 0 until n) ys(i) = readString.split(" ") match {
    case Array("ATK", x) => ('a', x.toInt)
    case Array("DEF", x) => ('d', x.toInt)
  }

  val yas = ys.filter(_._1 == 'a').map(_._2).sorted
  val yds = ys.filter(_._1 == 'd').map(_._2).sorted

  for (i <- 0 until m) xs(i) = readString.toInt

  var points1 = 0
  val xs1 = xs.sorted
  var di = 0
  var ai = 0

  for (x <- xs) {
     if (di < yds.length && x > yds(di)) {
       di += 1
     } else if (ai < yas.length && x >= yas(ai)) {
       points1 += x - yas(ai)
       ai += 1
     } else points1 += x
  }

  if (di < yds.length || ai < yas.length) points1 = 0

  var points2 = 0
  ai = 0

  for (x <- xs.reverse) {
    if (ai < yas.length && x >= yas(ai)) {
       points2 += x - yas(ai)
       ai += 1
     }
  }

  println(points1 max points2)
}


object Main
{
	def countareas(areas:Array[Int], a:Int):Int =
	{
		var i = a
		var j = a
		while(i > 0 && areas(i - 1) <= areas(i)) i -= 1
		while(j < areas.length - 1 && areas(j + 1) <= areas(j)) j += 1
		return j - i + 1
	}

	def main(args:Array[String])
	{
		readInt;
		val a = readLine.split(" ").map(i => i.toInt)
		println((0 until a.length).map(i => countareas(a, i)).max)
	}
}

import scala.io.Source

object Solution extends App {
  def count(height: IndexedSeq[Int], i: Int): Int = {
    val left = (i - 1 to 0 by -1).find(j => height(j) > height(j + 1))
    val right = (i + 1 until height.length).find(j => height(j) > height(j - 1))
    if (left.isEmpty)
      right.getOrElse(n)
    else
      right.getOrElse(n) - 1 - left.get
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val height = in.next().split(' ').map(_.toInt)
//  println((0 until n).map(i => count(height, i)))
  println((0 until n).map(i => count(height, i)).max)
}


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 private final 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 private final 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._

  case class Entry(ix: Int, v: Int, isFront: Boolean)
}

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 = {
    import java.util.Comparator
    val n, m, h = ni()
    val front = na(m)
    val left = na(n)
    val top = nm(n, m)
    val ans = Array.fill[Int](n, m)(-1)
    val E = Array.ofDim[Entry](n + m)
    REP(m) { i =>
      E(i) = Entry(i, front(i), isFront = true)
    }
    REP(n) { i =>
      E(m + i) = Entry(i, left(i), isFront = false)
    }
    sort(E, new Comparator[Entry] {
      override def compare(o1: Entry, o2: Entry): Int = Integer.compare(o1.v, o2.v)
    })

    debug(E.mkString(" "))

    REP(E.length) { ii =>
      val e = E(ii)
      if (e.v > 0) {
        if (E(ii).isFront) {
          val j = e.ix
          REP(n) { i =>
            if (ans(i)(j) == -1 && top(i)(j) == 1) {
              ans(i)(j) = e.v
            }
          }
        } else {
          val i = e.ix
          REP(m) { j =>
            if (ans(i)(j) == -1 && top(i)(j) == 1) {
              ans(i)(j) = e.v
            }
          }
        }
      }
    }
    debugDim(ans)

    REP(n) { i =>
      REP(m) { j =>
        if (ans(i)(j) == -1) ans(i)(j) = 0
      }
    }
    REP(n) { i =>
      out.println(ans(i).mkString(" "))
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val in = io.Source.stdin.getLines()
    val Array(n, m, h) = in.next().split(" ").map(_.toInt)

    val front = in.next().split(" ").map(_.toInt)
    val left = in.next().split(" ").map(_.toInt)

    val heights = Array.ofDim[Int](n,m)
    (0 until n).foreach { i =>
      heights(i) = in.next().split(" ").map(_.toInt)
    }

    val answer = Array.ofDim[Int](n,m)

    for (i <- 0 until n) {
      for (j <- 0 until m) {
        if (heights(i)(j) == 0) {
          answer(i)(j) = 0
        } else {
          answer(i)(j) = Math.min(Math.max(heights(i)(j), left(i)), Math.max(heights(i)(j), front(j)))
        }
      }
    }

    for (i <- 0 until n) {
      println(answer(i).mkString(" "))
    }

  }
}

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

object CodeForces2 extends App {

  val Array(n, m, h) = readLine().split(" ").map(_.toInt)

  val front = readLine().split(" ").map(_.toInt)
  val left = readLine().split(" ").map(_.toInt)

  var i = 0
  var lines = mutable.Buffer[String]()
  while (i < n) {
    val line = readLine().split(" ").map(_.toInt)
    var j = 0
    while (j < line.length) {
      line(j) = line(j) * Math.min(front(j), left(i))
      j += 1
    }
    lines += line.mkString(" ")
    i += 1
  }

  lines.foreach(println)

  def println(x: Any): Unit = {
    Console.println(x)
    Console.flush()
  }

  def readLine(): String = StdIn.readLine()
}

import scala.io.StdIn

object Codeforces1153B {

  def getBrickHeights(n: Int, m: Int, maxHeight: Int, a: Seq[Int], b: Seq[Int], h: Seq[Seq[Int]]): Seq[Seq[Int]] = {
    (0 until n).map(i => {
      (0 until m).map(j => {
        val value = math.min(a(j), b(i))
        if (h(i)(j) == 1) value else 0
      })
    })
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m, maxHeight) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)
    val b = StdIn.readLine().trim.split(" ").map(_.toInt)
    val h = (1 to n).map(_ => StdIn.readLine().trim.split(" ").map(_.toInt).toSeq)
    val gridHeights = getBrickHeights(n, m, maxHeight, a, b, h)
    for (rowHeights <- gridHeights) {
      for (cell <- rowHeights) {
        print(cell + " ")
      }
      println()
    }
  }
}


import scala.collection.mutable

object E extends App {

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readInts(n)
  val max = as.max
  val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }

  for (i <- as.indices) {
    positionBuilders(as(i)) += i
  }

  val positionsByA = positionBuilders.map(_.result)

  val bit = new BIT(Array.fill(n){ 0 })
  for (i <- 0 until n) bit.update(i, 1)

  var res = 0L
  var p = 0
  var a = 1

  while (a <= max) {
    val positions = positionsByA(a)
    if (positions.nonEmpty) {
      if (positions.head >= p) {
        val nextP = positions.last
        res += bit.rangeQuery(p, nextP)
        p = nextP
        for (pos <- positions) {
          bit.update(pos, -1)
        }
      } else {
        var nextP = p
        for (pos <- positions) {
          if (pos < p) nextP = pos
        }
        res += bit.rangeQuery(0, nextP)
        res += bit.rangeQuery(p, n - 1)
        p = nextP
        for (pos <- positions) {
          bit.update(pos, -1)
        }
      }
    }
    a += 1
  }

  println(res)
}

import scala.collection.mutable

object E extends App {

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readInts(n)
  val max = as.max
  val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }

  for (i <- as.indices) {
    positionBuilders(as(i)) += i
  }

  val positionsByA = positionBuilders.map(_.result)

  val bit = new BIT(Array.fill(n){ 0 })
  for (i <- 0 until n) bit.update(i, 1)

  var res = 0L
  var pos = 0
  var a = 1

  while (a <= max) {
    val positions = positionsByA(a)
    if (positions.nonEmpty) {
      var nextP = pos
      if (positions.head >= pos) {
        nextP = positions.last
        res += bit.rangeQuery(pos, nextP)
      } else {
        for (p <- positions) {
          if (p < pos) nextP = p
        }
        res += bit.rangeQuery(pos, n - 1) + bit.query(nextP)
      }
      for (p <- positions) {
        bit.update(p, -1)
      }
      pos = nextP
    }
    a += 1
  }

  println(res)
}

import scala.collection.mutable

object E extends App {

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

  class BIT(src: Array[Long]) {

    private val t = Array.fill(src.length) { 0L }

    for (i <- src.indices) update(i, src(i))

    def query(r: Int, acc: Long = 0): Long =
      if (r < 0) acc else query((r & (r + 1)) - 1, acc + t(r))

    def rangeQuery(l: Int, r: Int) = query(r) - query(l - 1)

    def update(i: Int, delta: Long): Unit =
      if (i < t.length) {
        t(i) += delta
        update(i | (i + 1), delta)
      }

  }

  val Array(n) = readInts(1)
  val as = readInts(n)
  val max = as.max
  val positionBuilders = Array.fill(max + 1){ new mutable.ArrayBuilder.ofInt }

  for (i <- as.indices) {
    positionBuilders(as(i)) += i
  }

  val positionsByA = positionBuilders.map(_.result)

  val bit = new BIT(Array.fill(n){ 0 })
  for (i <- 0 until n) bit.update(i, 1)

  var res = 0L
  var pos = 0
  var a = 1

  while (a <= max) {
    val positions = positionsByA(a)
    if (positions.nonEmpty) {
      var nextP = pos
      if (positions.head >= pos) {
        nextP = positions.last
        res += bit.rangeQuery(pos, nextP)
      } else {
        for (pos <- positions) {
          if (pos < pos) nextP = pos
        }
        res += bit.rangeQuery(pos, n - 1) + bit.query(nextP)
      }
      for (pos <- positions) {
        bit.update(pos, -1)
      }
      pos = nextP
    }
    a += 1
  }

  println(res)
}


object A extends App {

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

  val Array(n, s) = readInts(2)
  val as, bs = readInts(n)

  if (as(0) == 1 && as(s - 1) == 1) println("YES")
  else if (as(0) == 1 && bs(s - 1) == 1) {
    if ((s until n).exists(i => as(i) == 1 && bs(i) == 1)) println("YES")
    else println("NO")
  } else println("NO")

  Console.flush
}

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

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

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

    val Y = "YES"
    val N = "NO"

    var isOk:Boolean = false

    def solve = {
        var n = nextInt
        var loc = nextInt

        var s1 = (for (i <- 0 until n) yield nextInt).toArray
        var s2 = (for (i <- 0 until n) yield nextInt).toArray

        if (loc == 1) {
            isOk = true
        } else if (s1(loc - 1) == 0 && s2(loc - 1) == 0) {
            isOk = false
        } else if (s1(0) == 0 && loc > 1) {
            isOk = false
        } else {
            // for
            for (i <- 0 until n) {
                // println(i + "," + n + "," + loc)
                if (s1(i) == 1) {
                    if (i == loc - 1) {
                        isOk = true
                    } else if (s2(loc - 1) == 1 && i >= loc - 1 && s2(i) == 1) {
                        isOk = true
                    }
                }
            }
        }

        // println(s"$n, $loc, $s1")
    }

    solve
    println(if(isOk) Y else N)
}

object Main {
  import java.io.PrintStream

  def main(args: Array[String]): Unit = {
    val s = new Main()
    val ps = new PrintStream(Console.out)
    Console.withOut(ps) {
      s.solve()
    }
    ps.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
  import scala.Console

  val MOD = 1000000007

  def solve(): Unit = {
    val N, S = ni()
    val A, B = na(N) map (_ == 1)

    def openABAfter = {
      S until N exists { i =>
        A(i) && B(i)
      }
    }

    val ok = A(0) && ((A(S - 1) || B(S - 1) && openABAfter))
    println(if (ok) "YES" else "NO")
  }

  class InputReader(reader: BufferedReader) {
    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(Console.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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    //println(s"n a ${n} ${a}")

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)

    if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {
      println("NO")
    }
    else if (first(a - 1) == 1){
      println("YES")
    }
    else {
      var found = false
      (a - 1 until n).foreach{ mid =>
        if (first(mid) == 1 && second(mid) == 1) {
          found = true
        }
      }

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

  }
}

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    println(first.mkString(" "))
    println(second.mkString(" "))

    if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)

    if (first(0) == 0 || (first(a - 1) == 0 && second(a - 1) == 0)) {
      println("NO")
    }
    else if (first(a - 1) == 0){
      println("YES")
    }
    else {
      var found = false
      (a - 1 until n).foreach{ mid =>
        if (first(mid) == 1 && second(mid) == 1) {
          found = true
        }
      }

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

  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 >= 0).map(_._2)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 >= 0).map(_._2)

    //println(first.mkString(" "))
    //println(second.mkString(" "))

    if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

//package codeforce.mailru

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 > 0).map(_._2)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.filter(_._1 > 0).map(_._2)

    //println(first.mkString(" "))
    //println(second.mkString(" "))

    if (!first.contains(0) || (!first.contains(a - 1) && !second.contains(a - 1))) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

object A {
  def main(args: Array[String]): Unit = {
    val row = scala.io.StdIn.readLine().split("\\s+").map(_.toInt)
    val n = row(0)
    val a = row(1)

    val first = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    val second = scala.io.StdIn.readLine().split("\\s+").map(_.toInt).zipWithIndex.map(_._2).filter(_ > 0)

    if (!first.contains(0) == 0 || (!first.contains(a - 1) == 0 && !second.contains(a - 1) == 0)) {
      println("NO")
    }
    else {
      if (first.contains(a)) {
        println("YES")
      }
      else {
        if (first.intersect(second).filter(_ >= a).size > 0) {
          println("YES")
        }
        else {
          println("NO")
        }
      }
    }
  }
}

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

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

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

    val Y = "YES"
    val N = "NO"

    var isOk:Boolean = false

    def solve = {
        var n = nextInt
        var loc = nextInt

        var s1 = (for (i <- 0 until n) yield nextInt).toArray
        var s2 = (for (i <- 0 until n) yield nextInt).toArray

        if (loc == 1) {
            isOk = true
        } else if (s1(0) == 0 && loc > 1) {
            isOk = false
        } else {
            // for
            for (i <- 0 until n) {
                // println(i + "," + n + "," + loc)
                if (s1(i) == 1) {
                    if (i == loc - 1) {
                        isOk = true
                    } else if (s2(loc - 1) == 1) {
                        isOk = true
                    }
                }
            }
        }

        // println(s"$n, $loc, $s1")
    }

    solve
    println(if(isOk) Y else N)
}

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

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

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

    val Y = "YES"
    val N = "NO"

    var isOk:Boolean = false

    def solve = {
        var n = nextInt
        var loc = nextInt

        var s1 = (for (i <- 0 until n) yield nextInt).toArray
        var s2 = (for (i <- 0 until n) yield nextInt).toArray

        if (loc == 1) {
            isOk = true
        } else if (s1(0) == 0 && loc > 1) {
            isOk = false
        } else {
            // for
            for (i <- 0 until n) {
                // println(i + "," + n + "," + loc)
                if (s1(i) == 1) {
                    if (i == loc - 1) {
                        isOk = true
                    }
                }
                if (s2(loc - 1) == 1 && i >= loc - 1 && s2(i) == 1) {
                        isOk = true
                }
            }
        }

        // println(s"$n, $loc, $s1")
    }

    solve
    println(if(isOk) Y else N)
}


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

  override def apply(io: IO): io.type = {
    val nums = io.read[Vector[Long]]
    val counts = nums.groupBy(identity).mapValues(_.size).toMutable

    val Some(first) = nums.find(i => !counts.contains(3*i) && (i%2 == 1 || !counts.contains(i/2)))

    val ans = Vector.iterate(first, nums.length) {i =>
      dec(counts, i)
      if(i%3 == 0 && counts.contains(i/3)) {
        i/3
      } else if (counts.contains(2*i)) {
        2*i
      } else {
        throw new IllegalStateException("Cannot be here!")
      }
    }

    io.writeAll(ans)
  }

  def dec[A](map: mutable.Map[A, Int], key: A) = {
    if (map(key) == 1) map.remove(key) else map(key) = map(key) - 1
  }

  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
  }

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

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

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

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

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

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

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

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

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

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

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

object problemA {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable
    import scala.util.control.Breaks._
    import scala.collection.JavaConverters._

    val source = System.in
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val n = read().toInt
        val a = readArray().map(_.toLong)

        val ch = Array.fill[Boolean](n)(true)
        val f = new Array[Long](n)
        var c = 0

        def solve(k: Int): Unit = {
            if (c == n) {
                f.foreach(p => print(s"$p "))
                return
            }

            for (i <- 0 until n if ch(i)) {
                if (a(k) % 3 == 0 && a(k) / 3 == a(i)) {
                    f(c) = a(i)
                    c += 1
                    ch(i) = false
                    solve(i)
                    ch(i) = true
                    c -= 1

                } else if (a(k) * 2 == a(i)) {
                    f(c) = a(i)
                    c += 1
                    ch(i) = false
                    solve(i)
                    ch(i) = true
                    c -= 1
                }
            }
        }

        for (i <- 0 until n) {
            f(c) = a(i)
            c += 1
            ch(i) = false
            solve(i)
            ch(i) = true
            c -= 1
        }
    }
}

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = map(N)(_ => nl())

    def factorize(a: Long) = {
      var x = a

      var i = 0
      while(x % 2 == 0) {
        i += 1
        x /= 2
      }

      var j = 0
      while(x % 3 == 0) {
        j += 1
        x /= 3
      }

      (i, j, x)
    }

    def toNum(p: (Int, Int, Long)) = {
      pow(2, p._1) * pow(3, p._2) * p._3
    }

    val p = (A map factorize).sortBy(a => a._1 + a._2 * -1)
    val n = p map toNum
    out.println(n.mkString(" "))
  }

  def pow(x: Long, n: Long): Long = {
    n match {
      case 0 => 1
      case _ =>
        val r = pow(x * x, n / 2)
        if (n % 2 == 1) r * x else r
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

object D977 {

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

  def main(args: Array[String]): Unit = {
    val n = readInt
    val arr = readLongs(n).toSet
    val res = ArrayBuffer.empty[Long]
    arr.exists { _start =>
      var start = _start
      res.clear()
      res.append(start)
      while (res.length != n && ((start % 3 == 0 && arr.contains(start / 3)) || (start <= (Long.MaxValue >> 1) && arr
               .contains(start * 2)))) {
        if (start % 3 == 0 && arr.contains(start / 3)) {
          res.append(start / 3)
          start /= 3
        } else {
          res.append(start * 2)
          start *= 2
        }
      }
      res.length == n
    }

    out.println(res.mkString(" "))
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}


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

import scala.collection.mutable

object C extends App {

  def solve(in: InputReader): Unit = {
    val sticks = new Array[Int](1000000)
    val t = in.nextInt
    val sb = StringBuilder.newBuilder
    val met = mutable.HashMap.empty[Int, Boolean]
    var x: Int = 0
    var y: Int = 0
    var a: Int = 0
    var b: Int = 0
    var n: Int = 0
    var count: Int = 0
    var cur: Int = 0

    for (_ <- 1 to t) {
      n = in.nextInt
      count = 0
      met.clear()
      for (_ <- 0 until n) {
        cur = in.nextInt
        if (met.getOrElse(cur, false)) {
          sticks.update(count, cur)
          count = count + 1
          met.update(cur, false)
        } else {
          met.update(cur, true)
        }
      }
      java.util.Arrays.sort(sticks, 0, count)
      x = sticks(0)
      y = sticks(1)
      for (i <- 0 until count - 1) {
        a = sticks(i)
        b = sticks(i + 1)
        if (x.toDouble / y.toDouble < a.toDouble / b.toDouble) {
          x = a
          y = b
        }
      }
      sb.append(x)
      sb.append(' ')
      sb.append(x)
      sb.append(' ')
      sb.append(y)
      sb.append(' ')
      sb.append(y)
      sb.append('\n')
    }
    print(sb.toString())
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

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

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

}

import java.util

import scala.collection.mutable

object C extends App {

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

  val Array(t) = readInts(1)
  val res = new StringBuilder
  val counts = Array.fill(10001)(0)

  def getX(a: Int, b: Int): Double = {
    val p = 2d * (a + b)
    val s = a * b
    p * p / s
  }

  for (_ <- 1 to t) {
    val Array(n) = readInts(1)
    val as = readInts(n)

    var i = 0
    while (i < n) {
      counts(as(i)) = 0
      i += 1
    }

    i = 0
    val bsBuilder = new mutable.ArrayBuilder.ofInt
    while (i < n) {
      counts(as(i)) += 1
      if (counts(as(i)) == 2) bsBuilder += as(i)
      i += 1
    }
    val bs = bsBuilder.result().sorted

    i = 0
    var bestX = Double.PositiveInfinity
    var bestA = 0
    var bestB = 0
    while (i < bs.length) {
      val a = bs(i)
      if (counts(a) >= 4) {
        val x = getX(a, a)
        if (x < bestX) {
          bestX = x
          bestA = a
          bestB = a
        }
      }
      var j = i + 1
      while (j < bs.length) {
        val b = bs(j)
        val x = getX(a, b)
        if (x < bestX) {
          bestX = x
          bestA = a
          bestB = b
          j = bs.length
        } else {
          j = bs.length
        }
      }
      i += 1
    }
    val aStr = bestA.toString
    val bStr = bestB.toString
    res ++= aStr
    res += ' '
    res ++= aStr
    res += ' '
    res ++= bStr
    res += ' '
    res ++= bStr
    res += '\n'
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.result)

  Console.flush
}

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

import scala.collection.mutable

object C extends App {

  def solve(in: InputReader): Unit = {
    val sticks = new Array[Int](1000000)
    val t = in.nextInt
    val sb = StringBuilder.newBuilder
    val met = mutable.HashMap.empty[Int, Boolean]
    var x: Int = 0
    var y: Int = 0
    var a: Int = 0
    var b: Int = 0
    var n: Int = 0
    var count: Int = 0
    var cur: Int = 0

    for (_ <- 1 to t) {
      n = in.nextInt
      count = 0
      for (_ <- 0 until n) {
        cur = in.nextInt
        if (met.getOrElse(cur, false)) {
          sticks.update(count, cur)
          count = count + 1
          met.update(cur, false)
        } else {
          met.update(cur, true)
        }
      }
      java.util.Arrays.sort(sticks, 0, count)
      x = sticks(0)
      y = sticks(1)
      for (i <- 0 until count - 1) {
        a = sticks(i)
        b = sticks(i + 1)
        if (x.toDouble / y.toDouble < a.toDouble / b.toDouble) {
          x = a
          y = b
        }
      }
      sb.append(x)
      sb.append(' ')
      sb.append(x)
      sb.append(' ')
      sb.append(y)
      sb.append(' ')
      sb.append(y)
      sb.append('\n')
    }
    print(sb.toString())
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

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

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

}

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

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

object C extends App {

  def solve(in: InputReader): Unit = {
    val met = mutable.HashMap.empty[Int, Int]
    val t = in.nextInt

    for (_ <- 1 to t) {
      met.clear()
      val n = in.nextInt
      val possibleSides = new ArrayBuffer[Int](n)
      for (_ <- 1 to n) {
        val cur = in.nextInt
        val times = met.getOrElse(cur, 0)
        if (times == 3) {
          printf("%d %d %d %d\n", cur, cur, cur, cur)
          return Unit
        }
        if (times % 2 == 1) {
          possibleSides.append(cur)
        }
        met.update(cur, times + 1)
      }
      val sorted = possibleSides.toVector.sorted
      var (x, y) = (sorted.head, sorted(1))
      sorted.sliding(2).foreach { case Seq(a, b) =>
        if (x.toDouble / y.toDouble < a.toDouble / b.toDouble) {
          x = a
          y = b
        }
      }
      printf("%d %d %d %d\n", x, x, y, y)
    }
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

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

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

}


import scala.math
object C {
  def main(args: Array[String]) {
    val s0 = readLine()
    val s1 = readLine();
    if (s1.length() != s0.length() || math.min(s1.length, s0.length) < 0 || (!s1.contains("1") && s0.contains("1")) || (!s0.contains("1") && s1.contains("1"))) {
      println("NO")
      return;
    }
    println("YES");
  }
}

object Main {
  def main(args: Array[String]) {
    val s1 = readLine()
    val s2 = readLine()

    val zero1 = s1.count(_ == '0') == s1.size
    val zero2 = s2.count(_ == '0') == s2.size

    if(s1.size != s2.size || zero1 != zero2) println("NO")
    else println("YES")
  }
}

object CF173Div2C {
  def main(args: Array[String]){
    val a = readLine
    val b = readLine
    val res = {
      if(a==b) "YES"
      else if(a.length != b.length) "NO"
      else if(!a.contains('1') || !b.contains('1')) "NO"
      else "YES"
    }
    println(res)
  }
}

object C {
  def main(args: Array[String]) {
    val s0 = readLine()
    val s1 = readLine();
    if (s1.length() != s0.length() || (!s1.contains("1") && s0.contains("1"))) {
      println("NO")
      return;
    }
    println("YES");
  }
}


object A601 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val graph = Array.fill(n)(cu.Set.empty[Int])
    for (_ <- 1 to m) {
      val Array(x, y) = readInts(2).map(_ - 1)
      graph(x).add(y)
      graph(y).add(x)
    }
    val isTrainDone = graph(0).contains(n - 1)
    var res = -1

    def canVisit(top: Int) = {
      if (isTrainDone) {
        (0 until n).filter(_ != top).toSet.diff(graph(top))
      } else {
        graph(top)
      }
    }

    val q = cu.Queue.empty[Int]
    val vis = Array.fill(n)(false)
    val dist = Array.fill(n)(0)
    q.enqueue(0)
    var curr = 0
    while (q.nonEmpty && res == -1) {
      curr += 1
      val top = q.dequeue()
      val connections = canVisit(top)
      for (edge <- connections) {
        if (!vis(edge)) {
          vis(edge) = true
          dist(edge) = dist(top) + 1
          if (edge == n - 1 && res == -1) {
            res = dist(edge)
          } else {
            q.enqueue(edge)
          }
        }
      }
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(
      new java.io.InputStreamReader(
        if (System.getProperty("ONLINE_JUDGE") != null) System.in
        else new java.io.FileInputStream("src/input")
      )
    )
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

}

object C{
  import scala.collection.mutable.Queue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val bd=Array.ofDim[Int](n,n)
    for(i<-0 until m){
      val i0=nextInt-1
      val j=nextInt-1
      bd(i0)(j)=1
      bd(j)(i0)=1
    }
    val con=1-bd(0)(n-1)
    //con is the long way
    val q=new Queue[(Int,Int)]
    q+=((0,0))

    var le= -1
    val visited=Array.ofDim[Int](n)
    breakable{
    while(!q.isEmpty){
      val (cn,cl)=q.dequeue

      for(i<-0 until n if i!=cn){
        if(bd(i)(cn)==con){
          if(i==n-1){
            le=cl+1
            break
          }else{
            if(visited(i)==0){
              q+=((i,cl+1))
              visited(i)=1
            }
          }
        }
      }
    }
    }
    out.println(le)
    //code ends here
    out.flush
    out.close
  }
}

import scala.collection.mutable

object Solution extends App {

  def bfs(iron: Array[mutable.Set[Int]], isIron: Boolean): Int = {
    val n = iron.length - 1
    val marked = Array.ofDim[Boolean](n + 1)
    marked(1) = true
    var fringe = List(1)
    var count = 0
    while (fringe.nonEmpty) {
      var newFringe = List.empty[Int]
      fringe.foreach { i =>
        if (i == n)
          return count
        else {
          if (isIron) {
            iron(i).foreach{ j =>
              if (!marked(j)) {
                marked(j) = true
                newFringe ::= j
              }
            }
          } else {
            (1 to n).foreach { j =>
              if (!iron(i).contains(j) && !marked(j)) {
                marked(j) = true
                newFringe ::= j
              }
            }
          }
        }
      }
      count += 1
      fringe = newFringe
    }
    -1
  }

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val iron: Array[mutable.Set[Int]] = Array.fill(n + 1) {scala.collection.mutable.Set.empty[Int]}
  (1 to m).foreach { _ =>
    val Array(u, v) = in.next().split(' ').map(_.toInt)
    iron(u) += v
    iron(v) += u
  }
  println(bfs(iron, !iron(n).contains(1)))
}

object C{
  import scala.collection.mutable.Queue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val bd=Array.ofDim[Int](n,n)
    for(i<-0 until m){
      val i0=nextInt-1
      val j=nextInt-1
      bd(i0)(j)=1
      bd(j)(i0)=1
    }
    if(n==400 && m==42944){
      //I don't know why there is memory issue, testing
      out.println("reading finished")
      return
    }
    val con=1-bd(0)(n-1)
    //con is the long way
    val q=new Queue[(Int,Int)]
    q+=((0,0))
    var le= -1
    val visited=Array.ofDim[Int](n)
    breakable{
    while(!q.isEmpty){
      val (cn,cl)=q.dequeue
      //out.println(cn+" "+cl)
      visited(cn)=1
      for(i<-0 until n if i!=cn){
        if(bd(i)(cn)==con){
          if(i==n-1){
            le=cl+1
            break
          }else{
            if(visited(i)==0){
              q+=((i,cl+1))
            }
          }
        }
      }
    }
    }
    out.println(le)
    //code ends here
    out.flush
    out.close
  }
}

object C{
  import scala.collection.mutable.Queue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val (n,m)=(nextInt,nextInt)
    val bd=Array.ofDim[Int](n,n)
    for(i<-0 until m){
      val i0=nextInt-1
      val j=nextInt-1
      bd(i0)(j)=1
      bd(j)(i0)=1
    }
    val con=1-bd(0)(n-1)
    //con is the long way
    val q=new Queue[(Int,Int)]
    q+=((0,0))
    if(n==400 && m==42944){
      //I don't know why there is memory issue, testing
      for(i<-0 until 400){
        q+=((i,i+1))
      }
      out.println("queue finished")
      out.flush
      out.close
      return
    }

    var le= -1
    val visited=Array.ofDim[Int](n)
    breakable{
    while(!q.isEmpty){
      val (cn,cl)=q.dequeue
      //out.println(cn+" "+cl)
      visited(cn)=1
      for(i<-0 until n if i!=cn){
        if(bd(i)(cn)==con){
          if(i==n-1){
            le=cl+1
            break
          }else{
            if(visited(i)==0){
              q+=((i,cl+1))
            }
          }
        }
      }
    }
    }
    out.println(le)
    //code ends here
    out.flush
    out.close
  }
}


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

  val t = readInt()

  (0 until t).foreach { _ =>
    val caves      = readInt()
    val (power, _) = Array
      .fill(caves) {
        val Array(k, ak @ _*) = readLine().split(" ").map(_.toInt)
        val power             = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }
        (power, k)
      }
      .sorted
      .reduce[(Int, Int)] {
        case ((a, ak), (b, bk)) if (b > a + ak) => (b - ak, ak + bk)
        case ((a, ak), (b, bk))                 => (a, ak + bk)
      }

    println(power)
  }

}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()
    def readArrayInt(n: Int = 0): Array[Int] = {
        if (n == 0)
            return reader.readLine().split(" ").map(_.toInt)

        val a = new Array[Int](n)
        for (i <- 0 until n) {
            a(i) = readInt()
        }
        a
    }

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()

        val f = new Array[(Int, Int)](n)
        for (i <- 0 until n) {
            val k = readInt()
            var max = -Int.MaxValue
            for (j <- 0 until k) {
                val a = readInt()
                val b = a - j + 1
                max = Math.max(b, max)
            }
            f(i) = ((max, max + k))
        }

        quickSort[(Int, Int)](f)(Ordering.by[(Int, Int), Int](_._1))

        var l = f(0)._1
        var r = f(0)._2
        for (i <- 1 until n) {
            if (f(i)._1 <= r) {
                r += f(i)._2 - f(i)._1
            } else {
                l += f(i)._1 - r
                r = f(i)._2
            }
        }

        writer.println(l)
    }

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val caves      = readInt()
    val (power, _) = Array
      .fill(caves) {
        val Array(k, ak @ _*) = readLine().split(" ").map(_.toInt)
        val power             = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }
        (power, k)
      }
      .sorted
      .reduce[(Int, Int)] { case ((a, ak), (b, bk)) => (a max (b - ak), ak + bk) }

    println(power)
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val caves      = readInt()
    val (power, _) = Array
      .fill(caves) {
        val Array(k, ak @ _*) = readLine().split(" ").map(_.toInt)
        val power             = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }
        (power, k)
      }
      .sorted
      .reduce[(Int, Int)] {
        case ((a, ak), (b, bk)) if (b > a + ak) => (b - ak, bk)
        case ((a, ak), (b, bk))                 => (a, ak + bk)
      }

    println(power)
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val caves      = readInt()
    val (power, _) = Array
      .fill(caves) {
        val Array(k, ak @ _*) = readLine().split(" ").map(_.toInt)
        val power             = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }
        (power, power + k)
      }
      .sorted
      .reduce[(Int, Int)] {
        case ((a1, a2), (b1, b2)) if (b1 > a2) => (b1 - (a2 - a1), b1 - (a2 - a1) + (b2 - b1))
        case ((a1, _), (_, b2))                => (a1, b2)
      }

    println(power)
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val caves      = readInt()
    val (power, _) = Array
      .fill(caves) {
        val Array(k, ak @ _*) = readLine().split(" ").map(_.toInt)
        val power             = ak.zipWithIndex.foldLeft(0) { case (power, (ai, i)) => power max (ai - i + 1) }
        (power, power + k)
      }
      .sorted
      .reduce[(Int, Int)] {
        case ((_, a2), (b1, b2)) if (b1 > a2) => (b1, b2)
        case ((a1, _), (_, b2))               => (a1, b2)
      }

    println(power)
  }

}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()
    def readArrayInt(n: Int = 0): Array[Int] = {
        if (n == 0)
            return reader.readLine().split(" ").map(_.toInt)

        val a = new Array[Int](n)
        for (i <- 0 until n) {
            a(i) = readInt()
        }
        a
    }

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()

        val f = new Array[(Int, Int)](n)
        for (i <- 0 until n) {
            val k = readInt()
            var max = -Int.MaxValue
            for (j <- 0 until k) {
                val a = readInt()
                val b = a - j + 1
                max = Math.max(b, max)
            }
            f(i) = ((max, max + k))
        }

        quickSort[(Int, Int)](f)(Ordering.by[(Int, Int), Int](_._1))

        var l = f(0)._1
        var r = f(0)._2
        for (i <- 1 until n) {
            if (f(i)._1 <= r) {
                r += f(i)._2 - f(i)._1
            } else {
                l += f(i)._1 - r
                r += f(i)._2
            }
        }

        writer.println(l)
    }

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}


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

  override def apply(io: IO): io.type = {
    val n, k = io.read[Int]
    val as = io.read[IndexedSeq, Int](n).sorted.lift

    var i, s = 0
    val ans = mutable.ArrayBuffer.empty[Int]
    while(ans.length < k) {
      as(i) match {
        case None => ans.append(0)
        case Some(a) if a > s =>
          ans.append(a - s)
          s += a - s
        case _ =>
      }
      i += 1
    }

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

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

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

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

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

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

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

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

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

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

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

 import scala.io.StdIn

object B extends App {
  def readInts = StdIn.readLine().split(" ").map(_.toInt)

  val Array(n, k) = readInts
  val A = readInts.distinct.sorted

  def solve() = {
    var i = 0
    var offset = 0

    (0 until k).map { _ =>
      while (i < A.length && (A(i) - offset) == 0) i += 1
      if (i >= A.length) 0
      else {
        val res = A(i) - offset
        offset = A(i)
        res
      }
    }
  }

  println(solve().mkString("\n"))
}

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, K = ni()
    val A = na(N)
    val nums = mutable.Set[Int]()
    REP(N) { i =>
      nums += A(i)
    }
    val sorted = nums.toSeq.sorted
    var sum = 0L
    val n = sorted.length
    REP(K) { i =>
      if (i < n) {
        val a = sorted(i) - sum
        sum += a
        out.println(a)
      } else {
        out.println(0)
      }
    }
  }

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

import java.io.PrintWriter
import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {
    val xs = SortedSet(as: _*).toStream
    val xs0 = 0 #:: xs
    (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    val out = new PrintWriter(System.out)
    solution foreach out.println
    out.close()
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import java.io.PrintWriter
import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {
    val xs = SortedSet(as: _*).toStream
    val xs0 = 0 #:: xs
    (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    val out = new PrintWriter(System.out)
    out.println(solution.mkString("\n"))
    out.close()
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    // Just submitting this to test performance
    val out = new java.io.PrintWriter(System.out)
    val xs = SortedSet(as: _*).take(k).toList
    var last = 0
    for {
      x <- xs
    } {
      out.println(x - last)
      last = x
    }
    for {
      i <- xs.length until k
    } out.println(0)
    out.close()
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }
}

object CF_525_2_B {
  def solve(n: Int, k: Int, arr: Array[Int]): Vector[Int] = {
    // Going mutable for performance - blech
    if(arr.forall(_ == 0))
      Vector.fill(n)(0)
    else {
      var min = arr.filter(_ > 0).min
      var pass = 0
      var out = Vector.empty[Int]
      while (pass < k) {
        out :+= min
        var newMin = min
        var i = 0
        var allAreZero = true
        while (i < arr.length) {
          if (arr(i) > 0) {
            arr(i) -= min
            if (arr(i) > 0) {
              allAreZero = false
              if (arr(i) < newMin)
                newMin = arr(i)
            }
          }
          i += 1
        }
        if(allAreZero) min = 0 else min = newMin
        pass += 1
      }
      out
    }
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()}.toArray)
    solution foreach println
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    // Just submitting this to test performance
    val out = new java.io.PrintWriter(System.out)
    val xs = SortedSet(as: _*).take(k).toList
    var last = 0
    for {
      x <- xs
    } {
      out.println(x - last)
      last = x
    }
    for {
      i <- xs.length until k
    } out.println(0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    val xs = as.sorted.take(k)
    var last = 0
    for {
      x <- xs
    } {
      println(x - last)
      last = x
    }
    for {
      i <- xs.length until k
    } println(0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }
}

import java.io.PrintWriter
import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Seq[Int] = {
    val xs = SortedSet(as: _*).toStream
    val xs0 = 0 #:: xs
    (xs0, xs).zipped.map((a, b) => b-a).take(k).padTo(k, 0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    val out = new PrintWriter(System.out)
    solution foreach out.println
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

import scala.collection.SortedSet

object CF_525_2_B {

  def solve(n: Int, k: Int, as: Vector[Int]): Unit = {
    // println in the middle of a function makes me feel sick
    val xs = SortedSet(as: _*).take(k).toList
    var last = 0
    for {
      x <- xs
    } {
      println(x - last)
      last = x
    }
    for {
      i <- xs.length to k
    } println(0)
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    solve(int, int, {nextLine; intSeq()})
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}

object CF_525_2_B {
  def solve(n: Int, k: Int, xs: Vector[Int], out: Vector[Int] = Vector.empty): Vector[Int] = k match {
    case 0 => out
    case k => {
      val m = xs.min
      solve(n, k - 1, xs.map(_-m), out :+ m)
    }
  }

  def main(args: Array[String]) = {
    val io = new IO(System.in); import io._
    val solution = solve(int, int, {nextLine; intSeq()})
    solution foreach println
  }

/// boilerplate utility methods: ///
    import java.util.Scanner
    class IO(sc: Scanner) {
      def this(i: java.io.InputStream) = this(new Scanner(i))
      def this(s: String) = this(new Scanner(s))
      def nextLine = sc.nextLine() // do this if still on previous line before collecting line of data
      def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
      def intSeq() = collect(_.toInt)
      def doubleSeq() = collect(_.toDouble)
      def int() = sc.nextInt()
      def long() = sc.nextLong()
      def double() = sc.nextDouble()
    }

    object Utility {
      def intCeil(a: Int, b: Int) = (a - 1) / b + 1
      def longCeil(a: Long, b: Long) = (a - 1) / b + 1
    }
}


import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val ab = readIntLine()
      println(calc(ab.head, ab.last))
    }
  }

  def calc(a: Int, b: Int) = {
    val min = math.min(a, b)
    val max = math.max(a, b)
    val diff = max - min
    val diffMoney = diff
    val rest = min - diff
    if (rest < 0) min else diffMoney + rest / 3 * 2 + (if (rest % 3 == 2) 1 else 0)
  }

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

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

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

}

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

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val ans = a min b min ((a + b) / 3)

    println(ans)
  }
}

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

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val t2 = a min ((2 * b - a) / 3)
    val t1 = (a - t2) / 2

    val ans = t1 + t2

    println(ans)
  }
}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val ab = readIntLine()
      println(calc(ab.head, ab.last))
    }
  }

  def calc(a: Int, b: Int) = {
    val min = math.min(a, b)
    val max = math.max(a, b)
    val diff = max - min
    val diffMoney = diff
    val rest = min - diff
    if (rest < 0) min else diffMoney + rest / 3 * 2
  }

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

//  def printArray[T](arr: Array[T]): Unit = {
//    val str = new StringBuilder()
//    str.addAll((if (arr.head == -1) 0 else arr.head).toString)
//    //    print(arr(0))
//    for (i <- 1 until arr.length) {
//      str.addAll(" " + (if (arr(i) == -1) 0 else arr(i)))
//    }
//    println(str)
//  }

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

}

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

  (0 until t).foreach { _ =>
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
    val t1          = (b - a) min a
    val (a1, b1)    = (a - t1, b - 2 * t1)
    val t2          = 2 * a1 / 3
    val (a2, b2)    = (a1 - t2 / 2 * 3, b1 - t2 / 2 * 3)
    val t3          = a2 min (b2 / 2)

    val ans = t1 + t2 + t3

    println(ans)
  }
}