object Main {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.util.control.NonFatal

  def main(_argv: Array[String]): Unit = {
    val input = new BufferedReader(new InputStreamReader(System.in))
    val output = new PrintWriter(System.out)
    val solver = new T1512C(input, output)
    solver.solve()
    //println( solver.oneLine( "0", zeros = 0, ones = 1 ) )
    output.close()
  }

  class T1512C(input: BufferedReader, output: PrintWriter) {

    def solve(): Unit = {
      val num = input.readLine().toInt
      for (_ <- 0 until num) {
        val prms = new StringTokenizer(input.readLine())
        val zeros = prms.nextToken().toInt
        val ones = prms.nextToken().toInt
        val data = input.readLine()
        val result = try {
          oneLine(data, zeros, ones)
        }
        catch {
          case NonFatal(_) => "-1"
        }
        output.println(result)
      }
    }

    def oneLine(str: String, zeros: Int, ones: Int): String = {
      if (zeros + ones != str.length) {
        throw new Exception()
      }
      val buf = new Array[Char](str.length)
      var restZeros = zeros
      var restOnes = ones
      for (idx <- buf.indices) {
        val char = str(idx)
        val oppositIndex = buf.length - idx - 1
        val oppositChar = str(oppositIndex)
        if (idx < buf.length / 2) {
          char match {
            case '0' => oppositChar match {
              case '1' =>
                throw new Exception()
              case '0' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restZeros -= 2
            }
            case '1' => oppositChar match {
              case '0' =>
                throw new Exception()
              case '1' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restOnes -= 2
            }
            case '?' => ()
          }
        }
        else {
          char match {
            case '0' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restZeros -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restZeros -= 1
                }
              case '0' =>
                if (idx == oppositIndex) {
                  buf(oppositIndex) = char
                  restZeros -= 1
                }
            }
            case '1' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restOnes -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restOnes -= 1
                }
              case '1' =>
                if (idx == oppositIndex) {
                  buf(oppositIndex) = char
                  restOnes -= 1
                }
            }
            case '?' => ()
          }
        }
      }

      for (idx <- 0 to str.length / 2) {
        val char = buf(idx)
        if (char == '\0') {
          val oppositIndex = buf.length - idx - 1
          if (idx != oppositIndex) {
            if (restZeros > 1) {
              buf(idx) = '0'
              buf(oppositIndex) = '0'
              restZeros -= 2
            }
            else if (restOnes > 1) {
              buf(idx) = '1'
              buf(oppositIndex) = '1'
              restOnes -= 2
            }
            else {
              throw new Exception()
            }
          }
          else {
            if (restZeros > 0 && restZeros % 2 == 1) {
              buf(idx) = '0'
              restZeros -= 1
            }
            else if (restOnes > 0 && restOnes % 2 == 1) {
              buf(idx) = '1'
              restOnes -= 1
            }
            else {
              throw new Exception()
            }
          }
        }
      }

      if (restZeros == 0 && restOnes == 0) {
        buf.mkString("")
      }
      else {
        throw new Exception()
      }
    }
  }
}

import scala.io.StdIn

object Main {
  def test(): String = {
    val in = StdIn.readLine().split(" ")
    var (a, b) = (in(0).toInt, in(1).toInt)
    val s : String = StdIn.readLine()
    val kek : List[(Char, Int)] = s.toList.zipWithIndex
    val n : Int = s.size
    val f : (Char, Int) => Boolean = (e, i) => (s(n - i - 1) == '?' || e == '?' || s(n - i - 1) == e)
    if (a + b != n)
      return "-1"
    if (!kek.forall { (elem) => f(elem._1, elem._2) } )
      return "-1"
    val s2 : List[Char] = kek.map { elem => if (s(n - elem._2 - 1) != '?') s(n - elem._2 - 1) else elem._1 }
    a = a - (s2.count( _ == '0'))
    b = b - s2.count( _ == '1')
    if (a < 0 || b < 0 || (a % 2 == 1 && b % 2 == 1))
      return "-1"
    if (a % 2 == 1 && s2(n / 2) == '1')
      return "-1"
    if (b % 2 == 1 && s2(n / 2) == '0')
      return "-1"

    val a1 = a % 2
    val a2 = b % 2
    a = a / 2
    b = b / 2
    val res : StringBuilder = new StringBuilder()
    for ((elem, i) <- s2.zipWithIndex) {
        if ( elem == '?' && (a > 0 || i == n / 2 && a1 == 1)) {
          res.append('0')
          a -= 1
        }
        else {
          if ( elem == '?' && (b > 0 || i == n / 2 && a2 == 1)) {
            res.append('1')
            b -= 1
          }
          else {
            if (elem == '?')
              res.append(res(n - i - 1))
            else
              res.append(elem)
          }
        }
    }
    return res.toString()
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => println(test())
    }
  }
}

object Main {
import java.io.{BufferedReader, InputStreamReader, PrintWriter}
import java.util.StringTokenizer
import scala.util.control.NonFatal

  def main(_argv: Array[String]): Unit = {
    val input = new BufferedReader(new InputStreamReader(System.in))
    val output = new PrintWriter(System.out)
    val solver = new T1512C(input, output)
    solver.solve()
    //    println( solver.oneLine( "?0??10??", zeros = 4, ones = 4 ) )
    output.close()
  }

  class T1512C(input: BufferedReader, output: PrintWriter) {

    def solve(): Unit = {
      val num = input.readLine().toInt
      for (_ <- 0 until num) {
        val prms = new StringTokenizer(input.readLine())
        val zeros = prms.nextToken().toInt
        val ones = prms.nextToken().toInt
        val data = input.readLine()
        val result = try {
          oneLine(data, zeros, ones)
        }
        catch {
          case NonFatal(_) => "-1"
        }
        output.println(result)
      }
    }

    def oneLine(str: String, zeros: Int, ones: Int): String = {
      if (zeros + ones != str.length) {
        throw new Exception()
      }
      val buf = new Array[Char](str.length)
      var restZeros = zeros
      var restOnes = ones
      for (idx <- buf.indices) {
        val char = str(idx)
        val oppositIndex = buf.length - idx - 1
        val oppositChar = str(oppositIndex)
        if (idx < buf.length / 2) {
          char match {
            case '0' => oppositChar match {
              case '1' =>
                throw new Exception()
              case '0' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restZeros -= 2
            }
            case '1' => oppositChar match {
              case '0' =>
                throw new Exception()
              case '1' | '?' =>
                buf(idx) = char
                buf(oppositIndex) = char
                restOnes -= 2
            }
            case '?' => ()
          }
        }
        else {
          char match {
            case '0' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restZeros -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restZeros -= 1
                }
              case '0' => ()
            }
            case '1' => oppositChar match {
              case '?' =>
                buf(idx) = char
                restOnes -= 1
                if (idx != oppositIndex) {
                  buf(oppositIndex) = char
                  restOnes -= 1
                }
              case '1' => ()
            }
            case '?' => ()
          }
        }
      }

