object C extends App {

  def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

    def search(from: Int, to: Int, f: Int => Boolean): Int = {
      @annotation.tailrec
      def go(left: Int, right: Int): Int =
        if (left + 1 >= right) right
        else {
          val middle = (left + right) >>> 1

          f(middle) match {
            case true  => go(left, middle)
            case false => go(middle, right)
          }
        }
      go(from, to)
    }

    val overall = heroes.sum
    val sorted  = heroes.sorted

    (defense: Long, attack: Long) => {
      val index = search(0, heroes.length - 1, sorted(_) >= defense)

      def coins(index: Int): Long = {
        val hero = sorted(index)
        0L.max(defense - hero) + 0L.max(attack - overall + hero)
      }

      coins(index) min coins(0 max (index - 1))
    }
  }

  import InOut._

  val n  = nextInt()
  val hn = nextLongs(n)

  private lazy val coins = slayTheDragon(hn)

  val m = nextInt()

  (0 until m).foreach { _ =>
    val Array(x, y) = nextLongs(2)

    out.println(coins(x, y))
    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)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.util.Sorting.quickSort
import scala.math._

object test {
    val writer =  new PrintWriter(System.out, false)
    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(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val h = new Array[Long](n)
        for (i <- 0 to n-1)
            h(i) = readLong
        quickSort(h)
        val sum = h.sum
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.math._

object test {
    val writer =  new PrintWriter(System.out, false)
    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(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val h = new Array[Long](n)
        for (i <- 0 to n-1)
            h(i) = readLong
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.math._

object test {
    val writer =  new PrintWriter(System.out, false)
    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(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val ss = reader.readLine()
        var h = ss.split(' ').map(_.toLong)
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.math._

object test {
    val writer =  new PrintWriter(System.out, false)
    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(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val ss = reader.readLine()
        val h = ss.split(' ').map(_.toLong)
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
        }
        writer.flush()
    }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
import scala.math._

object test {
    val writer =  new PrintWriter(System.out, false)
    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(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    def bs(h: Array[Long], value: Long, start: Int, end: Int): Int = {
        //writer.println(start + " " + end)
        val mid = start + (end - start) / 2
        if (end - start < 3) {
            if (h(start) > value)
                return start
            else if (h(end - 1) > value)
                return end-1
            else return end
        }
        if (h(mid) < value)
            return bs(h, value, mid, end)
        else return bs(h, value, start, mid + 1)
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val ss = reader.readLine()
        val h = ss.split(' ').map(_.toLong)
        val sum = h.sum
        var i = 0
        for (k <- h.sorted){
            h(i) = k
            i += 1
        }
        val t = readInt()
        for (tt <- 1 to t) {
            val x = readLong()
            val y = readLong()
            var ind = bs(h, x, 0, n) - 1
            if (ind < 0)
                ind = 0
            var ans = max (0L, y-(sum-h(ind))) + max (0L, x - h(ind))
            if (ind < n-1)
                ans = min(ans, max (0L, y-(sum-h(ind+1))))
            writer.println(ans)
            writer.flush()
        }
        writer.flush()
    }
}

object what extends App{
    def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

        def search(from: Int, to: Int, f: Int => Boolean): Int = {
            @annotation.tailrec
            def go(left: Int, right: Int): Int =
                if (left + 1 >= right) right
                else {
                    val middle = (left + right) >>> 1

                    f(middle) match {
                        case true  => go(left, middle)
                        case false => go(middle, right)
                    }
                }
            go(from, to)
        }

        val overall = heroes.sum
        val sorted  = heroes.sorted

        (defense: Long, attack: Long) => {
            val index = search(0, heroes.length - 1, sorted(_) >= defense)

            def coins(index: Int): Long = {
                val hero = sorted(index)
                0L.max(defense - hero) + 0L.max(attack - overall + hero)
            }

            coins(index) min coins(0 max (index - 1))
        }
    }

    import InOut._

    val n  = nextInt()
    val hn = nextLongs(n)

    private lazy val coins = slayTheDragon(hn)

    val m = nextInt()

    (0 until m).foreach { _ =>
        val Array(x, y) = nextLongs(2)

        out.println(coins(x, y))

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

        def nextInt()        = Integer.parseInt(nextToken())
        def nextInts(n: Int) = Array.fill(n)(nextInt())

        def nextLong()        = java.lang.Long.parseLong(nextToken())
        def nextLongs(n: Int) = Array.fill(n)(nextLong())

        def nextBig()        = BigInt(nextToken())
        def nextBigs(n: Int) = Array.fill(n)(nextBig())

        def nextLine() = in.readLine()

        private[this] var tokenizer: java.util.StringTokenizer = _

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

}

object what extends App{
    def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

        def search(from: Int, to: Int, f: Int => Boolean): Int = {
            @annotation.tailrec
            def go(left: Int, right: Int): Int =
                if (left + 1 >= right) right
                else {
                    val middle = (left + right) >>> 1

                    f(middle) match {
                        case true  => go(left, middle)
                        case false => go(middle, right)
                    }
                }
            go(from, to)
        }

        val overall = heroes.sum
        val sorted  = heroes.sorted

        (defense: Long, attack: Long) => {
            val index = search(0, heroes.length - 1, sorted(_) >= defense)

            def coins(index: Int): Long = {
                val hero = sorted(index)
                0L.max(defense - hero) + 0L.max(attack - overall + hero)
            }

            coins(index) min coins(0 max (index - 1))
        }
    }

    import InOut._

    val n  = nextInt()
    val hn = nextLongs(n)

    private lazy val coins = slayTheDragon(hn)

    val m = nextInt()

    (0 until m).foreach { _ =>
        val Array(x, y) = nextLongs(2)

        out.println(coins(x, y))
        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)

        def nextInt()        = Integer.parseInt(nextToken())
        def nextInts(n: Int) = Array.fill(n)(nextInt())

        def nextLong()        = java.lang.Long.parseLong(nextToken())
        def nextLongs(n: Int) = Array.fill(n)(nextLong())

        def nextBig()        = BigInt(nextToken())
        def nextBigs(n: Int) = Array.fill(n)(nextBig())

        def nextLine() = in.readLine()

        private[this] var tokenizer: java.util.StringTokenizer = _

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

}

object C extends App {

  def slayTheDragon(heroes: IndexedSeq[Long]): (Long, Long) => Long = {

    def search(from: Int, to: Int, f: Int => Boolean): Int = {
      @annotation.tailrec
      def go(left: Int, right: Int): Int =
        if (left + 1 >= right) right
        else {
          val middle = (left + right) >>> 1

          f(middle) match {
            case true  => go(left, middle)
            case false => go(middle, right)
          }
        }
      go(from, to)
    }

    val heroesSorted  = heroes.sorted
    val heroesOverall = heroes.sum

    (dragonDefense: Long, dragonAttack: Long) => {
      val index = search(0, heroes.length - 1, heroesSorted(_) >= dragonDefense)

      def coins(index: Int): Long = {
        val hero = heroesSorted(index)
        0L.max(dragonDefense - hero) + 0L.max(dragonAttack - heroesOverall + hero)
      }

      coins(index) min coins(0 max (index - 1))
    }
  }

  import InOut._

  val n  = nextInt()
  val hn = nextLongs(n)

  lazy val coins = slayTheDragon(hn)

  val m = nextInt()

  (0 until m).foreach { _ =>
    val Array(x, y) = nextLongs(2)

    out.println(coins(x, y))
  }
  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)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

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 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 main(args: Array[String]) {
        var t = 1 //readInt()
        while (t > 0) {
            t -= 1
            val n = readInt()
            val a = new Array[Long](n)
            for (i <- 0 until n) a(i) = readLong()

            quickSort(a)
            val sum = a.sum

            val m = readInt()
            for (i <- 0 until m) {
                val x = readLong()
                val y = readLong() - sum

                if (y >= x) {
                    writer.println(Math.max(0, x - a(0)) + Math.max(0, y + a(0)))
                } else {
                    val avg = (x - y) / 2
                    var l = 0
                    var r = n - 1
                    var min = -1L
                    while (l <= r) {
                        val mid = (l + r) / 2
                        if (a(mid) > avg) r = mid - 1
                        else {
                            min = a(mid)
                            l = mid + 1
                        }
                    }

                    l = 0
                    r = n - 1
                    var max = -1L
                    while (l <= r) {
                        val mid = (l + r) / 2
                        if (a(mid) >= avg) {
                            r = mid - 1
                            max = a(mid)
                        } else l = mid + 1
                    }

                    val rsmin = if (min != -1) Math.max(0, x - min) + Math.max(0, y + min) else Long.MaxValue
                    val rsmax = if (max != -1) Math.max(0, x - max) + Math.max(0, y + max) else Long.MaxValue

                    writer.println(Math.min(rsmin, rsmax))
                }

            }
        }
        writer.close()
    }
}


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 nx = readIntLine()
      val arr = readIntLine().toArray
      println(findLongest(arr, nx.last))
    }
  }

  def findLongest(arr: Array[Int], x: Int): Int = {
    if (arr.forall(_ % x == 0)) return -1

    if (arr.sum % x != 0) return arr.length

    for (i <- arr.indices) {
      if (arr(i) % x != 0 || arr(arr.length - 1 - i) % x != 0)
        return arr.length - i - 1
    }

    -1
  }

  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 {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextInts(n)
      var l = 0
      while (l < n && as(l) % x == 0) {
        l += 1
      }

      var r = n - 1
      while (r >= 0 && as(r) % x == 0) {
        r -= 1
      }

      var res = -1
      val sum = as.sum
      if (sum % x != 0) {
        res = n
      } else if (l <= r) {
        val rr = r
        val ll = n - l - 1
        res = ll max rr
        //println(l, r, ll, rr)
      }
      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 nx = readIntLine()
      val arr = readIntLine().toArray
      println(findLongest(arr, nx.last))
    }
  }

  def findLongest(arr: Array[Int], x: Int): Int = {
    if (arr.forall(_ % x == 0)) return -1

    if (arr.sum % x != 0) return arr.length

    for (i <- arr.indices) {
      if (arr(i) % x != 0 || arr(arr.length - 1 - i) != 0)
        return arr.length - i - 1
    }

    -1
  }

  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 {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextInts(n)
      var l = 0
      while (l < n && as(l) % x == 0) {
        l += 1
      }

      var r = n - 1
      while (r >= 0 && as(r) % x == 0) {
        r -= 1
      }

      var res = -1
      val sum = as.sum
      if (sum % x != 0) {
        res = n
      } else {
        val rr = r - 1
        val ll = n - l - 1
        res = ll max rr
        //println(l, r, ll, rr)
      }
      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
  }
}

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

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextInts(n)
      var l = 0
      while (l < n && as(l) % x == 0) {
        l += 1
      }