      for (idx <- 0 to str.length / 2) {
        val char = buf(idx)
        if (char == '\0') {
          val oppositIndex = buf.length - idx - 1
          if (idx != oppositIndex) {
            if (restZeros > 1) {
              buf(idx) = '0'
              buf(oppositIndex) = '0'
              restZeros -= 2
            }
            else if (restOnes > 1) {
              buf(idx) = '1'
              buf(oppositIndex) = '1'
              restOnes -= 2
            }
            else {
              throw new Exception()
            }
          }
          else {
            if (restZeros > 0 && restZeros % 2 == 1) {
              buf(idx) = '0'
              restZeros -= 1
            }
            else if (restOnes > 0 && restOnes % 2 == 1) {
              buf(idx) = '1'
              restOnes -= 1
            }
            else {
              throw new Exception()
            }
          }
        }
      }

      if (restZeros == 0 && restOnes == 0) {
        buf.mkString("")
      }
      else {
        throw new Exception()
      }
    }
  }
}

import scala.io.StdIn

object Main {
  def test(): String = {
    val in = StdIn.readLine().split(" ")
    var (a, b) = (in(0).toInt, in(1).toInt)
    val s : String = StdIn.readLine()
    val kek : List[(Char, Int)] = s.toList.zipWithIndex
    val n : Int = s.size
    val f : (Char, Int) => Boolean = (e, i) => (s(n - i - 1) == '?' || e == '?' || s(n - i - 1) == e)
    if (a + b != n)
      return "-1"
    if (!kek.forall { (elem) => f(elem._1, elem._2) } )
      return "-1"
    val s2 : List[Char] = kek.map { elem => if (s(n - elem._2 - 1) != '?') s(n - elem._2 - 1) else elem._1 }
    a = a - (s2.count( _ == '0'))
    b = b - s2.count( _ == '1')
    if (a < 0 || b < 0 || (a % 2 == 1 && b % 2 == 1))
      return "-1"

    a = a / 2 + a % 2
    b = b / 2 + b % 2
    val res : StringBuilder = new StringBuilder()
    for ((elem, i) <- s2.zipWithIndex) {
        if (elem == '?' && a > 0) {
          res.append('0')
          a -= 1
        }
        else {
          if (elem == '?' && b > 0) {
            res.append('1')
            b -= 1
          }
          else {
            if (elem == '?')
              res.append(res(n - i - 1))
            else
              res.append(elem)
          }
        }
    }
    return res.toString()
  }

  def main(args: Array[String]): Unit = {
    val t = StdIn.readLine().toInt
    (1 to t) foreach {
      _ => println(test())
    }
  }
}


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

/**
 * Created by arseny on 28.09.14.
 */
object A extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextInt

    def sieve(n: Long): Array[Boolean] = {
      val primes = Array.fill(n.toInt + 1)(true)
      primes(0) = false
      primes(1) = false
      for(i <- 2L to n) {
        if(primes(i.toInt)) {
          if(i * i <= n) {
            for(j <- i * i to n by i) {
              primes(j.toInt) = false
            }
          }
        }
      }
      primes
    }

    val primes = sieve(1000000)
    //print(primes.toList)

    var found = false
    for (i <- 2 until n if !found) {
      if ((primes(i) == false) && (primes(n - i) == false)) {
        out.print(s"$i ${n - i}")
        found = true
      }
    }
  }

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

object DesignTutorial {
	def main(args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextLong;
		if (n % 2 == 0) {
			println(n - 4+ " "+4)
		}
		else {
			println(n - 9+ " "+9)
		}
	}
}

object Main {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);

  def main(args: Array[String]) {
    var Array(n) = READ;
    if (n%2 == 0) println("4 " + (n-4));
    else println("9 " + (n-9));
  }
}

import scala.io.StdIn

/**
 * Created by breezzo on 19.02.17.
 */
object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val primes = new Primes(n)

    for (i <- 4 to n) {
      if (!primes.isPrime(i)) {
        val y = n - i
        if (!primes.isPrime(y)) {
          println(i + " " + y)
          return
        }
      }
    }
  }

  class Primes(val n: Int) {
    val primes = Array.fill(n + 1)(true)
    primes(0) = false
    primes(1) = false

    for (i <- 2 to n if primes(i) && i.toLong * i <= n) {
      for (j <- i * i to n by i) {
        primes(j) = false
      }
    }

    def isPrime(v: Int): Boolean = {
      primes(v)
    }
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-29.
 */
object A472 extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  var com1 = 4
  var com2 = n - com1

  def isComposite(com: Int): Boolean = {
    if (com < 4) {
      false
    } else if (com == 4) {
      true
    } else {
      var i = 2

      while (i < com) {
        if (com % i == 0) {
          return true
        }

        i += 1
      }

      false
    }
  }

  while (!(isComposite(com1) && isComposite(com2))) {
    com1 += 1
    com2 -= 1
  }

  println(com1 + " " + com2)
}

import scala.io.StdIn.readInt
import Math.sqrt

object DesignTutorial {

   def isPrime(p : Int) : Boolean =
    p != 1 && (p == 2 || (2 to sqrt(p*1.0).toInt by 1).toList.forall { p % _ != 0 })

   def main(args: Array[String]) {
     val n = readInt
     Stream.from(4).find { x => !isPrime(x) && !isPrime(n-x) } match {
       case Some(x) => println(x + " " + (n-x))
       case _       => println("should not happen")
     }
   }

}

import scala.io.StdIn._

object Main2 extends App {
  val number = readInt()
  println(s"${number - (number%2+8)} ${number%2+8}")
}

import scala.annotation.tailrec

object Main extends App {

  val n: Int = io.StdIn.readInt()

  def solve(n: Int): String = {
    @tailrec
    def tailRec(i: Int, j: Int): String = {
      if (!isPrime(i) && !isPrime(j)) s"$i $j"
      else tailRec(i - 1, j + 1)
    }

    tailRec(n / 2, n - n / 2)
  }

  def isPrime(n: Int): Boolean = {
    @tailrec
    def isPrimeHelper(x: Int, acc: Boolean): Boolean = {
      if (!acc) false
      else if (x <= 1) true
      else isPrimeHelper(x - 1, n % x != 0 && acc)
    }

    isPrimeHelper(n / 2, acc = true)
  }

  println(solve(n))
}

import java.io._

object Solution extends App {
  val n = readInt

  def isPrime(n:Int):Boolean = {
    def paux(n:Int, i:Int):Boolean = {
      (n % i != 0) && (i*i > n || paux(n, i+2))
    }

    if(n == 1)
      false
    else if(n % 2 == 0)
      false
    else
      paux(n, 3)
  }

  val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>
    !isPrime(a) && !isPrime(b)
  }.head

  println(s"${ans._1} ${ans._2}")
}

import java.io._

object Solution extends App {
  val n = readInt

  def isPrime(n:Int):Boolean = {
    if(n == 1)
      false
    else if(n % 2 == 0)
      false
    else
      Stream.from(3, 2).takeWhile(i => i*i < n + 1).forall(i => n % i != 0)
  }

  val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>
    !isPrime(a) && !isPrime(b)
  }.head

  println(s"${ans._1} ${ans._2}")
}

import scala.io.StdIn

object Task472A {
	def main(args: Array[String]) {
		val n = StdIn.readInt()
		for (i <- 4 to n)
			if (!isPrime(i) && !isPrime(n-i)) {
				println(i + " " + (n - i))
				return
			}
	}

	def isPrime(n: Int): Boolean = {
		if (n % 2 == 0) return false
		var i = 3
		while (i*i <= n) if (n % i == 0) return false else i += 2
		true
	}
}

object TaskA {
  def main(args: Array[String]) {
    val n = readInt
    println {
      n match {
        case 12 => "6 6"
        case x if x % 2 == 0 => s"4 ${x - 4}"
        case x => s"9 ${x - 9}"
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._

object HelloWorld {

  def main(args: Array[String]) {

    val n = readInt()

    println(
      if (n % 2 == 0) ("4 " + (n-4))
      else ("9 " + (n-9))
    )

  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._

object HelloWorld {

  def is_compound(value: Int) = {
    var end = false

    for(i <- 2 to sqrt(value).toInt if !end) {
      if (value % i == 0) end = true
    }

    end
  }

  def main(args: Array[String]) {

    val n = readInt()
    var end = false

    for(i <- 4 to (n / 2, 2) if !end) {
      val j = n - i

      if (is_compound(j)) {
        println(i + " " + j)
        end = true
      }
    }

  }
}

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

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

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

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

  def genPrimes(till: Int): Array[Int] = {
    val isPrime = Array.fill[Boolean](till+1)(true)
    isPrime(0) = false
    isPrime(1) = true // not composite
    for(i <- 4 to till by 2) {
      isPrime(i) = false
    }
    for(i <- 3 to till by 2 if isPrime(i)) {
      for(j <- i+i to till by i) isPrime(j) = false
    }
    isPrime.zipWithIndex.filter(_._1).map(_._2)
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val primes = genPrimes(n).toSet
    for(i <- 1 to n/2) {
      if(!primes.contains(i) && !primes.contains(n - i)) {
        println(s"$i ${n-i}")
        return
      }
    }
  }
}

import scala.math._

object Main extends App{
  val n = readInt
  val iList = List(4, 6, 8, 10, 12)
  var result = for(i <- iList; m = n - i)
    yield if(m % 2 == 0 || m % 3 == 0 || m % 5 == 0 || m % 7 == 0 || (m % 11 == 0 && m != 11))
     (m, i)
  var res = result.filter(x => x != ()).head.toString.replace(',',' ') drop 1 dropRight 1
  print(res)
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)

  val LIMIT = n
  val prime = Array.fill(LIMIT)(true)
  prime(0) = false

  Stream.from(2).takeWhile(i => i * i < LIMIT).filter(prime(_)).foreach { i =>
    (i * i until LIMIT by i).foreach(prime(_) = false)
  }
  val primes = prime.indices.filter(prime(_)).toSet

  for (i <- 4 until n) {
    val j = n - i
    if (!primes(i) && !primes(j)) {
      println(s"$i $j")
      System.exit(0)
    }
  }
}

/**
 * <a href="http://codeforces.com/problemset/problem/472/A"/>
 *
 * @author pvasilyev
 * @since 08 Apr 2016
 */
object Problem147 extends App {

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

  def isNotPrime(number: Int): Boolean = {
    val upperBound = Math.sqrt(number).toInt + 1
    val range = 2 to upperBound
    for (x <- range) {
      if (number % x == 0) {
        return true
      }
    }
    return false
  }

  def solve(number: Int): String = {
      for (x <- 4 to number / 2) {
        if (isNotPrime(x) && isNotPrime(number - x)) {
          return x.toString() + " " + (number - x).toString()
        }
      }
    ""
  }

  println(solve(number))

}

import scala.io.StdIn

object Task472A {
	def main(args: Array[String]) {
		val n = StdIn.readInt()
		for (i <- 2 to n)
			if (!isPrime(i) && !isPrime(n-i)) {
				println(i + " " + (n - i))
				return
			}
	}

	def isPrime(n: Int): Boolean = {
		if (n % 2 == 0) return false
		var i = 3
		while (i*i <= n) if (n % i == 0) return false else i += 2
		true
	}
}

import scala.math._

object Main extends App{
  val n = readInt
  val iList = List(4, 6, 8, 10, 12)
  var result = for(i <- iList; m = n - i)
    yield if(m % 2 == 0 || m % 3 == 0 || m % 5 == 0 || m % 7 == 0 || m % 11 == 0)
     (m, i)
  var res = result.filter(x => x != ()).head.toString.replace(',',' ') drop 1 dropRight 1
  print(res)
}

/**
 * <a href="http://codeforces.com/problemset/problem/472/A"/>
 *
 * @author pvasilyev
 * @since 08 Apr 2016
 */
object Problem147 extends App {

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

  def isNotPrime(number: Int): Boolean = {
    val upperBound = Math.sqrt(number).toInt + 1
    val range = 2 to upperBound
    for (x <- range) {
      if (number % x == 0) {
        return true
      }
    }
    return false
  }

  def solve(number: Int): String = {
      for (x <- 4 until number / 2) {
        if (isNotPrime(x) && isNotPrime(number - x)) {
          return x.toString() + " " + (number - x).toString()
        }
      }
    ""
  }

  println(solve(number))

}

import java.io._

object Solution extends App {
  val n = readInt

  def isPrime(n:Int):Boolean = {
    def paux(n:Int, i:Int):Boolean = {
      (n % i == 0) && (i*i > n || paux(n, i+2))
    }

    if(n == 1)
      false
    else if(n % 2 == 0)
      false
    else
      paux(n, 3)
  }

  val ans = Stream.range(4, n/2+1).map(a => (a, n-a)).filter{ case(a, b) =>
    !isPrime(a) && !isPrime(b)
  }.head

  println(s"${ans._1} ${ans._2}")
}


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

import scala.collection.mutable

object B {

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

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

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

  def nextInt: Int = Integer.parseInt(next)

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

  def nextDouble: Double = java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      map.getOrDefault(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = map.firstKey()

    def last(): T = map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Unit = {
    val t = nextInt
    for (_ <- 0 until t) {
      val n = nextInt
      val apples = new Array[Int](n)
      val bananas = new Array[Int](n)
      for (i <- 0 until n) {
        apples(i) = nextInt
      }
      val min_app = apples.sorted.apply(0)
      for (i <- 0 until n) {
        bananas(i) = nextInt
      }
      val min_ban = bananas.sorted.apply(0)
      var moves = 0L
      for (i <- 0 until n) {
        val diff1 = apples(i) - min_app
        val diff2 = bananas(i) - min_ban
        moves += Math.min(diff1, diff2)
        moves += Math.max(diff1, diff2) - Math.min(diff1, diff2)

      }
      out.println(moves)

    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int]
    val candies, oranges = io.read[Vector, Long](n)

    val minCandy = candies.min
    val minOrange = oranges.min

    val ans = candies.zip(oranges) map {
      case (c, o) =>
        val candiesToEat = c - minCandy
        val orangesToEat = o - minOrange
        (candiesToEat min orangesToEat) + (candiesToEat - orangesToEat).abs
    }

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

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

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

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

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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

//package codeforces.contests._1399

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

      val minA = a.min
      val minB = b.min

      val answer = (0 until n).foldLeft(0L)((acc, i) => acc + {

        val decA = a(i) - minA
        val decB = b(i) - minB

        decA max decB
      })

      println(answer)
    }
  }
}

import scala.io.Source

object GiftsFixing1399B extends App {

  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//    val lines: Iterator[String] =
//      Source.fromString("5\n3\n3 5 6\n3 2 3\n5\n1 2 3 4 5\n5 4 3 2 1\n3\n1 1 1\n2 2 2\n6\n1 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1\n3\n10 12 8\n7 5 4").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach println

  def handleTC() = {
    if (lines.next.toInt == 1) {
      lines.next; lines.next;
      0L
    } else {
      val as = lines.next.split(" ").map(_.toLong)
      val bs = lines.next.split(" ").map(_.toLong)
      solve(as, bs)
    }
  }

  def solve(as: Array[Long], bs: Array[Long]) = {
    val am = as.min
    val bm = bs.min
    as.zip(bs).map { case (a, b) =>
      Math.max(a-am,b-bm)
    }.sum
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val xs = StdIn.readLine().split(" ").map(_.toLong)
      val ys  = StdIn.readLine().split(" ").map(_.toLong)
      val x = xs.min
      val y = ys.min
      val res = xs.map(_ - x) zip ys.map(_ - y) map {
        case (i, j) => i max j
      }
      println(res.sum)
    }
  }
}


object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val vov = Array[Char]('a', 'e', 'i', 'o', 'u', 'y')
  val lines = in.take(n).map(_.count(vov.contains)).toArray
  if (lines sameElements line)
    println("YES")
  else
    println("NO")
}

import scala.io.StdIn
import scala.math.pow
import scala.collection.mutable._

object Main {
  implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }

  def main(args: Array[String]): Unit = {
    val n = readInt
    val patterns = readLine.split(' ').map(_.toInt)

    var ok = true

    patterns.foreach { pattern =>
      val verse = readLine
      val vowels = verse.replaceAll("[^aeiouy]", "").length()

      if (ok && pattern != vowels) { ok = false }
    }

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

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

object test extends App {
	val vowels = List('a', 'e', 'i', 'o', 'u', 'y')
	val sc = new Scanner(System.in)
	val n = sc.nextInt()
	val numbers = List.range(0, n).map(x => sc.nextInt())
	sc.nextLine()
	val textLine = List.range(0, n).map(x => sc.nextLine())
	val counts = for (i <- 0 until textLine.length)
		yield textLine(i).count(vowels.contains(_))
	println(
		if (counts == numbers)
			"YES"
		else
			"NO"
	)
}

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

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

object Main extends App {

  val vowels = List('a', 'e', 'i', 'o', 'u', 'y')

  val sc = new Scanner(System.in)
  val n = sc.nextInt()
  val xs = List.range(0, n).map { _ => sc.nextInt() }
  sc.nextLine()
  val ys = List.range(0, n).map { _ => sc.nextLine() }
  val counts = for (i <- List.range(0, ys.length)) yield ys(i).count(vowels.contains(_))
  println(
    if(counts == xs) "YES" else "NO"
  )
}

object B extends App {

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

  val vowel = Set('a', 'e', 'i', 'o', 'u', 'y')
  val Array(n) = readInts(1)
  val ps = readInts(n)
  val ss = Array.fill(n){ readLine }

  val ok = (0 until n).forall(i => ss(i).count(vowel) == ps(i))

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

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

object _722B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val patterns = read[Vector[Int]]
    val input = patterns.zipWith(i => io.readTillEndOfLine())
    val vowels = "aeiouy".toSet

    val ans = input forall {case (pattern, line) =>
      line.count(vowels) ==  pattern
    }

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

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

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

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

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

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

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

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

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


import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.PriorityQueue
import java.util.StringTokenizer

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
    val inputs = file.readLine.toInt

    var i = 0
    while (i < inputs) {
      handleTC()
      i+=1
    }

    def handleTC(): Unit = {
      var st = new StringTokenizer(file.readLine)
      val v = st.nextToken.toInt
      val s = st.nextToken.toLong
      val g: Array[java.util.ArrayList[Array[Int]]] = Array.ofDim[java.util.ArrayList[Array[Int]]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      var ing = 1
      while (ing < v) {
        st = new StringTokenizer(file.readLine)
        val v = st.nextToken.toInt
        val u = st.nextToken.toInt
        val w = st.nextToken.toInt
        g(v).add(Array(u,w))
        g(u).add(Array(v,w))
        ing+=1
      }
      val tWs = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {
        def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1
        else -1

        foo(x, y)
      })
      var cur = 0L
      // DFS
      def traverse(par: Int, p: Int = 0): Int = {
        val adjL = g(par)
        if (p != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConversions._
        var sum = 0
        for (a <- adjL if a(0) != p) {
          val efs = traverse(a(0), par)
          tWs add Array(a(1), efs)
          cur += a(1) *1L* efs
          sum += efs
        }
        sum
      }
      traverse(1)
      var ans = 0
      while (cur > s) {
        val a = tWs.remove()
        cur -= (a(0) + 1) / 2 * a(1)
        tWs add Array(a(0) / 2, a(1))
        ans += 1
      }
      println(ans)
    }
  }
}

import java.util.PriorityQueue
import java.util.StringTokenizer

import scala.io.Source

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines

    val inputs = lines.next.toInt
    var i = 0
    while (i < inputs) {
      handleTC()
      i+=1
    }

    def handleTC(): Unit = {
      val vAndS = lines.next.split(" ")
      val v = vAndS(0).toInt
      val s = vAndS(1).toLong
      val g: Array[java.util.ArrayList[Array[Int]]] = Array.ofDim[java.util.ArrayList[Array[Int]]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      var ing = 1
      while (ing < v) {
        val s = lines.next.split(" ")
        val v = s(0).toInt
        val u = s(1).toInt
        val w = s(2).toInt
        g(v).add(Array(u,w))
        g(u).add(Array(v,w))
        ing+=1
      }
      val tWs = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {
        def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1
        else -1

        foo(x, y)
      })
      var cur = 0L
      // DFS
      def traverse(par: Int, p: Int = 0): Int = {
        val adjL = g(par)
        if (p != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConversions._
        var sum = 0
        for (a <- adjL if a(0) != p) {
          val efs = traverse(a(0), par)
          tWs add Array(a(1), efs)
          cur += a(1) *1L* efs
          sum += efs
        }
        sum
      }
      traverse(1)
      var ans = 0
      while (cur > s) {
        val a = tWs.remove()
        cur -= (a(0) + 1) / 2 * a(1)
        tWs add Array(a(0) / 2, a(1))
        ans += 1
      }
      println(ans)
    }
  }
}

object E {

  import java.io.BufferedReader
  import java.io.IOException
  import java.io.InputStreamReader
  import java.util
  import java.util.PriorityQueue
  import java.util.StringTokenizer

  var currSum = 0L

  @SuppressWarnings(Array("unchecked"))
  @throws[IOException]
  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
    var inputs = file.readLine.toInt
    while ( {
      {
        inputs -= 1; inputs + 1
      } > 0
    }) {
      var st = new StringTokenizer(file.readLine)
      val n = st.nextToken.toInt
      val s = st.nextToken.toLong
      val con = new Array[util.ArrayList[Array[Int]]](n)
      for (i <- 0 until n) {
        con(i) = new util.ArrayList[Array[Int]]
      }
      for (i <- 0 until n - 1) {
        st = new StringTokenizer(file.readLine)
        val a = st.nextToken.toInt - 1
        val b = st.nextToken.toInt - 1
        val weight = st.nextToken.toInt
        con(a).add(Array[Int](b, weight))
        con(b).add(Array[Int](a, weight))
      }
      val edges = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {
        def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1
        else -1

        foo(x, y)
      })
      currSum = 0
      dfs(0, new Array[Boolean](n), con, edges)
      var moves = 0
      while ( {
        currSum > s
      }) {
        moves += 1
        val curr = edges.remove()
        currSum -= (curr(0) + 1) / 2 * curr(1)
        curr(0) /= 2
        edges.add(curr)
      }
      System.out.println(moves)
    }
  }