      var r = n - 1
      while (r >= 0 && as(r) % x == 0) {
        r -= 1
      }

      var res = -1
      val sum = as.sum
      if (sum % x != 0) {
        res = n
      } else if (l < r) {
        val rr = r - 1
        val ll = n - l - 1
        res = ll max rr
        //println(l, r, ll, rr)
      }
      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 java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    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(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Long](n+1)
        var cnt = 0
        var sum = 0L
        var mx = 1L
        for (i <- 1 to n) {
            arr(i) = readLong()
            while(arr(i) % 2 == 0) {
                cnt += 1
                arr(i) /= 2L
            }
            sum += arr(i)
            mx = max(mx, arr(i))
        }
        sum -= mx
        for (i <- 1 to cnt) {
            mx *= 2L
        }
        sum += mx
        writer.println(sum)

        def check(kk: Int): Boolean = {
            return true
        }
        def bs(st:Int, en:Int): Int = {
            if (en - st <= 1) {
                if (check(en))
                    return en
                else
                    return st
            }
            val mid = (st + en) / 2
            if (check(mid))
                return bs(mid, en)
            else
                return bs(st, mid)
        }
    }
    writer.flush()
}

import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._
import scala.io.StdIn

object Main extends App {
  val t = StdIn.readInt()
  (0 until t).foreach { _ =>
    val n = StdIn.readInt()
    val arr = StdIn.readLine().split(" ").map(i => BigInt(i.toInt))
    var num:BigInt  = 1
    var mx:BigInt = 0
    var mxidx = 0
    (0 until n).foreach { i =>
      while (arr(i) % 2 == 0) {
        arr(i) /= 2
        num *= 2
      }
      if (arr(i) > mx) {
        mx = arr(i)
        mxidx = i
      }
    }
    arr(mxidx) *= num
    println(arr.sum)
  }
}


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

  val mod = (1e9 + 7).toInt

  val fib = {
    val n = 1e5.toInt
    val f = Array.ofDim[Int](n + 1)
    f.indices foreach {
      case i if i <= 1 => f(i) = i
      case i => f(i) = (f(i-1) + f(i-2)) % mod
    }
    f
  }

  override def apply(implicit io: IO): io.type = {
    val msg = io.read[String]
    val ans = splitRepeating(msg) map { token =>
      token(0) match {
        case 'u' | 'n' => fib(token.length + 1)
        case 'w' | 'm' => 0
        case _ => 1
      }
    }
    io.writeLine(ans.foldLeft(BigInt(1)) {case (i, j) => (i * j).mod(mod)})
  }

  def splitRepeating(s: String): Seq[String] = s.split("(?<=(.))(?!\\1)")

}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(implicit io: IO): io.type
  def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

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

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

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

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  case class Len(len: Int, c: Char)

// nCk % MOD を求める。下準備で階乗Fと≡MODでの階乗の逆元Iを作る
class Comb(N: Int, MOD: Int) {
  def powMod(x: Int, n: Int, m: Int): Int = {
    def step(x: Long, n: Int, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1).toInt
  }

  private[this] val F = Array.ofDim[Long](N + 1)
  F(0) = 1
  REP(N) { i =>
    F(i + 1) = F(i) * (i + 1) % MOD
  }
  private[this] val I = Array.ofDim[Long](F.length)
  I(N) = powMod(F(N).toInt, MOD - 2, MOD)

  // x! = x(x-1)!
  // x!I(x!) ≡ (x-1)!I((x-1)!)
  // I((x-1)!) ≡ I(x!) * x   MODがでかいので(x-1)!はMODと素
  REP_r(N) { i =>
    I(i) = I(i + 1) * (i + 1) % MOD
  }

  def comb(n: Int, k: Int): Long = {
    if (n < k) 0
    else F(n) * I(n - k) % MOD * I(k) % MOD
  }

  def rev(x: Int): Long = {
    I(x) * F(x - 1) % MOD
  }

  /**
    * nのグループからk回重複ありで選ぶ組み合わせ数
    * n - 1のしきりとkの○で考える
    */
  def H(n: Int, k: Int): Long = {
    comb(n + k - 1, k)
  }

  /**
    * private[this]をつかってるのでgetterが必要
    * @return (F, I)
    */
  def get: (Array[Long], Array[Long]) = (F, I)
}
}

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 = {
    val s = ns()
    val n = s.length
    if (s.contains('m') || s.contains('w')) {
      out.println(0)
      return
    }

    val L = ArrayBuffer[Len]()
    var cnt = 0
    REP(n) { i =>
      if (i > 0 && s(i) != s(i - 1)) {
        L += Len(cnt, s(i - 1))
      }
      if (i == 0 || s(i) != s(i - 1)) cnt = 1
      else cnt += 1
    }
    L += Len(cnt, s(n - 1))

    debug(L.mkString)

    var ans = 1L
    val comb = new Comb(n, MOD)
    def calc(x: Int): Long = {
      debug(s"calc($x)")
      var res = 0L
      var a = x
      var b = 0
      while (a >= 0) {
        res += comb.comb(a + b, a) % MOD
        a -= 2
        b += 1
      }
      res % MOD
    }

    for {
      l <- L
      if l.c == 'u' || l.c == 'n'
    } {
      ans = ans * calc(l.len) % MOD
    }
    out.println(ans)
  }
}


object B extends App {
  val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val x = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val y = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  var i = 0
  var j = 0
  var p = 0
  var q = 0
  var c = 1
  while (i < n && j < m) {
    if (p != 0 && q != 0 && p == q) {
      c += 1
      p = 0
      q = 0
    }
    if (p > q) {
      q += y(j)
      j += 1
    } else if (q > p) {
      p += x(i)
      i += 1
    } else {
      p += x(i)
      i += 1
      q += y(j)
      j += 1
    }
  }

  println(c)
}