  def dfs(curr: Int, visited: Array[Boolean], con: Array[util.ArrayList[Array[Int]]], edges: PriorityQueue[Array[Long]]): Int = {
    visited(curr) = true
    var numVisited = 0
    var size = 0
    import scala.collection.JavaConversions._
    for (i <- con(curr)) {
      if (!visited(i(0))) {
        numVisited += 1
        val s = dfs(i(0), visited, con, edges)
        currSum += i(1).toLong * s
        edges.add(Array[Long](i(1), s))
        size += s
      }
    }
    if (numVisited == 0) return 1
    size
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.PriorityQueue
import java.util.StringTokenizer

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
    val inputs = file.readLine.toInt

    var i = 0
    while (i < inputs) {
      handleTC()
      i += 1
    }

    def handleTC(): Unit = {
      var st = new StringTokenizer(file.readLine)
      val v = st.nextToken.toInt
      val s = st.nextToken.toLong
      val g: Array[java.util.ArrayList[Array[Int]]] = Array.ofDim[java.util.ArrayList[Array[Int]]](v + 1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb += 1
      }
      var ing = 1
      while (ing < v) {
        st = new StringTokenizer(file.readLine)
        val v = st.nextToken.toInt
        val u = st.nextToken.toInt
        val w = st.nextToken.toInt
        g(v).add(Array(u, w))
        g(u).add(Array(v, w))
        ing += 1
      }
      val tWs = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {
        def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1
        else -1

        foo(x, y)
      })
      var cur = 0L

      // DFS
      def traverse(par: Int, p: Int = 0): Int = {
        val adjL = g(par)
        if (p != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConversions._
        var sum = 0
        for (a <- adjL if a(0) != p) {
          val efs = traverse(a(0), par)
          tWs add Array(a(1), efs)
          cur += a(1) * 1L * efs
          sum += efs
        }
        sum
      }

      traverse(1)
      var ans = 0
      while (cur > s) {
        val a = tWs.remove()
        cur -= (a(0) + 1) / 2 * a(1)
        a(0) /= 2
        tWs add a
        ans += 1
      }
      println(ans)
    }
  }
}