import scala.io.StdIn

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

    val (n, m) = StdIn.readLine.split(" ").map(_.toInt) match {
      case xy: Array[Int] => (xy(0), xy(1))
    }

    val x = StdIn.readLine.split(" ").map(_.toInt)
    val y = StdIn.readLine.split(" ").map(_.toInt)

    var z = 0
    val xc = x.map(a => {
      z += a
      z
    })

    z = 0
    val yc = y.map(a => {
      z += a
      z
    })

    var ans = 0

    var (i, j) = (0, 0)
    while (i < n && j < m) {
      val small = Math.min(xc(i), yc(j))

      if (xc(i) == yc(j)) ans += 1
      if (xc(i) == small) i += 1
      else j += 1
    }

    println(ans)
  }
}

import scala.io.StdIn._
object B950 {
  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val b = readLine().split(" ").map(_.toInt)
    var left = 0
    var right = 0
    var aSum = -1
    var bSum = -1
    var res = 0
    while (!(left >= n && right >= m)) {
      if (aSum != -1 && aSum == bSum) {
        res += 1
        aSum = -1
        bSum = -1
      } else if (aSum == -1) {
        aSum = if (left < n) a(left) else 0
        left += 1
        bSum = if (right < m) b(right) else 0
        right += 1
      } else if (aSum < bSum) {
        aSum += (if (left < n) a(left) else 0)
        left += 1
      } else {
        bSum += (if (right < m) b(right) else 0)
        right += 1
      }
    }
    if (aSum != -1 && aSum == bSum) res += 1
    println(res)
  }
}

object bTask2 {
  import scala.io.StdIn.{readLine, readInt}

  def message(n: Int, m: Int, xs: List[Int], ys: List[Int]):Int = {

    def helper(xx: List[Int], yy: List[Int], ax: Int, ay: Int, num: Int):Int = {
      (xx, yy) match {
        case (Nil,_)|(_,Nil) => num
        case (l@(x::xss), y::yss) if ax > ay => helper(l, yss, ax, ay + y, num)
        case (x::xss, r@(y::yss)) if ax < ay => helper(xss, r, ax + x, ay, num)
        case (x::xss, y::yss) if ax == ay => helper(xss, yss, x, y, num + 1)
      }
    }
    helper(xs, ys, 0,0,0)
  }

  def main(args: Array[String]):Unit = {
    val n::m::Nil = readLine.split(" ").map(_.toInt).toList
    val xs = readLine.split(" ").map(_.toInt).toList
    val ys = readLine.split(" ").map(_.toInt).toList
    println(message(n,m,xs,ys))
  }
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n, m = sc.nextInt
    val xs = prefixSum(List.fill(n)(sc.nextInt))
    val ys = prefixSum(List.fill(m)(sc.nextInt))

    println(xs.foldLeft((ys, 0)) {
      case ((zs, res), x) =>
        zs.span(_ < x)._2 match {
          case (z :: zs) if z == x => (zs, res + 1)
          case zs => (zs, res)
        }
    }._2 - 1)
  }

  def prefixSum(as: List[Int]) = as.scanLeft(0){ case (acc, a) => a + acc }
}

object Solution {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n, m = sc.nextInt
    val xs = prefixSum(List.fill(n)(sc.nextInt))
    val ys = prefixSum(List.fill(m)(sc.nextInt))

    println(xs.foldLeft((ys, 0)) {
      case ((Nil, res), _) => (Nil, res)
      case ((z :: zs, res), x) => if (x == z) (zs, res + 1) else ((z :: zs).dropWhile(_ < x), res)
    }._2)
  }

  def prefixSum(as: List[Int]) = as.scanLeft(0){ case (acc, a) => a + acc }
}


import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    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(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        var a = n
        var b = m
        if (m > n) {
            a = m
            b = n
        }
        var ans = 0
        ans = (a / 3).toInt * b
        a = a % 3
        ans += (b / 3).toInt * a
        b = b % 3
        if (a == 2 && b == 2)
            ans += 2
        else if (a != 0 && b != 0)
            ans += 1
        writer.println(ans)
    }
    writer.flush()
}

import scala.io.Source

object Main extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  Range(0, t).map(_ => input.next().split(" "))
    .map(x => (x(0).toInt, x(1).toInt))
    .foreach(nm => {
      val (n, m) = nm
      val c3 = if (n * m % 3 == 1) (n * m) / 3 - 1 else (n * m) / 3
      val c2 = (n * m - c3 * 3) / 2
      println(c3 + c2)
    })
}


import scala.io.StdIn._

object Main2 extends App {
  val boyNumber = readInt()
  val boySkills = readLine().split(" ").map(_.toInt).sorted
  val girlNumber = readInt()
  val girlSkills = readLine().split(" ").map(_.toInt).sorted
  var boyIndex: Int = 0
  var girlIndex: Int = 0
  var ans = 0
  while(boyIndex < boyNumber && girlIndex < girlNumber) {
    val difference = boySkills(boyIndex) - girlSkills(girlIndex)
    difference match {
      case d if Math.abs(d) < 2 =>
        boyIndex += 1
        girlIndex += 1
        ans += 1
      case d if d < 0 => boyIndex += 1
      case d if d > 0 => girlIndex += 1
    }
  }
  println(ans)
}

object B {

  def main(args: Array[String]): Unit = {
    readInt()
    val a = readLine().split(" ").toList.map(_.toInt).sorted
    readInt()
    val b = readLine().split(" ").toList.map(_.toInt).sorted
    println(dancing(a, b, Map())._1)
  }

  type Memo = Map[(Int, Int), Int]

  def dancing(a: List[Int], b: List[Int], memo: Memo): (Int, Memo) = (a, b) match {
    case (Nil, _) => (0, memo)
    case (_, Nil) => (0, memo)
    case (x :: xs, y :: ys) =>
      if (memo.contains((a.length, b.length))) {
        (memo.get((a.length, b.length)).get, memo)
      } else if (math.abs(x - y) <= 1) {
        val z = dancing(xs, ys, memo)
        (z._1 + 1, z._2 + ((a.length, b.length) -> (z._1 + 1)))
      } else {
        val z1 = dancing(a, ys, memo)
        val z2 = dancing(xs, b, z1._2)
        val res = math.max(z1._1, z2._1)
        (res, z2._2 + ((a.length, b.length) -> res))
      }
  }
}

object Solution {

  import scala.math._

  def main(args: Array[String]) {

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

    val n = sc.nextInt()
    val boys = Array.fill(n)(sc.nextInt()).sorted

    val m = sc.nextInt()
    val girls = Array.fill(m)(sc.nextInt()).sorted

    val dp = Array.fill(n)(Array.fill(m)(0))

    dp(0)(0) = if(abs(boys(0)-girls(0))<2) 1 else 0

    for (i <- (1 until m)) {
      if (dp(0)(i-1) == 1) dp(0)(i) = 1
      else if (abs(boys(0)-girls(i)) < 2) dp(0)(i) = 1
    }
    for (i <- (1 until n)) {
      if (dp(i-1)(0) == 1) dp(i)(0) = 1
      else if (abs(boys(i)-girls(0)) < 2) dp(i)(0) = 1
    }

    for (i <- (1 until n)) {
      for (j <- (1 until m)) {
        if (abs(boys(i)-girls(j)) < 2)
          dp(i)(j) = List(dp(i-1)(j-1)+1, dp(i-1)(j), dp(i)(j-1)).max
        else
          dp(i)(j) = max(dp(i-1)(j), dp(i)(j-1))
      }
    }

    println(dp(n-1)(m-1))
  }
}

object SB_2 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    var arr1:Array[Int]=new Array[Int](n)

    val l1=readLine()
    val line1:Array[String]=l1.split(" ")
    for(i<-0 until arr1.length)
      arr1(i)=line1(i).toInt
    arr1=arr1.sortBy(x=>x)

    val m:Int=readInt()
    var arr2:Array[Int]=new Array[Int](m)

    val l2=readLine()
    val line2:Array[String]=l2.split(" ")
    for(i<-0 until arr2.length)
      arr2(i)=line2(i).toInt
    arr2=arr2.sortBy(x=>x)

    var i:Int=0
    var j:Int=0
    var flagi:Boolean=true
    var flagj:Boolean=true
    var sum:Int=0

    while(flagi&&flagj){
      while(flagj&&flagi){
        if(Math.abs(arr1(i)-arr2(j))<=1){
          i=i+1
          j=j+1
          sum=sum+1

          if(i>=arr1.length)
            flagi=false
          if(j>=arr2.length)
            flagj=false
        }
        else{
          if(arr1(i)>arr2(j))
            j=j+1
          else
            i=i+1

          if(i>=arr1.length)
            flagi=false
          if(j>=arr2.length)
            flagj=false
        }

        if(i>=arr1.length)
          flagi=false
        if(j>=arr2.length)
          flagj=false
      }
    }

    println(sum)

  }

}

object SB_2 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    var arr1:Array[Int]=new Array[Int](n)

    val l1=readLine()
    val line1:Array[String]=l1.split(" ")
    for(i<-0 until arr1.length)
      arr1(i)=line1(i).toInt
    arr1=arr1.sortBy(x=>x)

    val m:Int=readInt()
    var arr2:Array[Int]=new Array[Int](m)

    val l2=readLine()
    val line2:Array[String]=l2.split(" ")
    for(i<-0 until arr2.length)
      arr2(i)=line2(i).toInt
    arr2=arr2.sortBy(x=>x)

    var i:Int=0
    var j:Int=0
    var flagi:Boolean=true
    var flagj:Boolean=true
    var sum:Int=0

    while(flagi&&flagj){
      while(flagj&&flagi){
        if(Math.abs(arr1(i)-arr2(j))<=1){
          i=i+1
          j=j+1
          sum=sum+1
        }
        else{
          if(arr1(i)>arr2(j))
            j=j+1
          else
            i=i+1
        }

        if(i>=arr1.length)
          flagi=false
        if(j>=arr2.length)
          flagj=false
      }
    }

    println(sum)

  }

}

object B489 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val boys = readInts(n).sortBy(identity)
    val Array(m) = readInts(1)
    val girls = readInts(m).sortBy(identity)

    var res = 0
    var j = 0
    var lastj = 0
    for(i <- boys.indices) {
      var break = false
      while(!break && j < girls.length && girls(j) <= boys(i)+1) {
        if(math.abs(boys(i) - girls(j)) <= 1) {
          res += 1
          lastj = j
          break = true
        }
        j += 1
      }
      if(break) j = lastj+1
    }

    println(res)
  }
}

/**
  * Created by yousack on 2017/03/01.
  */

import scala.io.StdIn.readLine

object App {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    var a = readLine().split(" ").map(_.toInt).sorted
    val m = readLine().toInt
    var b = readLine().split(" ").map(_.toInt).sorted
    var ans = 0

    while (!a.isEmpty && !b.isEmpty) {
      if (math.abs(a{0} - b{0}) <= 1) {
        ans += 1
        a = a.drop(1)
        b = b.drop(1)
      } else if (a{0} < b{0}) {
        a = a.drop(1)
      } else {
        b = b.drop(1)
      }
    }