object E {

  import java.io.BufferedReader
  import java.io.IOException
  import java.io.InputStreamReader
  import java.util
  import java.util.PriorityQueue
  import java.util.StringTokenizer

  var currSum = 0L

  @throws[IOException]
  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
    var inputs = file.readLine.toInt
    while ( {
      {
        inputs -= 1; inputs + 1
      } > 0
    }) {
      var st = new StringTokenizer(file.readLine)
      val n = st.nextToken.toInt
      val s = st.nextToken.toLong
      val con = new Array[util.ArrayList[Array[Int]]](n)
      for (i <- 0 until n) {
        con(i) = new util.ArrayList[Array[Int]]
      }
      for (i <- 0 until n - 1) {
        st = new StringTokenizer(file.readLine)
        val a = st.nextToken.toInt - 1
        val b = st.nextToken.toInt - 1
        val weight = st.nextToken.toInt
        con(a).add(Array[Int](b, weight))
        con(b).add(Array[Int](a, weight))
      }
      val edges = new PriorityQueue[Array[Long]]((x: Array[Long], y: Array[Long]) => {
        def foo(x: Array[Long], y: Array[Long]) = if ((x(0) + 1) / 2 * x(1) < (y(0) + 1) / 2 * y(1)) 1
        else -1

        foo(x, y)
      })
      currSum = 0
      dfs(0, new Array[Boolean](n), con, edges)
      var moves = 0
      while ( {
        currSum > s
      }) {
        moves += 1
        val curr = edges.remove()
        currSum -= (curr(0) + 1) / 2 * curr(1)
        curr(0) /= 2
        edges.add(curr)
      }
      System.out.println(moves)
    }
  }

  def dfs(curr: Int, visited: Array[Boolean], con: Array[util.ArrayList[Array[Int]]], edges: PriorityQueue[Array[Long]]): Int = {
    visited(curr) = true
    var numVisited = 0
    var size = 0
    import scala.collection.JavaConversions._
    for (i <- con(curr)) {
      if (!visited(i(0))) {
        numVisited += 1
        val s = dfs(i(0), visited, con, edges)
        currSum += i(1).toLong * s
        edges.add(Array[Long](i(1), s))
        size += s
      }
    }
    if (numVisited == 0) return 1
    size
  }
}

//package codeforces.contests._1399

object WeightsDivisionEasy {

  import scala.collection.mutable

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, s) = io.StdIn.readLine.split(" ").map(_.toInt)
      val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)
      (1 until n).foreach { _ =>
        val Array(u, v, w) = io.StdIn.readLine.split(" ").map(_.toInt)
        graph(u) ::= (v, w)
        graph(v) ::= (u, w)
      }

      val leaves = new Array[Int](n + 1)

      val queue = mutable.PriorityQueue.empty[(Int, Int)](Ordering.by { case (w, c) => w * c - (w / 2) * c })

      var sum = 0

      def dfs(u: Int, p: Int): Unit = {
        if (graph(u).tail.isEmpty && graph(u).head._1 == p) leaves(u) = 1
        else
          graph(u).foreach { case (v, w) =>
            if (v != p) {
              dfs(v, u)
              leaves(u) += leaves(v)
              sum += w * leaves(v)
              queue.enqueue((w, leaves(v)))
            }
          }

      }

      dfs(1, 0)

      @scala.annotation.tailrec
      def reduce(sum: Int, steps: Int = 0): Int = {
        if (sum <= s) steps else {
          val (w, c) = queue.dequeue()
          queue.enqueue((w / 2, c))
          reduce(sum - w * c + (w / 2) * c, steps + 1)
        }
      }

      println(reduce(sum))
    }
  }
}

//package codeforces.contests._1399

object WeightsDivisionEasy {

  import scala.collection.mutable

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val Array(n, s) = io.StdIn.readLine.split(" ").map(_.toInt)
      val graph = Array.fill[List[(Int, Int)]](n + 1)(Nil)
      (1 until n).foreach { _ =>
        val Array(u, v, w) = io.StdIn.readLine.split(" ").map(_.toInt)
        graph(u) ::= (v, w)
        graph(v) ::= (u, w)
      }

      val leaves = new Array[Int](n + 1)

      val queue = mutable.PriorityQueue.empty[(Int, Int)](Ordering.by(x => x._1 * x._2))

      var sum = 0

      def dfs(u: Int, p: Int): Unit = {
        graph(u).foreach { case (v, w) =>
          if (v != p) {
            dfs(v, u)
            leaves(u) += leaves(v)
            sum += w * leaves(v)
            queue.enqueue((w, leaves(v)))
          }
        }

        if (leaves(u) == 0) leaves(u) = 1
      }