    print(ans)
  }
}

/**
  * Created by yousack on 2017/03/01.
  */

import scala.io.StdIn.readLine

object App {
  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    val a = readLine().split(" ").map(_.toInt).sorted
    val m = readLine().toInt
    val b = readLine().split(" ").map(_.toInt).sorted

    print(solve(a, b, 0))
  }

  def solve(a: Array[Int], b: Array[Int], p: Int): Int = {
    if (a.isEmpty || b.isEmpty) {
      return p
    }

    if (math.abs(a{0} - b{0}) <= 1) {
      solve(a.drop(1), b.drop(1), p + 1)
    } else if (a{0} < b{0}) {
      solve(a.drop(1), b, p)
    } else {
      solve(a, b.drop(1), p)
    }
  }
}

object B489 {
  @inline def read = scala.io.StdIn.readLine

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val boys = readInts(n).sortBy(identity)
    val Array(m) = readInts(1)
    val girls = readInts(m).sortBy(identity)

    var res = 0
    var j = 0
    var lastj = 0
    for(i <- boys.indices) {
      var break = false
      while(!break && j < girls.length && girls(j) <= boys(i)+1) {
        if(math.abs(boys(i) - girls(j)) <= 1) {
          res += 1
          lastj = j
          break = true
        }
        j += 1
      }
      j = lastj+1
    }

    println(res)
  }
}

object B {

  def main(args: Array[String]): Unit = {
    readInt()
    val a = readLine().split(" ").toList.map(_.toInt).sorted
    readInt()
    val b = readLine().split(" ").toList.map(_.toInt).sorted
    println(dancing(a, b, Map())._1)
  }

  type Memo = Map[(Int, Int), Int]

  def dancing(a: List[Int], b: List[Int], memo: Memo): (Int, Memo) = (a, b) match {
    case (Nil, _) => (0, memo)
    case (_, Nil) => (0, memo)
    case (x :: xs, y :: ys) =>
      if (memo.contains((x, y))) {
        (memo.get((x, y)).get, memo)
      } else if (math.abs(x - y) <= 1) {
        val z = dancing(xs, ys, memo)
        (z._1 + 1, z._2 + ((x, y) -> (z._1 + 1)))
      } else {
        val z1 = dancing(a, ys, memo)
        val z2 = dancing(xs, b, z1._2)
        val res = math.max(z1._1, z2._1)
        (res, z2._2 + ((x, y) -> res))
      }
  }
}


import scala.io.StdIn

object Test extends App {

  def find(packages: List[Int],and: Map[Int,Int],gr: Map[Int,Int],index: Int): Map[Int,Int ] = {
    val sum1 = and.values.sum
    val sum2 = gr.values.sum
    if (packages.isEmpty && sum1 != sum2 && sum1 != 0 && sum2 != 0) gr
    else
      {
        if (packages.nonEmpty) {
          val current = packages.head
          val a1 = find(packages.tail, and.updated(index, current), gr, index + 1)
          if (a1.nonEmpty) a1
          else {
            find(packages.tail, and, gr.updated(index, current), index + 1)
          }
        }else Map.empty
      }
  }

  val n = StdIn.readLine().trim.toInt
  val s = StdIn.readLine().split(" ").map(_.toInt).toList

  val gr = find(s,Map.empty,Map.empty,0)
  if (gr.isEmpty)
    {
      println(-1)
    }else
    {
      println(gr.size)
      gr.keys.map(_ + 1).foreach(el => print(s"$el "))
    }
}

object Main{
  def main(args: Array[String]) {
    val n = readInt()
    if(n == 1){
      println(-1)
      return;
    }
    val a = readLine().split(" ").map(_.toInt)

    var minIndex = -1
    var minValue = Long.MaxValue
    var sum: Long = 0L
    for(i <- 0 to (a.length - 1)){
      if(a(i) < minValue){
        minValue = a(i)
        minIndex = i
      }
      sum += a(i)
    }

    if(sum - minValue == minValue){
      println(-1)
      return;
    }

    println(1)
    println(minIndex + 1)

  }
}

object Main{
  def main(args: Array[String]) {
    val n = readInt()
    if(n == 1){
      println(-1)
      return;
    }
    val a = readLine().split(" ").map(_.toInt)

    var minIndex = -1
    var minValue = Long.MaxValue
    var sum: Long = 0L
    for(i <- 0 to (a.length - 1)){
      if(a(i) < minValue){
        minValue = a(i)
        minIndex = i
      }
      sum += a(i)
    }

    if(sum - minValue == minValue){
      println(-1)
      return;
    }

    println(1)
    println(minIndex)

  }
}

object Main{
  def main(args: Array[String]) {
    val n = readInt()
    if(n == 1){
      println(-1)
      return;
    }
    val a = readLine().split(" ").map(_.toInt)

    var minIndex = -1
    var minValue = Long.MaxValue
    var sum: Long = 0L
    for(i <- 0 to (a.length - 1)){
      if(a(i) < minValue){
        minValue = a(i)
        minIndex = i
      }
      sum += a(i)
    }

    if(sum - minValue == minValue){
      println(-1)
      return;
    }

    println(1)
    println(minValue)

  }
}


/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.mutable

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def solve(): Unit = {
    val (r, s, p) = (nextInt, nextInt, nextInt)
    val dp = Array.ofDim[Double](r + 1, s + 1, p + 1)
    dp(r)(s)(p) = 1.0
    for (i <- (0 to r).reverse) {
      for (j <- (0 to s).reverse) {
        for (k <- (0 to p).reverse) {
          val total = i * j + j * k + i * k
          if (i > 0 && j > 0) {
            dp(i)(j - 1)(k) += dp(i)(j)(k) * (i * j) / total
          }
          if (j > 0 && k > 0) {
            dp(i)(j)(k - 1) += dp(i)(j)(k) * (j * k) / total
          }
          if (i > 0 && k > 0) {
            dp(i - 1)(j)(k) += dp(i)(j)(k) * (i * k) / total
          }
        }
      }
    }
    var (ans_r, ans_s, ans_p) = (0.0, 0.0, 0.0)
    for (i <- 1 to r) ans_r += dp(i)(0)(0)
    for (j <- 1 to s) ans_s += dp(0)(j)(0)
    for (k <- 1 to p) ans_p += dp(0)(0)(k)
    out.println(f"$ans_r%.12f $ans_s%.12f $ans_p%.12f")
  }

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

object main{
  object Solver extends InputReader{
    val dp = Array.ofDim[Array[Double]](128, 128, 128)

    def merge(rate: Double, dst: Array[Double], src: Array[Double]){
      for(i <- 0 to dst.length - 1)
        dst(i) += rate * src(i)
    }

    def dfs(r: Int, s: Int, p: Int): Array[Double] = {
      if(dp(r)(s)(p) != null) return dp(r)(s)(p)
      val ret = new Array[Double](3)

      if(r == 0){
        ret(1) = 1
      }else if(s == 0){
        ret(2) = 1
      }else if(p == 0){
        ret(0) = 1
      }else{
        val all = r + s + p
        val b: Double = all * (all - 1) / 2

        merge((r * s) / b, ret, dfs(r, s - 1, p))
        merge((s * p) / b, ret, dfs(r, s, p - 1))
        merge((p * r) / b, ret, dfs(r - 1, s, p))

        val sum = ret.sum
        for(i <- 0 to ret.length - 1)
          ret(i) /= sum
      }

      dp(r)(s)(p) = ret
      return ret
    }

    def solve(){
      val r = getInt()
      val s = getInt()
      val p = getInt()

      for(a <- dfs(r, s, p))
        printf("%.12f ", a)
      println()
    }
  }

  // TEMPLATE ------------------------

  def main(args: Array[String]){
    Solver.solve()
  }

  trait InputReader{
    import java.io._
    import java.util._
    protected val stream = System.in
    private val reader = new BufferedReader(new InputStreamReader(stream))
    private var tokenizer = new StringTokenizer(reader.readLine())

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

    def getInt(): Int = getStr().toInt
    def getLong(): Long = getStr().toLong
    def getDouble(): Double = getStr().toDouble
  }
}

import annotation.tailrec

object main extends App with fastIO {

  val Array(a, b, c) = readLine split(" ") map(_.toInt)
  var dp = Array.fill[Double](101, 101, 101)(-1)

  def sum1n(n: Int) = n * (n - 1) >> 1

  def dfs(a: Int, b: Int, c: Int): Double = {
    if (a == 0) return 0
    if (b + c == 0) return 1

    if (dp(a)(b)(c) > -1e-10) return dp(a)(b)(c)
    var value: Double = 0

    var cnt: Double = sum1n(a + b + c)
    var q: Double = (sum1n(a) + sum1n(b) + sum1n(c)) / cnt

    if (a > 0) value += dfs(a - 1, b, c) * (a * c) / cnt
    if (b > 0) value += dfs(a, b - 1, c) * (b * a) / cnt
    if (c > 0) value += dfs(a, b, c - 1) * (c * b) / cnt

    value *= 1 / (1 - q)

    dp(a)(b)(c) = value
    value
  }

  println("%.10f %.10f %.10f" format(dfs(a, b, c), dfs(b, c, a), dfs(c, a, b)) replace(",","."))
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}


object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val t = stdin.next().toInt
  val res = stdin.take(t * 2).map(_.split(" ").map(_.toInt)).grouped(2).map {
    arr =>
      val Array(n, p, k) = arr.head
      val x = arr(1).sorted
      solve(x, p, k)
  }

  println(res.mkString("\n"))

  def solve(x: Array[Int], p: Int, k: Int) = {
    var startIndex = 0
    var endIndex = k
    val sum = x.scanLeft(0) {case(acc, el) => acc + el}.tail
    var currentVal = sol(x, p, k, k - 1)
//    println(currentVal)
    while (startIndex + 1 < endIndex) {
      val mid = (startIndex + endIndex) / 2
//      println("mid " + mid)
      val tr = if (mid == 0 || sum(mid - 1) > p) 0 else mid + sol(x, p - sum(mid - 1), k, mid + k - 1)
      if (tr > currentVal) {
        currentVal = tr
        startIndex = mid
      }
      else {
        endIndex = mid
      }
    }
    currentVal
  }

  def sol(x: Array[Int], p: Int, k: Int, tryIndex: Int): Int = {
    if (tryIndex >= x.length) Math.max(0, (tryIndex - k + 1) / k * k)
    else if (x(tryIndex) > p) Math.max(0, (tryIndex - k + 1) / k * k)
    else sol(x, p - x(tryIndex), k, tryIndex + k)
  }

}