      dfs(1, 0)

      @scala.annotation.tailrec
      def reduce(sum: Int, steps: Int = 0): Int = {
        if (sum <= s) steps else {
          val (w, c) = queue.dequeue()
          queue.enqueue((w / 2, c))
          reduce(sum - w * c + (w / 2) * c, steps + 1)
        }
      }

      println(reduce(sum))
    }
  }
}

import scala.collection.mutable
import scala.io.Source

object WeightsDivision1399E1 extends App {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//   val lines: Iterator[String] =
//     Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { println }

  case class Edge(uv: (Int, Int), w: Long)

  private def handleTC() = {
    val vAndS = lines.next.split(" ")
    val v = vAndS(0).toInt
    val S = vAndS(1).toLong
    val g: Array[mutable.Set[Edge]] = Array.ofDim[mutable.Set[Edge]](v+1)
    def updEdgeSet(e: Edge, f: Edge => Int): Unit = {
      val es = Option(g(f(e))).getOrElse(mutable.Set())
      es.+=(e)
      g(f(e)) = es
    }
    for (_ <- 1 until v) {
      val s = lines.next.split(" ")
      val e = Edge((s(0).toInt, s(1).toInt), s(2).toInt)
      updEdgeSet(e, _.uv._1)
      updEdgeSet(e, _.uv._2)
    }
    val eCounts = mutable.Map[Edge, Long]()
    val tWs = mutable.PriorityQueue[(Long, Long)]()(Ordering
      .by[(Long, Long), Long](x => Math.ceil(x._1 / 2.0).asInstanceOf[Int] * x._2))
    var r = 0L
    def traverse(par: Int): Unit = {
      val adjL = g(par)
      for (e <- adjL) {
        val nonPar = if (e.uv._1 == par) e.uv._2 else e.uv._1
        val nextAdjL = g(nonPar)
        nextAdjL.remove(e)
        traverse(nonPar)
        val ec = nextAdjL.map(eCounts).sum
        val ecf = if (ec == 0) 1 else ec
        eCounts(e) = ecf
        tWs += ((e.w, ecf))
        r = r + e.w * ecf
      }
    }
    traverse(1)
    if (r <= S) {
      0
    } else {
      var st = 0
      do {
        val (w, c) = tWs.dequeue
        st = st + 1
        val ceil = Math.ceil(w / 2.0).asInstanceOf[Long]
        r = r - ceil * c
        tWs += ((Math.floor(w / 2.0).asInstanceOf[Long], c))
      } while (tWs.nonEmpty && r > S)
      st
    }
  }
}

import scala.io.Source

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
//    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
       val lines: Iterator[String] =
         Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

    //       1
    //   / /  \     \
    // 5   6  4      2
    //           /  / \  \ \
    //          10  8  7 9  3
    val ntc: Int = lines.next.toInt
    var i = 0
    while (i < ntc) {
      println(handleTC())
      i+=1
    }

    def handleTC(): Int = {
      val vAndS = lines.next.split(" ")
      val v = vAndS(0).toInt
      val S = vAndS(1).toLong
      val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      val efs = Array.ofDim[Int](v)
      val ws = Array.ofDim[Int](v)
      var ing = 1
      while (ing < v) {
        val s = lines.next.split(" ")
        val v = s(0).toInt
        val u = s(1).toInt
        val w = s(2).toInt
        g(v).add((u,ing))
        g(u).add((v,ing))
        ws(ing) = w
        ing+=1
      }
      val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {
        def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else -1
        foo(x, y)
      })
      def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)
      var r = 0L
      // DFS
      def traverse(par: Int, grand: Int): Int = {
        val adjL = g(par)
        if (grand != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConverters._
        (for ((v,id) <- adjL.asScala if id != grand) yield {
          efs(id) = traverse(v, id)
          tWs add ((getDiff(id), id))
          r = r + ws(id) * efs(id)
          efs(id)
        }).sum
      }
      traverse(1,0)
      var st = 0
      while (r > S) {
        val (k, e) = tWs.remove()
        st += 1
        ws(e) = ws(e) / 2
        r = r - k
        tWs add ((getDiff(e), e))
      }
      st
    }
  }
}

import scala.io.Source

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
    //   val lines: Iterator[String] =
    //      Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

    //       1
    //   / /  \     \
    // 5   6  4      2
    //           /  / \  \ \
    //          10  8  7 9  3
    val ntc: Int = lines.next.toInt
    var i = 0
    while (i < ntc) {
      println(handleTC())
      i+=1
    }

    def handleTC(): Int = {
      val vAndS = lines.next.split(" ")
      val v = vAndS(0).toInt
      val s = vAndS(1).toLong
      val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      val efs = Array.ofDim[Int](v)
      val ws = Array.ofDim[Int](v)
      var ing = 1
      while (ing < v) {
        val s = lines.next.split(" ")
        val v = s(0).toInt
        val u = s(1).toInt
        val w = s(2).toInt
        g(v).add((u,ing))
        g(u).add((v,ing))
        ws(ing) = w
        ing+=1
      }
      val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {
        def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else if (x._1 == y._1 && x._2 < y._2) 1
        else -1
        foo(x, y)
      })
      def getDiff(e: Int): Long = (ws(e)*1L - ws(e) / 2) * efs(e)
      var cur = 0L
      // DFS
      def traverse(par: Int, p: Int = 0): Int = {
        val adjL = g(par)
        if (p != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConverters._
        (for ((v,id) <- adjL.asScala if id != p) yield {
          efs(id) = traverse(v, id)
          tWs add ((getDiff(id), id))
          cur = cur + ws(id) * efs(id)
          efs(id)
        }).sum
      }
      traverse(1)
      var ans = 0
      while (cur > s) {
        val (k, id) = tWs.remove()
        cur -= k
        ws(id) /= 2
        tWs add ((getDiff(id), id))
        ans += 1
      }
      ans
    }
  }
}

import scala.io.Source

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
    //   val lines: Iterator[String] =
    //      Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

    //       1
    //   / /  \     \
    // 5   6  4      2
    //           /  / \  \ \
    //          10  8  7 9  3
    val ntc: Int = lines.next.toInt
    var i = 0
    while (i < ntc) {
      println(handleTC())
      i+=1
    }

    def handleTC(): Int = {
      val vAndS = lines.next.split(" ")
      val v = vAndS(0).toInt
      val s = vAndS(1).toLong
      val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      val efs = Array.ofDim[Int](v)
      val ws = Array.ofDim[Int](v)
      var ing = 1
      while (ing < v) {
        val s = lines.next.split(" ")
        val v = s(0).toInt
        val u = s(1).toInt
        val w = s(2).toInt
        g(v).add((u,ing))
        g(u).add((v,ing))
        ws(ing) = w
        ing+=1
      }
      val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {
        def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else if (x._1 == y._1 && x._2 < y._2) 1
        else -1
        foo(x, y)
      })
      def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)
      var cur = 0L
      // DFS
      def traverse(par: Int, p: Int = 0): Int = {
        val adjL = g(par)
        if (p != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConverters._
        (for ((v,id) <- adjL.asScala if id != p) yield {
          efs(id) = traverse(v, id)
          tWs add ((getDiff(id), id))
          cur = cur + ws(id) * efs(id)
          efs(id)
        }).sum
      }
      traverse(1)
      var ans = 0
      while (cur > s) {
        val (k, id) = tWs.remove()
        cur -= k
        ws(id) /= 2
        tWs add ((getDiff(id), id))
        ans += 1
      }
      ans
    }
  }
}

import scala.collection.mutable
import scala.io.Source

object WeightsDivision1399E1 extends App {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//   val lines: Iterator[String] =
//     Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

  //       1
  //   / /  \     \
  // 5   6  4      2
  //           /  / \  \ \
  //          10  8  7 9  3
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { println }

  case class Edge(uv: (Int, Int), w: Long)

  private def handleTC(): Int = {
    val vAndS = lines.next.split(" ")
    val v = vAndS(0).toInt
    val S = vAndS(1).toLong
    val g: Array[mutable.Set[(Int, Int)]] = Array.ofDim[mutable.Set[(Int, Int)]](v+1)
    def updEdgeSet(v: Int, u: Int, w: Int): Unit = {
      val es = Option(g(v)).getOrElse(mutable.Set())
      es.+=((u,w))
      g(v) = es
    }
    for (_ <- 1 until v) {
      val s = lines.next.split(" ")
      val v = s(0).toInt
      val u = s(1).toInt
      val w = s(2).toInt
      updEdgeSet(v, u, w)
      updEdgeSet(u, v, w)
    }
    val tWs = mutable.PriorityQueue[(Long, Long)]()(Ordering
      .by[(Long, Long), Long](x => Math.ceil(x._1 / 2.0).asInstanceOf[Int] * x._2))
    var r = 0L
    // DFS
    def traverse(par: Int, grand:Int): Long = {
      val adjL = g(par)
      if (adjL.size == 1) return 1
      (for ((v,w) <- adjL.toSeq if v != grand) yield {
        val nextAdjL = g(v)
//        nextAdjL.-=((par, w))//remove parent edge = mark as visited
        val ecf = traverse(v,par)
        tWs += ((w, ecf))
        r = r + w * ecf
        ecf
      }).sum
    }
    traverse(1,0)
    if (r <= S) {
      0
    } else {
      var st = 0
      do {
        val (w, c) = tWs.dequeue
        st = st + 1
        val ceil = Math.ceil(w / 2.0).asInstanceOf[Long]
        r = r - ceil * c
        tWs += ((w - ceil, c))
      } while (tWs.nonEmpty && r > S)
      st
    }
  }
}

import scala.collection.mutable
import scala.io.Source

object WeightsDivision1399E1 extends App {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//  val lines: Iterator[String] =
//    Source.fromString("3\n3 20\n2 1 8\n3 1 7\n5 50\n1 3 100\n1 5 10\n2 3 123\n5 4 55\n2 100\n1 2 409").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { println }

  case class Edge(uv: (String, String), w: Int)

  private def handleTC() = {
    val vAndS = lines.next.split(" ")
    val v = vAndS(0).toInt
    val S = vAndS(1).toInt
    val g = mutable.Map[String, mutable.Set[Edge]]()
    def updEdgeSet(e: Edge, f: Edge => String): Unit = {
      val es = g.getOrElse(f(e), mutable.Set())
      es.add(e)
      g(f(e)) = es
    }
    for (_ <- 1 until v) {
      val s = lines.next.split(" ")
      val e = Edge((s(0), s(1)), s(2).toInt)
      updEdgeSet(e, _.uv._1)
      updEdgeSet(e, _.uv._2)
    }
    val eCounts = mutable.Map[Edge, Int]()
    val tWs = mutable.PriorityQueue[Int]()
    def traverse(par: String): Unit = {
      for (e <- g(par)) {
        val nonPar = e.uv.productIterator.find(_ != par).get.asInstanceOf[String]
        g(nonPar).remove(e)
        traverse(nonPar)
        val ec = g(nonPar).map(eCounts).sum
        val ecf = if (ec == 0) 1 else ec
        eCounts(e) = ecf
        tWs += e.w * ecf
      }
    }
    traverse("1")
    var r = tWs.sum
    if (r <= S) {
      0
    } else {
      var st = 0
      do {
        val i = tWs.dequeue
        st = st + 1
        val ceil = Math.ceil(i / 2.0).asInstanceOf[Int]
        r = r - ceil
        tWs += Math.floor(i / 2.0).asInstanceOf[Int]
      } while (tWs.nonEmpty && r > S)
      st
    }
  }
}

import scala.io.Source

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
    //   val lines: Iterator[String] =
    //      Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

    //       1
    //   / /  \     \
    // 5   6  4      2
    //           /  / \  \ \
    //          10  8  7 9  3
    val ntc: Int = lines.next.toInt
    var i = 0
    while (i < ntc) {
      println(handleTC())
      i+=1
    }

    def handleTC(): Int = {
      val vAndS = lines.next.split(" ")
      val v = vAndS(0).toInt
      val s = vAndS(1).toLong
      val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      val efs = Array.ofDim[Int](v)
      val ws = Array.ofDim[Int](v)
      var ing = 1
      while (ing < v) {
        val s = lines.next.split(" ")
        val v = s(0).toInt
        val u = s(1).toInt
        val w = s(2).toInt
        g(v).add((u,ing))
        g(u).add((v,ing))
        ws(ing) = w
        ing+=1
      }
      val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {
        def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else if (x._1 == y._1 && x._2 < y._2) 1
        else -1
        foo(x, y)
      })
      def getDiff(e: Int): Long = ws(e)*1L*efs(e) - (ws(e) / 2L) * 1L*efs(e)
      var cur = 0L
      // DFS
      def traverse(par: Int, p: Int = 0): Int = {
        val adjL = g(par)
        if (p != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConverters._
        (for ((v,id) <- adjL.asScala if id != p) yield {
          efs(id) = traverse(v, id)
          tWs add ((getDiff(id), id))
          cur = cur + ws(id) * efs(id)
          efs(id)
        }).sum
      }
      traverse(1)
      var ans = 0
      while (cur > s) {
        val (k, id) = tWs.remove()
        cur -= k
        ws(id) /= 2
        tWs add ((getDiff(id), id))
        ans += 1
      }
      ans
    }
  }
}

import scala.io.Source

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
    //   val lines: Iterator[String] =
    //      Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

    //       1
    //   / /  \     \
    // 5   6  4      2
    //           /  / \  \ \
    //          10  8  7 9  3
    val ntc: Int = lines.next.toInt
    var i = 0
    while (i < ntc) {
      println(handleTC())
      i+=1
    }

    def handleTC(): Int = {
      val vAndS = lines.next.split(" ")
      val v = vAndS(0).toInt
      val S = vAndS(1).toLong
      val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      val efs = Array.ofDim[Int](v)
      val ws = Array.ofDim[Int](v)
      var ing = 1
      while (ing < v) {
        val s = lines.next.split(" ")
        val v = s(0).toInt
        val u = s(1).toInt
        val w = s(2).toInt
        g(v).add((u,ing))
        g(u).add((v,ing))
        ws(ing) = w
        ing+=1
      }
      val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {
        def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else -1
        foo(x, y)
      })
      def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)
      var r = 0L
      // DFS
      def traverse(par: Int, p: Int): Int = {
        val adjL = g(par)
        if (adjL.size == 1) return 1
        import scala.collection.JavaConverters._
        (for ((v,id) <- adjL.asScala if id != p) yield {
          efs(id) = traverse(v, id)
          tWs add ((getDiff(id), id))
          r = r + ws(id) * efs(id)
          efs(id)
        }).sum
      }
      traverse(1,0)
      var st = 0
      while (r > S) {
        val (k, e) = tWs.remove()
        st += 1
        ws(e) = ws(e) / 2
        r = r - k
        tWs add ((getDiff(e), e))
      }
      st
    }
  }
}