// 5 11 2
// 2 3 4 5 7

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("MY_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = {
    if (!oj){ System.err.println(s) }
  }
  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 = _

    private[this] 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._
  import java.util.Arrays.sort

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

  def upperBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) > x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, P, K = ni()
      val A = na(N)
      sort(A)
      val S = Array.ofDim[Long](N + 1)
      REP(N) { i =>
        if (i + 1 >= K) {
          S(i + 1) = S(i + 1 - K) + A(i)
        }
      }
      debug(S)
      val cum = Array.ofDim[Long](K - 1)
      cum(0) = A(0)
      REP(K - 2, 1) { i =>
        cum(i) = cum(i - 1) + A(i)
      }
      debug(cum)

      var ans = 0
      REP(N) { i =>
         if (S(i + 1) <= P) {
           val remain = P - S(i + 1)
           val c1 = (i + 1) / K * K
           val c2 = upperBound(cum, remain)
           val c = c1 + min(c2, i + 1 - c1)
           ans = max(ans, c)
         }
      }
      out.println(ans)
    }
  }
}

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("MY_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = {
    if (!oj){ System.err.println(s) }
  }
  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 = _

    private[this] 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._
  import java.util.Arrays.sort

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N, P, K = ni()
      val A = na(N)
      sort(A)
      val S = Array.ofDim[Long](N)
      REP(N) { i =>
        if (i - K >= 0) {
          S(i) = A(i) + S(i - K)
        } else {
          S(i) = A(i)
        }
      }
      debug(S)
      var ans = 0
      REP(N) { i =>
        if (S(i) <= P) {
          val v = if (i + 1 >= K) i + 1 else 1
          ans = max(ans, v)
        }
      }
      out.println(ans)
    }
  }
}


import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))
    lazy val input = getFreq(readLine)
    println(getFreq("Bulbasaur").map(p => input.getOrElse(p._1, 0) / p._2).min)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val str2 = in.next().toCharArray
  val answer = str2.filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.toList.sorted

  if (str.forall(str2.contains))
    println(answer.headOption.getOrElse(0))
  else
    println(0)

}

object GottaCatchEmAll extends App{
  val textCount = io.StdIn.readLine().groupBy(_.toChar).mapValues(_.length)
  val bulbasaur = "Bulbasaur".groupBy(_.toChar).mapValues(_.length)
  val ans = bulbasaur.collect{ case (k, v) => textCount.getOrElse(k, 0) / v }.min
  println(ans)
}

object A757 {

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

  def main(args: Array[String]): Unit = {
    val in = read
    val map = collection.mutable.Map.empty[Char, Int].withDefaultValue(0)
    in.foreach{char => map(char) += 1}

    var res = Array(map('B'), map('u')/2, map('l'), map('b'), map('a')/2, map('s'), map('r')).min//"Bulbasaur"
    println(res)
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @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 scala.io.StdIn._

object Main extends App {
  val A = readLine()

  val G = A.groupBy(identity).mapValues(_.length)
  val min = Array(
    G.getOrElse('B', 0),
    G.getOrElse('u', 0) / 2,
    G.getOrElse('l', 0),
    G.getOrElse('b', 0),
    G.getOrElse('a', 0) / 2,
    G.getOrElse('s', 0),
    G.getOrElse('r', 0)).min

  println(min)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val answer = in.next().filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.toList.sorted

  if (str.forall(answer.contains))
    println(answer.headOption.getOrElse(0))
  else
    println(0)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val answer = in.next().filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.toList.sorted.headOption

  println(answer.getOrElse(0))

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = "Bulbasaur".toCharArray
  val answer = in.next().filter(str.contains).groupBy(identity).map {
    case ('a', str) => str.length / 2
    case ('u', str) => str.length / 2
    case (_, str) => str.length
  }.max

  println(answer)

}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))
    lazy val input = getFreq(readLine)
    println(getFreq("Bulbbasaur").map(p => input.getOrElse(p._1, 0) / p._2).min)
  }
}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def getFreq(str: String) = str.groupBy(identity).map(p => (p._1, p._2.length))
    val input = getFreq(readLine)
    println(getFreq("Bulbbasaur").map(p => input.getOrElse(p._1, 0) / p._2).min)
  }
}

import scala.io.StdIn._

object Main extends App {
  val A = readLine()
  val Match = "Bulbbasaur"

  val G = A.groupBy(identity).mapValues(_.length)
  val min = Array(
  G.getOrElse('B', 0),
  G.getOrElse('u', 0) / 2,
  G.getOrElse('l', 0),
  G.getOrElse('b', 0) / 2,
  G.getOrElse('a', 0) / 2,
  G.getOrElse('s', 0),
  G.getOrElse('r', 0)).min

  println(min)
}


import scala.io.StdIn

object Solution_D extends App {
  val T = StdIn.readInt()
  for (_ <- 1 to T) {
    val sudoku = Array.ofDim[String](9)
    val result = Array.ofDim[Int](9, 9)
    for (idx <- 0 until 9) {
      sudoku(idx) = StdIn.readLine()
      for (c <- 0 until 9) {
        result(idx)(c) = sudoku(idx)(c).toInt - '0'
      }
    }
    for (offset <- 0 until 3) {
      for (r <- 0 until 3) {
        val column = r + offset * 3
        val row = offset + r * 3
        result(row)(column) = 1 + result(row)(column) % 9
      }
    }
    for (idx <- 0 until 9) {
      println(result(idx).mkString)
    }
  }
}

object Main extends App {
  import scala.io.StdIn._
  val t = readInt

  for(_ <- 0 until t) {
    val state = Array.fill(9){readLine.trim.map(_.asDigit).toArray}
    var j = 0
    for (i <- 0 until 9) {
      state(i)(j) = state(i)(j) % 9 + 1
      j = (j + 4) % 9
    }
    println(state.map(_.mkString).mkString("\n"))
  }
}