import scala.collection.mutable
import scala.io.Source

object WeightsDivision1399E1 extends App {
//    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
  val lines: Iterator[String] =
    Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

  //       1
  //   / /  \     \
  // 5   6  4      2
  //           /  / \  \ \
  //          10  8  7 9  3
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { println }

  case class Edge(uv: (Int, Int), w: Long)

  private def handleTC(): Int = {
    val vAndS = lines.next.split(" ")
    val v = vAndS(0).toInt
    val S = vAndS(1).toLong
    val g: Array[mutable.Buffer[(Int, Int)]] = Array.ofDim[mutable.Buffer[(Int, Int)]](v+1)
    def updEdgeSet(v: Int, u: Int, w: Int): Unit = {
      val es = Option(g(v)).getOrElse(mutable.Buffer())
      es.+=((u,w))
      g(v) = es
    }
    for (_ <- 1 until v) {
      val s = lines.next.split(" ")
      val v = s(0).toInt
      val u = s(1).toInt
      val w = s(2).toInt
      updEdgeSet(v, u, w)
      updEdgeSet(u, v, w)
    }
    val tWs = mutable.TreeMap[(Long, Int), (Long, Long)]()
    var r = 0L
    def getDiff(w: Long, c: Long): Long = {
      Math.ceil(w / 2.0).asInstanceOf[Long] * c
    }
    // DFS
    def traverse(par: Int, grand: Int): Long = {
      val adjL = g(par)
      if (grand != 0 && adjL.size == 1) return 1
      (for ((v,w) <- adjL if v != grand) yield {
        val ecf = traverse(v, par)
        tWs((getDiff(w, ecf), v)) = (w, ecf)
        r = r + w * ecf
        ecf
      }).sum
    }
    traverse(1,0)
    var st = 0
    while (r > S) {
      val ((k, v), (w, c)) = tWs.last
      tWs.remove((k,v))
      st = st + 1
      val floor = Math.floor(w / 2.0).asInstanceOf[Long]
      r = r - k
      tWs((getDiff(floor, c), v)) = (floor, c)
    }
    st
  }
}

import scala.io.Source

object WeightsDivision1399E1 {

  def main(args: Array[String]): Unit = {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
    //   val lines: Iterator[String] =
    //      Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines

    //       1
    //   / /  \     \
    // 5   6  4      2
    //           /  / \  \ \
    //          10  8  7 9  3
    val ntc: Int = lines.next.toInt
    var i = 0
    while (i < ntc) {
      println(handleTC())
      i+=1
    }

    def handleTC(): Int = {
      val vAndS = lines.next.split(" ")
      val v = vAndS(0).toInt
      val S = vAndS(1).toLong
      val g: Array[java.util.ArrayList[(Int, Int)]] = Array.ofDim[java.util.ArrayList[(Int, Int)]](v+1)
      var inb = 0
      while (inb <= v) {
        g(inb) = new java.util.ArrayList()
        inb+=1
      }
      val efs = Array.ofDim[Int](v)
      val ws = Array.ofDim[Int](v)
      var ing = 1
      while (ing < v) {
        val s = lines.next.split(" ")
        val v = s(0).toInt
        val u = s(1).toInt
        val w = s(2).toInt
        g(v).add((u,ing))
        g(u).add((v,ing))
        ws(ing) = w
        ing+=1
      }
      val tWs: java.util.PriorityQueue[(Long, Int)] = new java.util.PriorityQueue[(Long, Int)]((x: (Long, Int), y: (Long, Int)) => {
        def foo(x: (Long, Int), y: (Long, Int)) = if (x._1 < y._1) 1 else -1
        foo(x, y)
      })
      def getDiff(e: Int): Long = (ws(e) - ws(e) / 2) * efs(e)
      var r = 0L
      // DFS
      def traverse(par: Int, grand: Int): Int = {
        val adjL = g(par)
        if (grand != 0 && adjL.size == 1) return 1
        import scala.collection.JavaConverters._
        (for ((v,id) <- adjL.asScala if id != grand) yield {
          efs(id) = traverse(v, id)
          tWs add ((getDiff(id), id))
          r = r + ws(id) * efs(id)
          efs(id)
        }).sum
      }
      traverse(1,0)
      var st = 0
      while (r > S) {
        val (k, e) = tWs.remove()
        st += 1
        ws(e) = ws(e) / 2
        r = r - k
        tWs add ((getDiff(e), e))
      }
      st
    }
  }
}

import scala.collection.mutable
import scala.io.Source

object WeightsDivision1399E1 extends App {
    val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//  val lines: Iterator[String] =
//    Source.fromString("1\n10 28\n8 2 8\n5 1 4\n6 1 10\n10 2 7\n7 2 1\n9 2 1\n2 1 5\n4 1 9\n3 2 5").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach { println }

  case class Edge(uv: (String, String), w: Int)

  private def handleTC() = {
    val vAndS = lines.next.split(" ")
    val v = vAndS(0).toInt
    val S = vAndS(1).toInt
    val g = mutable.Map[String, mutable.Set[Edge]]()
    def updEdgeSet(e: Edge, f: Edge => String): Unit = {
      val es = g.getOrElse(f(e), mutable.Set())
      es.add(e)
      g(f(e)) = es
    }
    for (_ <- 1 until v) {
      val s = lines.next.split(" ")
      val e = Edge((s(0), s(1)), s(2).toInt)
      updEdgeSet(e, _.uv._1)
      updEdgeSet(e, _.uv._2)
    }
    val eCounts = mutable.Map[Edge, Int]()
    val tWs = mutable.PriorityQueue[(Int, Int)]()(Ordering.by[(Int, Int), Int](x => Math.ceil(x._1 / 2.0).asInstanceOf[Int] * x._2))
    def traverse(par: String): Unit = {
      for (e <- g(par)) {
        val nonPar = e.uv.productIterator.find(_ != par).get.asInstanceOf[String]
        g(nonPar).remove(e)
        traverse(nonPar)
        val ec = g(nonPar).toSeq.map(eCounts).sum
        val ecf = if (ec == 0) 1 else ec
        eCounts(e) = ecf
        tWs += ((e.w, ecf))
      }
    }
    traverse("1")
    var r = tWs.map { case (w,c) => w * c }.sum
    if (r <= S) {
      0
    } else {
      var st = 0
      do {
        val (w, c) = tWs.dequeue
        st = st + 1
        val ceil = Math.ceil(w / 2.0).asInstanceOf[Int]
        r = r - ceil * c
        tWs += ((Math.floor(w / 2.0).asInstanceOf[Int], c))
      } while (tWs.nonEmpty && r > S)
      st
    }
  }
}