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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

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

      val mn = math.min(a, b)
      val mx = math.max(a, b)

      if(2 * mn > mx) {
        out.println(4 * mn * mn)
      } else out.println(mx * mx)
    }
  }
}

object CodeforcesRound644a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

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

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

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a, b) = rll_long
    val res = sqr(Math.max(Math.max(Math.min(a * 2, b * 2), a), b))
    writer.println(res)
  }

  def sqr(a: Long): Long = a * a

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

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

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

}

import scala.io.StdIn.readLine

object A {

  import scala.math._
  def solution(a: Int, b: Int): Int = {
    val (mi, ma) = (min(a, b), max(a, b))
    val c = max(mi*2, ma)
    c * c
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(n, k) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(n, k))
    }
  }
}

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

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

    val c = (2 * (a min b)) max (a max b)

    println(c * c)

  }
}

object CodeforcesRound644a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

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

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

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a,b) = rll_long
    val res = Math.pow(Math.min(Math.max(3,b*2), Math.max(a*2,b)), 2).toLong
    writer.println(res)
  }

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

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

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

}

object CodeforcesRound644a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

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

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

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a,b) = rll_long
    val res = (Math.min(a,b) * 2) * (Math.min(a,b) * 2)
    writer.println(res)
  }

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

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

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

}


object CF_522_2_B {

  case class Output(rows: Int, columns: Int, table: Seq[String])

  def solve(in: String): Output = {
    val n = in.length
    val rows = ceil(n,20)
    val cols = ceil(n, rows)
    val tableSize = rows * cols
    val remainder = tableSize - n
    def make(r: Int, s: String, out: Seq[String]): Seq[String] = r match {
      case 0 => out
      case _ =>
        val len = if (r <= remainder) cols - 1 else cols
        val (first, last) = s.splitAt(len)
        make(r - 1, last, out :+ first.padTo(cols,'*'))
    }
    val table = make(rows, in, Seq.empty)
    Output(rows, cols, table)
  }

  def solution(i: Input) = solve(i.string)

//     ~~~ Boilerplate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  def main(args: Array[String]) {
    val out = new java.io.PrintWriter(System.out)
    val sol = solution(new Input(System.in))
    out.println(sol.rows + " " + sol.columns + "\n" + sol.table.mkString("\n"))
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def string = sc.next()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
}

object B extends App {

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

  val s = readLine
  val n = s.length

  var rows = 1
  while (rows < 6) {
    if (rows * 20 >= n) {
      val colsMin = n / rows
      val rem = n % rows
      if (rem == 0) {
        println(s"$rows $colsMin")
        s.grouped(colsMin).foreach(println)
      } else {
        val cols = colsMin + 1
        val left = s.take(rem * cols)
        val right = s.drop(rem * cols)
        println(s"$rows $cols")
        left.grouped(cols).foreach(println)
        right.grouped(colsMin).foreach(x => println(x + "*"))
      }
      rows = 100
    }
    rows += 1
  }
}

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

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

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

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

  def solve(): Unit = {
    val S = ns()
    val n = S.length
    val rowCnt = (n - 1) / 20 + 1
    val colCnt = (n - 1) / rowCnt + 1
    val minus = colCnt * rowCnt - n
    var l = 0

    out.println(s"$rowCnt $colCnt")

    rep(rowCnt) { r =>
      if (r < rowCnt - minus) {
        val r = l + colCnt
        out.println(S.substring(l, r))
        l = r
      } else {
        val r = l + colCnt - 1
        out.println(s"${S.substring(l, r)}*")
        l = r
      }
    }
  }

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

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

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

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

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

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

object CF_522_2_B {

  case class Output(rows: Int, columns: Int, table: Seq[String])

  def solve(in: String): Output = {
    val n = in.length
    val rows = ceil(n,20)
    val cols = ceil(n, rows)
    val tableSize = rows * cols
    val remainder = tableSize - n
    def make(r: Int, s: String, out: Seq[String]): Seq[String] = r match {
      case 0 => out
      case _ =>
        val len = if (r < remainder) cols - 1 else cols
        val (first, last) = s.splitAt(len)
        make(r - 1, last, out :+ first.padTo(cols,'*'))
    }
    val table = make(rows, in, Seq.empty)
    Output(rows, cols, table)
  }

  def solution(i: Input) = solve(i.string)

//     ~~~ Boilerplate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  def main(args: Array[String]) {
    val out = new java.io.PrintWriter(System.out)
    val sol = solution(new Input(System.in))
    out.println(sol.rows + " " + sol.columns + "\n" + sol.table.mkString("\n"))
    out.close()
  }

//     ~~~ Utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def string = sc.next()
    def nextLine = sc.nextLine()
    // If there are prior values, remember to call nextLine to advance past the newline character before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq() = collect(_.toInt)
    def doubleSeq() = collect(_.toDouble)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
}


import scala.collection.mutable.ArrayBuffer

object C {

  import java.io._

  val out: OutputPrinter = new BufferedOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
//    val input = new InputReader(new StringReader(
//      """4
//              7
//              1 2 1 2 1 2 1
//              6 8 3 1 5 1 5
//              10
//              1 1 1 2 2 2 2 3 3 3
//              3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
//              6
//              3 3 3 3 3 3
//              5 9 6 7 9 7
//              1
//              1
//              3083
//              """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n) { (idx, u) => st(idx) = u - 1 }
        val ub = Array.fill[List[Int]](n)(Nil)
        input.forInts(n) { (idx, s) =>
          val un = st(idx)
          ub(un) ::= s
        }
        val uns = ub.filter(_.nonEmpty).map { l =>
          val ar = new Array[Long](l.length)
          val it = l.iterator
          for (i <- ar.indices) {
            ar(i) = it.next()
          }
          val arr = ar.sortBy(-_)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
          arr
        }

        val ans = new Array[Long](n)

        for (i <- uns.indices) {
          for (k <- 1 to uns(i).length) {
            val len = uns(i).length
            if (len >= k) {
              ans(k - 1) += uns(i)(len / k * k - 1);
            }
          }
        }

        for (i <- 0 until n) out.print(s"${ans(i)} ")

        out.flush()
      }
    }
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt

        val s = new Array[Int](n)
        val u = new Array[Int](n)

        input.forInts(n) { (idx, i) => s(idx) = i - 1 }
        input.forInts(n) { (idx, i) => u(idx) = i }

        val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
        for (i <- 0 until n) bst(s(i)) += u(i)
        for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)

        val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)

        for (i <- 0 until n) {
          bst(i).foreach(x => pr(i) += pr(i).last + x)
        }

        val ans = new Array[Long](n)

        for (i <- 0 until n) {
          for (k <- 1 to bst(i).length) {
            ans(k - 1) += pr(i)(bst(i).length / k * k);
          }
        }

        for (i <- 0 until n) out.print(s"${ans(i)} ")

        out.flush()
      }
    }
  }

  class Solution2 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n)((idx, u) => st(idx) = u - 1)

        val bst = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]())
        input.forInts(n)((idx, s) => bst(st(idx)) += s)

        for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)

        for (i <- 0 until n) {
          val arr = bst(i)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
        }

        val ans = new Array[Long](n)

        for (i <- 0 until n) {
          for (k <- 1 to bst(i).length) {
            val len = bst(i).length
            if (len >= k) {
              ans(k - 1) += bst(i)(len / k * k - 1);
            }
          }
        }

        for (i <- 0 until n) out.print(s"${ans(i)} ")

        out.flush()
      }
    }
  }

  class Solution3 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n) { (idx, u) => st(idx) = u - 1 }

        val bst = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]())
        input.forInts(n)((idx, s) => bst(st(idx)) += s)

        for (i <- 0 until n) {
          val arr = bst(i).sortBy(-_)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
          bst(i) = arr
        }

        val ans = new Array[Long](n)

        for (k <- 1 to n) {
          var s = 0L
          bst.foreach { u =>
            val teams = u.length / k
            if (teams > 0) {
              s += u(teams * k - 1)
            }
          }
          out.print(s.toString)
          out.print(' ')
        }
        out.flush()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      if (buffer.nonEmpty) {
        println(buffer.result())
        buffer.clear()
      }
    }
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = {
      endl()
      buffer.flush()
    }
  }

}

import scala.collection.mutable.ArrayBuffer

object C {

  import java.io._

  val out: OutputPrinter = new BufferedOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
//  val input = new InputReader(new StringReader(
//    """4
//            7
//            1 2 1 2 1 2 1
//            6 8 3 1 5 1 5
//            10
//            1 1 1 2 2 2 2 3 3 3
//            3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
//            6
//            3 3 3 3 3 3
//            5 9 6 7 9 7
//            1
//            1
//            3083
//            """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution2
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt

        val s = new Array[Int](n)
        val u = new Array[Int](n)

        input.forInts(n) { (idx, i) => s(idx) = i - 1 }
        input.forInts(n) { (idx, i) => u(idx) = i }

        val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
        for (i <- 0 until n) bst(s(i)) += u(i)
        for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)

        val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)

        for (i <- 0 until n) {
          bst(i).foreach(x => pr(i) += pr(i).last + x)
        }

        val ans = new Array[Long](n)

        for (i <- 0 until n) {
          for (k <- 1 to bst(i).length) {
            ans(k - 1) += pr(i)(bst(i).length / k * k);
          }
        }

        for (i <- 0 until n) out.print(s"${ans(i)} ")

        out.flush()
      }
    }
  }

  class Solution2 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n)((idx, u) => st(idx) = u - 1)

        val bst = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]())
        input.forInts(n)((idx, s) => bst(st(idx)) += s)

        for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)

        for (i <- 0 until n) {
          val arr = bst(i)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
        }

        val ans = new Array[Long](n)

        for (i <- 0 until n) {
          for (k <- 1 to bst(i).length) {
            val len = bst(i).length
            if (len >= k) {
              ans(k - 1) += bst(i)(len / k * k - 1);
            }
          }
        }

        for (i <- 0 until n) out.print(s"${ans(i)} ")

        out.flush()
      }
    }
  }

  class Solution3 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n) { (idx, u) => st(idx) = u - 1 }
        val ub = Array.fill[List[Int]](n)(Nil)
        input.forInts(n) { (idx, s) =>
          val un = st(idx)
          ub(un) ::= s
        }
        val uns = ub.filter(_.nonEmpty).map { l =>
          val ar = new Array[Long](l.length)
          val it = l.iterator
          for (i <- ar.indices) {
            ar(i) = it.next()
          }
          val arr = ar.sortBy(-_)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
          arr
        }
        for (k <- 1 to n) {
          var s = 0L
          uns.foreach { u =>
            val teams = u.length / k
            if (teams > 0) {
              s += u(teams * k - 1)
            }
          }
          out.print(s.toString)
          out.print(' ')
        }
        out.flush()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      if (buffer.nonEmpty) {
        println(buffer.result())
        buffer.clear()
      }
    }
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = {
      endl()
      buffer.flush()
    }
  }

}

import scala.collection.mutable.ArrayBuffer

object C {

  import java.io._

  val out: OutputPrinter = new BufferedOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
  //    val input = new InputReader(new StringReader(
  //      """4
  //          7
  //          1 2 1 2 1 2 1
  //          6 8 3 1 5 1 5
  //          10
  //          1 1 1 2 2 2 2 3 3 3
  //          3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
  //          6
  //          3 3 3 3 3 3
  //          5 9 6 7 9 7
  //          1
  //          1
  //          3083
  //          """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {
    //
    //    int main() {
    //      int t;
    //      scanf("%d", &t);
    //      forn(_, t){
    //        int n;
    //        scanf("%d", &n);
    //        vector<int> s(n), u(n);
    //        forn(i, n){
    //          scanf("%d", &s[i]);
    //          --s[i];
    //        }
    //        forn(i, n){
    //          scanf("%d", &u[i]);
    //        }
    //        vector<vector<int>> bst(n);
    //        forn(i, n) bst[s[i]].push_back(u[i]);
    //        forn(i, n) sort(bst[i].begin(), bst[i].end(), greater<int>());

    //        vector<vector<long long>> pr(n, vector<long long>(1, 0));

    //        forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);
    //        vector<long long> ans(n);
    //        forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)
    //        ans[k - 1] += pr[i][bst[i].size() / k * k];
    //        forn(i, n)
    //        printf("%lld ", ans[i]);
    //        puts("");
    //      }
    //      return 0;
    //    }
    //
    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt

        val s = new Array[Int](n)
        val u = new Array[Int](n)

        input.forInts(n) { (idx, i) => s(idx) = i - 1 }
        input.forInts(n) { (idx, i) => u(idx) = i }

        val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
        for (i <- 0 until n) bst(s(i)) += u(i)
        for (i <- 0 until n) bst(i) = bst(i).sortBy(-_)

        val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)

        for (i <- 0 until n) {
          bst(i).foreach(x => pr(i) += pr(i).last + x)
        }

        val ans = new Array[Long](n)

        for (i <- 0 until n) {
          for (k <- 1 to bst(i).length) {
            ans(k - 1) += pr(i)(bst(i).length / k * k);
          }
        }

        for (i <- 0 until n) out.print(s"${ans(i)} ")

        out.flush()
      }
    }
  }

  class Solution2 {
    //
    //    int main() {
    //      int t;
    //      scanf("%d", &t);
    //      forn(_, t){
    //        int n;
    //        scanf("%d", &n);
    //        vector<int> s(n), u(n);
    //        forn(i, n){
    //          scanf("%d", &s[i]);
    //          --s[i];
    //        }
    //        forn(i, n){
    //          scanf("%d", &u[i]);
    //        }
    //        vector<vector<int>> bst(n);
    //        forn(i, n) bst[s[i]].push_back(u[i]);
    //        forn(i, n) sort(bst[i].begin(), bst[i].end(), greater<int>());
    //        vector<vector<long long>> pr(n, vector<long long>(1, 0));
    //        forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);
    //        vector<long long> ans(n);
    //        forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)
    //        ans[k - 1] += pr[i][bst[i].size() / k * k];
    //        forn(i, n)
    //        printf("%lld ", ans[i]);
    //        puts("");
    //      }
    //      return 0;
    //    }
    //
    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n) { (idx, u) => st(idx) = u - 1 }
        val ub = Array.fill[List[Int]](n)(Nil)
        input.forInts(n) { (idx, s) =>
          val un = st(idx)
          ub(un) ::= s
        }
        val uns = ub.filter(_.nonEmpty).map { l =>
          val ar = new Array[Long](l.length)
          val it = l.iterator
          for (i <- ar.indices) {
            ar(i) = it.next()
          }
          val arr = ar.sortBy(-_)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
          arr
        }
        for (k <- 1 to n) {
          var s = 0L
          uns.foreach { u =>
            val teams = u.length / k
            if (teams > 0) {
              s += u(teams * k - 1)
            }
          }
          out.print(s.toString)
          out.print(' ')
        }
        out.flush()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      if (buffer.nonEmpty) {
        println(buffer.result())
        buffer.clear()
      }
    }
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = {
      endl()
      buffer.flush()
    }
  }

}

import scala.collection.mutable.ArrayBuffer

object C {

  import java.io._

  val out: OutputPrinter = new BufferedOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
//  val input = new InputReader(new StringReader(
//    """4
//        7
//        1 2 1 2 1 2 1
//        6 8 3 1 5 1 5
//        10
//        1 1 1 2 2 2 2 3 3 3
//        3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
//        6
//        3 3 3 3 3 3
//        5 9 6 7 9 7
//        1
//        1
//        3083
//        """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {
    //
    //    int main() {
    //      int t;
    //      scanf("%d", &t);
    //      forn(_, t){
    //        int n;
    //        scanf("%d", &n);
    //        vector<int> s(n), u(n);
    //        forn(i, n){
    //          scanf("%d", &s[i]);
    //          --s[i];
    //        }
    //        forn(i, n){
    //          scanf("%d", &u[i]);
    //        }
    //        vector<vector<int>> bst(n);
    //        forn(i, n) bst[s[i]].push_back(u[i]);
    //        forn(i, n) sort(bst[i].begin(), bst[i].end(), greater<int>());

    //        vector<vector<long long>> pr(n, vector<long long>(1, 0));

    //        forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);
    //        vector<long long> ans(n);
    //        forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)
    //        ans[k - 1] += pr[i][bst[i].size() / k * k];
    //        forn(i, n)
    //        printf("%lld ", ans[i]);
    //        puts("");
    //      }
    //      return 0;
    //    }
    //
    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt

        val s = new Array[Int](n)
        val u = new Array[Int](n)

        input.forInts(n) { (idx, i) => s(idx) = i - 1 }
        input.forInts(n) { (idx, i) => u(idx) = i }

        val bst = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
        for (i <- 0 until n) bst(s(i)) += u(i)
        for (i <- 0 until n) bst(i).sortBy(-_)

        val pr = Array.fill[ArrayBuffer[Long]](n)(new ArrayBuffer[Long]() += 0)

        for (i <- 0 until n) {
          bst(i).foreach(x => pr(i) += pr(i).last + x)
        }

        val ans = new Array[Long](n)

        for (i <- 0 until n) {
          for (k <- 1 to bst(i).length) {
            ans(k - 1) += pr(i)(bst(i).length / k * k);
          }
        }

        for (i <- 0 until n) out.print(s"${ans(i)} ")

        out.flush()
      }
    }
  }

  class Solution2 {
    //
    //    int main() {
    //      int t;
    //      scanf("%d", &t);
    //      forn(_, t){
    //        int n;
    //        scanf("%d", &n);
    //        vector<int> s(n), u(n);
    //        forn(i, n){
    //          scanf("%d", &s[i]);
    //          --s[i];
    //        }
    //        forn(i, n){
    //          scanf("%d", &u[i]);
    //        }
    //        vector<vector<int>> bst(n);
    //        forn(i, n) bst[s[i]].push_back(u[i]);
    //        forn(i, n) sort(bst[i].begin(), bst[i].end(), greater<int>());
    //        vector<vector<long long>> pr(n, vector<long long>(1, 0));
    //        forn(i, n) for (int x : bst[i]) pr[i].push_back(pr[i].back() + x);
    //        vector<long long> ans(n);
    //        forn(i, n) for (int k = 1; k <= int(bst[i].size()); ++k)
    //        ans[k - 1] += pr[i][bst[i].size() / k * k];
    //        forn(i, n)
    //        printf("%lld ", ans[i]);
    //        puts("");
    //      }
    //      return 0;
    //    }
    //
    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n) { (idx, u) => st(idx) = u - 1 }
        val ub = Array.fill[List[Int]](n)(Nil)
        input.forInts(n) { (idx, s) =>
          val un = st(idx)
          ub(un) ::= s
        }
        val uns = ub.filter(_.nonEmpty).map { l =>
          val ar = new Array[Long](l.length)
          val it = l.iterator
          for (i <- ar.indices) {
            ar(i) = it.next()
          }
          val arr = ar.sortBy(-_)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
          arr
        }
        for (k <- 1 to n) {
          var s = 0L
          uns.foreach { u =>
            val teams = u.length / k
            if (teams > 0) {
              s += u(teams * k - 1)
            }
          }
          out.print(s.toString)
          out.print(' ')
        }
        out.flush()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      if (buffer.nonEmpty) {
        println(buffer.result())
        buffer.clear()
      }
    }
  }

  class BufferedOutputPrinter extends OutputPrinter {
    private val buffer = new PrintWriter(System.out)

    override def print(c: Char): Unit = buffer.print(c)

    override def print(i: Int): Unit = buffer.print(i)

    override def print(s: String): Unit = buffer.print(s)

    override def endl(): Unit = buffer.println()

    override def flush(): Unit = {
      endl()
      buffer.flush()
    }
  }

}

import scala.collection.mutable.ArrayBuffer

object C {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
  //  val input = new InputReader(new StringReader(
  //    """4
  //    7
  //    1 2 1 2 1 2 1
  //    6 8 3 1 5 1 5
  //    10
  //    1 1 1 2 2 2 2 3 3 3
  //    3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
  //    6
  //    3 3 3 3 3 3
  //    5 9 6 7 9 7
  //    1
  //    1
  //    3083
  //    """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n) { (idx, u) => st(idx) = u - 1 }
        val ub = Array.fill[List[Int]](n)(Nil)
        input.forInts(n) { (idx, s) =>
          val un = st(idx)
          ub(un) ::= s
        }
        val uns = ub.filter(_.nonEmpty).map { l =>
          val arr = new ArrayBuffer[Long](l.length)
          l.foreach(arr += _.toLong)
          arr.sortBy(-_)
          var s = 0L
          for (len <- arr.indices) {
            s += arr(len)
            arr(len) = s
          }
          arr
        }
        for (k <- 1 to n) {
          var s = 0L
          uns.foreach { u =>
            val teams = u.length / k
            if (teams > 0) {
              s += u(teams * k - 1)
            }
          }
          out.print(s.toString)
          out.print(' ')
        }
        out.flush()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      println(buffer.result())
      buffer.clear()
    }
  }

}

object C {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
  //  val input = new InputReader(new StringReader(
  //    """4
  //7
  //1 2 1 2 1 2 1
  //6 8 3 1 5 1 5
  //10
  //1 1 1 2 2 2 2 3 3 3
  //3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
  //6
  //3 3 3 3 3 3
  //5 9 6 7 9 7
  //1
  //1
  //3083
  //"""))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    import scala.collection.mutable.ArrayBuffer

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val n = input.nextInt
        val st = new Array[Int](n)
        input.forInts(n) { (idx, u) => st(idx) = u - 1 }
        val ub = Array.fill[ArrayBuffer[Int]](n)(new ArrayBuffer[Int]())
        input.forInts(n) { (idx, s) =>
          val un = st(idx)
          ub(un) += s
        }
        val uns = ub.filter(_.nonEmpty).map(_.sortBy(s => -s))
        uns.foreach { u =>
          var s = 0
          for (len <- u.indices) {
            s += u(len)
            u(len) = s
          }
        }
        for (k <- 1 to n) {
          var s = 0
          uns.foreach { u =>
            val teams = u.length / k
            if (teams > 0) {
              s += u(teams * k - 1)
            }
          }
          out.print(s)
          out.print(' ')
        }
        out.flush()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      println(buffer.result())
      buffer.clear()
    }
  }

}


import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val Array(n, m) = readInts
  val students = for(_ <- 1 to n) yield reader.readLine()
  val bestGrades = students.transpose.map(_.max)
  def ans = students.count(_.zip(bestGrades).exists(x => x._1 == x._2))

  def main(args: Array[String]) {
    println(ans)
  }
}

import scala.collection.mutable.ListBuffer

object Solver {
    def main(args: Array[String]) {
        var input = Console.readLine.split(" ").map(_.toInt)
        var n = input(0); var m = input(1)

        var data: ListBuffer[Int] = new ListBuffer()
        for ( i <- 0 until m ) data.append(0)

        var estimates = List[Seq[Int]]()

        for (i <- 0 until n) {
            estimates = estimates ++ Array(Console.readLine.map(_.toInt - '0'.toInt))
            for (j <- 0 until m)
                if (estimates(i)(j) > data(j))
                    data(j) = estimates(i)(j)
        }

        var count = 0
        for (i <- 0 until n) {
            var continue = true
            for (j <- 0 until m)
                if (continue && estimates(i)(j) == data(j)) { count += 1; continue = false; }
        }

        println(count)
    }
}

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  val n = in.nextInt()
  val m = in.nextInt()
  in.nextLine()
  var grade = Array.ofDim[Int](n, m);
  for (i <- 0 until n) {
    var cur = in.nextLine()
    for (j <- 0 until m) {
      grade(i)(j) = cur(j) - '0'
    }
  }
  var student = Array.ofDim[Int](n);
  for (i <- 0 until m) {
    var best = -1
    for (j <- 0 until n) {
      if (grade(j)(i) > best) {
        best = grade(j)(i)
      }
    }
    for (j <- 0 until n) {
      if (grade(j)(i) == best) {
        student(j) += 1
      }
    }
  }
  var cnt = 0
  for (i <- 0 until n) {
    if (student(i) > 0) {
      cnt += 1
    }
  }
  println(cnt)
}

import java.util.StringTokenizer

object _152A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val m = next.toInt
  val a = (1 to n).map(i => next.map(ch => ch - '0').toArray).toArray

  val colMax = (0 until m).map(j => (0 until n).map(i => a(i)(j)).max).toArray
  val cb = (0 until n).filter(i => (0 until m).exists(j => a(i)(j) == colMax(j)))
  println(cb.size)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data = (1 to n).map(_ => in.next())
  val max = (0 until m).map(i => data.map(_(i)).max)
  println(data.count(el => el.zip(max).exists(t => t._1 == t._2)))
}

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

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

  val Array(n, m) = sc.nextLine.split(" ").map(_.toInt)
  val g = new Array[Array[Int]](n)
  for (i <- 0 until n)
    g(i) = sc.nextLine.toCharArray.map(_.asDigit)
  val s = Array.fill(n)(false)
  for (j <- 0 until m) {
    val max = (0 until n).map(g(_)(j)).max
    for (i <- 0 until n)
      if (g(i)(j) == max) s(i) = true
  }

  val answer = s.filter(identity[Boolean]).size

  out.println(answer)
  out.close
}

import collection.immutable.IndexedSeq
import java.io.BufferedReader
import java.util.StringTokenizer

/**
 *
 * @author Vladislav Isenbaev (vladislav.isenbaev@odnoklassniki.ru)
 */

object CF152A extends App {

  def solve() {
    val n = nextInt()
    val m = nextInt()
    val lines = for (i <- 0 until n) yield in.nextLine()
    val courses = lines.map(_.map(_ - '0')).transpose
    val cool = new Array[Boolean](n)
    for (marks <- courses) {
      val max = marks.max
      for (i <- 0 until n if marks(i) == max) cool(i) = true
    }
    println(cool.count(identity[Boolean]))
  }

  class Tokenizer(in: BufferedReader, pattern: String = " \t\n\r\f") {
    private def tokenizer = new StringTokenizer(_: String, pattern)

    var st: StringTokenizer = tokenizer("")

    def nextLine() = in.readLine()

    def nextToken(): String = {
      while (!st.hasMoreTokens) {
        val line = nextLine()
        if (line == null) return null
        st = tokenizer(line)
      }
      st.nextToken()
    }

    def next[A](f: String => A): A = f(nextToken())
  }

  implicit val in = new Tokenizer(Console.in)
  implicit def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
  implicit def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
  implicit def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
  implicit def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
  implicit def nextString()(implicit t: Tokenizer) = t.next(identity[String])

  def nextSeq[A](len: Int = nextInt())(implicit c: () => A): Seq[A] = for (i <- 0 until len) yield c()

  solve()

}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val Array(n, m) = readInts
  val students = for(_ <- 1 to n) yield reader.readLine()
  val bestGrades = students.transpose.map(_.max)
  def ans = students.count(_.view.zip(bestGrades.view).exists(x => x._1 == x._2))

  def main(args: Array[String]) {
    println(ans)
  }
}

object Main {
  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val n = nm(0)
    val m = nm(1)
    val marks = (1 to n).map(_ => readLine().map(c => (c - '0').toInt))
    val maxes = (0 until m).map(i => marks.map(_(i)).max)
    val count = marks.count(row => row.zip(maxes).count(t => t._1 == t._2) > 0)
    println(count)
  }
}


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

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

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

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

  def solve(): Unit = {
    val N = ni()
    out.println(N)
    out.println(map(N)(_ => 1).mkString(" "))
  }

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

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

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

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

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

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

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

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

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

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

object Main {

  def main(args: Array[String]) {
    val std = scala.io.StdIn
    val n = std.readLine().toInt
    println(n)
    for (i <- 0 until n) {
      print(1)
      if (i + 1 < n) {
        print(" ")
      }
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

object NumberSplit {

  @tailrec
  def step(n: Long, acc: Long): (Long, Long) = {
    if (acc == 0) (n, 1)
    else if (n % acc == 0) (n / acc, acc)
    else step(n, acc - 1)
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().toLong
    val s = if (n < 9) n - 1 else 9
    val (times, n1) = step(n, s)
    val res = List.fill(times.toInt)(n1)
    println(res.length)
    println(res.mkString(" "))
  }
}

object Main {
  def main(args: Array[String]) : Unit = {
    val n = readInt
    println(n)
    println(List.fill(n)(1).mkString(" "))
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

object NumberSplit {

  @tailrec
  def step(n: Long, res: List[Int], acc: Int): List[Int] = {
    if (n == 0 || acc == 0) {
      res
    } else {
      val ki = n / acc
      val kiRes = n % acc
      step(kiRes, res ++ List.fill(ki.toInt)(acc), acc - 1)
    }
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().toLong
    val res = step(n, List(), 9)
    println(res.length)
    println(res.mkString(" "))
  }
}

object Main {
  def main(args: Array[String]) : Unit = {
    val n = readInt
    println(1)
    println(List.fill(n)(1).mkString(" "))
  }
}

import scala.io.StdIn.readInt

object MyModule {
  def main(args: Array[String]) : Unit = {
    val n = readInt
    println(1)
    println(n)
  }
}

object Main {
  def main(args: Array[String]) : Unit = {
    val n = readInt
    println(List.fill(n)(1).mkString(" "))
  }
}


import java.util.Scanner
import java.util.StringTokenizer

object CF551C extends App {
  var token = new StringTokenizer("")
  def next() = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val n = next.toInt
  val m = next.toLong
  val a = (1 to n).map(_ => next.toLong)

  def ok(timeLimit: Long): Boolean = {
    var um, rd: Long = 0
    for (i <- n - 1 to 0 by -1) {
      if (a(i) <= rd)
        rd -= a(i)
      else {
        val each = timeLimit - i - 1
        if (each <= 0)
          return false
        val need = a(i) - rd
        val take = (need - 1) / each + 1
        um += take
        rd = take * each - need
      }
    }
    um <= m
  }

  var (le, ri) = (0.toLong, 1e15.toLong)
  while (le < ri) {
    val mid = (le + ri) / 2;
    if (ok(mid))
      ri = mid
    else
      le = mid + 1
  }
  println(le)
}

import java.util.Scanner

object CF551C extends App {
  var in = new Scanner(System.in)
  val n = in.nextInt()
  val m = in.nextLong()
  val a = (1 to n).map(_ => in.nextLong())
  var (le, ri) = (0.toLong, 1e15.toLong)
  while (le < ri) {
    val mid = (le + ri) / 2;
    var um, rd: Long = 0
    var ok = true
    for (i <- n - 1 to 0 by -1) {
      if (a(i) <= rd)
        rd -= a(i)
      else {
        val each = mid - i - 1
        if (each <= 0)
          ok = false
        else {
          val need = a(i) - rd
          val take = (need - 1) / each + 1
          um += take
          rd = take * each - need
        }
      }
    }
    if (ok && um <= m)
      ri = mid
    else
      le = mid + 1
  }
  println(le)
}

import java.util.Scanner
import java.util.StringTokenizer

object CF551C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

 val n = next.toInt
 val m = next.toLong
 val a = (1 to n).map(_ => next.toLong)

  // var in = new Scanner(System.in)
  // val n = in.nextInt()
  // val m = in.nextLong()
  // val a = (1 to n).map(_ => in.nextLong())
  var (le, ri) = (0.toLong, 1e15.toLong)
  while (le < ri) {
    val mid = (le + ri) / 2;
    var um, rd: Long = 0
    var ok = true
    for (i <- n - 1 to 0 by -1) {
      if (a(i) <= rd)
        rd -= a(i)
      else {
        val each = mid - i - 1
        if (each <= 0)
          ok = false
        else {
          val need = a(i) - rd
          val take = (need - 1) / each + 1
          um += take
          rd = take * each - need
        }
      }
    }
    if (ok && um <= m)
      ri = mid
    else
      le = mid + 1
  }
  println(le)
}


import scala.io.StdIn._
import scala.io._
import scala.math.abs;
object _1551A {

  def main(args: Array[String]): Unit = {
    var t = readInt()
    while (t > 0) {
      t -= 1
      val n = readInt()
      val temp = n / 3
      if(n % 3 == 0)println(temp + " " + temp)
      else if(n % 3 == 1)println((temp + 1) + " " + temp)
      else println(temp + " " + (temp + 1))
    }

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

import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }

    rep(StdIn.readInt) {

      def f(i: Int) {
        var twos = i / 3
        var ones = twos

        if (i % 3 == 2) twos += 1
        else if (i % 3 == 1) ones += 1

        println(s"${ones} ${twos}")
      }
      f(StdIn.readInt)

    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readInt()

    val (d, r)   = (n / 3, n % 3)
    val (c1, c2) = (d + (if (r == 1) 1 else 0), d + (if (r == 2) 1 else 0))

    println(s"$c1 $c2")
  }
}


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

object Main {

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

  private case class Graph(edges: Array[Array[Boolean]])

  private case class Edge(a: Int, b: Int, c: Int)

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts
    val tGraphs = Array.ofDim[Graph](m + 2)
    val edges = Range(0, m).map { _ =>
      val Array(x, y, z) = readInts
      Edge(x, y, z)
    }.toList

    edges.groupBy(_.c).foreach {
      case (index, es) =>
        val m = Array.ofDim[Boolean](n + 2, n + 2).map(_.map(_ => false))
        es.foreach { e => {
          m(e.a)(e.b) = true
          m(e.b)(e.a) = true
        }
        }
        tGraphs(index) = Graph(m)
    }

    val graphs = tGraphs.toList.filter(_ != null)

    val q = StdIn.readInt()
    for (_ <- Range(0, q)) {
      val Array(u, v) = readInts
      println(graphs.count(g => wave(g, u, v)))
    }
  }

  private def wave(g: Graph, start: Int, end: Int): Boolean = {
    val visited = mutable.Set[Int]()
    val toVisit = mutable.Queue[Int](start)

    while (toVisit.nonEmpty) {
      val next = toVisit.dequeue()
      if (next == end) return true
      visited.add(next)
      val nexts: Array[Int] = g.edges(next).zipWithIndex.filter(_._1).map(_._2).filter(!visited.contains(_))
      if (nexts contains end) return true
      toVisit.enqueue(nexts: _*)
    }
    false
  }
}

import scala.math._
import scala.collection.mutable.Map

object Graph extends App {

  type Vertex = Int
  type Graph = Map[Int, Map[Int, List[Vertex]]]
  type traversableGraph = Map[Int, List[Vertex]]
  def readGraph(n : Int, m : Int) : Graph = {
    val graph : Graph = Map[Int, Map[Int, List[Vertex]]]()
    var v : List[Int] = Nil

    for(i <- 1 to m) {
      graph(i) = Map[Int, List[Vertex]]()
      for(j <- 1 to n)
        graph(i)(j) = Nil
    }

    for(i <- 0 until m) {
    v = readLine.split(" ").map(_.toInt).toList

    graph(v(2))((v(0))) ++= List(v(1))
    graph(v(2))((v(1))) ++= List(v(0))

    }

    graph
  }

  def DFS(start : Vertex, g : traversableGraph) : List[Vertex] = {

  def DFS0(v: Vertex, visited: List[Vertex]): List[Vertex] = {
    if (visited.contains(v))
      visited
    else {
      val neighbours:List[Vertex] = g(v) filterNot visited.contains
      neighbours.foldLeft(v :: visited)((b,a) => DFS0(a,b))
    }
  }

    DFS0(start, List[Vertex]())
  }

  val dim = readLine.split(" ").map(_.toInt)
  val n = dim(0)
  val m = dim(1)
  val graph = readGraph(n, m)

  val q = readInt
  var u, v : Int = 0
  var qR : Array[Int] = Array[Int]()

  for(i <- 0 until q) {
    qR = readLine.split(" ").map(_.toInt)
    u = qR(0)
    v = qR(1)

   println((1 to m).map(x => if (DFS(u, graph(x)).contains(v)) 1 else 0).sum)
  }

}

import scala.collection.mutable.ArrayBuffer
import scala.util.Random

object Main extends App {

   class UF(card: Int) {
     val p = ArrayBuffer.range(0, card+1)

     def find(at: Int): Int = {
       if(p(at) == at) return at
       p(at) = find(p(at))
       return p(at)
     }

     def unite(from: Int, to: Int): Unit = {
       p(find(from)) = find(to)
     }

     def isConn(from: Int, to: Int): Boolean = {
       find(from) == find(to)
     }
   }

   val Array(n,m) = readLine.split(" ").map(_.toInt)
   val dots = (1 to m).map({ _ =>
      val Array(a,b,c) = readLine.split(" ").map(_.toInt)
      (a,b,c)
   })

   val colors = dots.map({ case (_,_,c) => c }).toSet.map((color: Int) => (color, new UF(n))).toMap

   dots.foreach({ case (a,b,c) =>
     colors.get(c).get.unite(a,b)
   })

   val q  = readInt
   (1 to q).foreach({ _ =>
      val Array(u,v) = readLine.split(" ").map(_.toInt)
      println(colors.map(_._2).filter(_.isConn(u,v)).size)
   })

}

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

/** B. Mr. Kitayuta's Colorful Graph
  * http://codeforces.com/contest/505/problem/B
  * @author Yuichiroh Matsubayashi
  *         Created on 15/01/19.
  */
object P505B {

  case class Edge(a: Int, b: Int, c: Int)

  case class Query(u: Int, v: Int)

  def main(args: Array[String]): Unit = {
    val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)

    val cs = mutable.Set[Int]()

    val edges = (Map[Int, Seq[(Int, Int)]]() /: (1 to m)) { (map, i) =>
      val Array(a, b, c) = StdIn.readLine().split(" ").map(_.toInt)
      cs.add(c)
      map + (a -> (map.getOrElse(a, Seq()) :+(b, c))) + (b -> (map.getOrElse(b, Seq()) :+(a, c)))
    }

    val q = StdIn.readInt()
    val queries = (1 to q) map { i =>
      val Array(u, v) = StdIn.readLine().split(" ").map(_.toInt)
      Query(u, v)
    }

    def search(start: Int, goal: Int, color: Int, visited: List[Int] = Nil): Boolean = edges.getOrElse(start, Seq()).exists { bc =>
      if (bc._2 == color) {
        if (visited.contains(bc._1)) false
        else if (bc._1 == goal) true
        else search(bc._1, goal, color, start :: visited)
      }
      else false
    }

    queries.map { q => cs.count { c => search(q.u, q.v, c) == true } }.foreach(println)
  }
}

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  val Array(n, m) = data.next().split(" ").map(_.toInt)
  val edges = Range(0, m).map(_ => data.next().split(" ").map(_.toInt)).groupBy(_(2)).map {
    case(color, data) => color -> data.foldLeft(scala.collection.mutable.Set.empty[scala.collection.mutable.Set[Int]]) {
      case (acc, el) =>
        val f1 = acc.find(_.contains(el(0)))
        val f2 = acc.find(_.contains(el(1)))
        if (f1.isEmpty && f2.isEmpty) acc += scala.collection.mutable.Set(el(0), el(1))
        else {
          if (f1.isEmpty) {
            acc -= f2.get
            acc + (f2.get + el(0))
          }
          else if (f2.isEmpty) {
            acc -= f1.get
            acc + (f1.get + el(1))
          }
          else {
            f1.get ++= f2.get
            acc -= f1.get
            acc -= f2.get
            acc + (f1.get ++ f2.get)
          }
        }
    }
  }.values.toList

  Range(0, data.next().toInt).foreach {_ =>
    val Array(a, b) = data.next().split(" ").map(_.toInt)
    println(edges.count{
      case(sets) => sets.exists(t => t.contains(a) && t.contains(b))
    })
  }
}

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  val Array(n, m) = data.next().split(" ").map(_.toInt)
  val edges = Range(0, m).map(_ => data.next().split(" ").map(_.toInt)).groupBy(_(2)).map {
    case(color, data) => color -> data.foldLeft(scala.collection.mutable.Set.empty[scala.collection.mutable.Set[Int]]) {
      case (acc, el) =>
        val f1 = acc.find(_.contains(el(0)))
        val f2 = acc.find(_.contains(el(1)))
        if (f1.isEmpty && f2.isEmpty) acc += scala.collection.mutable.Set(el(0), el(1))
        else {
          if (f1.isEmpty)
            f2.get += el(0)
          else if (f2.isEmpty)
            f1.get += el(1)
          else {
            f1.get ++= f2.get
            acc -= f2.get
          }
        }
        acc
    }
  }.values.toList

  Range(0, data.next().toInt).foreach {_ =>
    val Array(a, b) = data.next().split(" ").map(_.toInt)
    println(edges.count{
      case(sets) => sets.exists(t => t.contains(a) && t.contains(b))
    })
  }
}

object Solution extends App {
  val data = scala.io.Source.stdin.getLines()
  val Array(n, m) = data.next().split(" ").map(_.toInt)
  val edges = Range(0, m).map(_ => data.next().split(" ").map(_.toInt)).groupBy(_(2)).map {
    case(color, data) => color -> data.foldLeft(Set.empty[scala.collection.mutable.Set[Int]]) {
      case (acc, el) =>
        val f1 = acc.find(_.contains(el(0)))
        val f2 = acc.find(_.contains(el(1)))
        if (f1.isEmpty && f2.isEmpty) acc + scala.collection.mutable.Set(el(0), el(1))
        else {
          if (f1.isEmpty) {
            f2.get += el(0)
            acc
          }
          else if (f2.isEmpty) {
            f1.get += el(1)
            acc
          }
          else {
            f1.get ++= f2.get
            acc - f2.get
          }
        }
    }
  }.values.toList

  Range(0, data.next().toInt).foreach {_ =>
    val Array(a, b) = data.next().split(" ").map(_.toInt)
    println(edges.count{
      case(sets) => sets.exists(t => t.contains(a) && t.contains(b))
    })
  }
}


import scala.io.StdIn._

object ModuloSum {

  def add(current: Seq[Int],v: Int, m: Int) = {
    def mapper(i: Int) = (i+v)%m
    ((current.map(mapper) :+ v%m) ++ current).distinct
  }
  def main (args: Array[String]) {
    val l1 = readLine().split(" ")
    val N = l1(0).toInt
    val M = l1(1).toInt
    val l2 = readLine().split(" ").map(_.toInt)
    if (N>=M) println("YES")
    else {
      val t1 = l2.foldLeft(Seq[Int]()) {
        (B, i) => add(B, i, M)
      }
      if(t1.contains(0)) println("YES") else println("NO")
    }
  }
}

//package round319.b

import java.util.Scanner

/*
var n, m, i, j, cur, num: longint;
    cnt: array [0..1010] of longint;

begin
  fillchar(cnt, sizeof(cnt), 0);
  readln(n, m);
  for i := 1 to n do
  begin
    read(num);
    num := num mod m;
    for j := 0 to m - 1 do
    begin
      if ((cnt[j] = 0) or (cnt[j] = i)) then
        continue;
      cur := num + j;
      if (cur >= m) then
        cur := cur - m;
      if (cnt[cur] = 0) then
        cnt[cur] := i;
    end;
    cnt[num] := i;
    if (cnt[0] <> 0) then
    begin
      writeln('YES');
      halt;
    end;
  end;
  writeln('NO');
end.
 */

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

  val n = sc.nextInt
  val m = sc.nextInt
  val cnt = Array.fill(1010)(0)

  for(i <- 1 to n) {
    val num = sc.nextInt % m
    for(j <- 0 until m) {
      if(cnt(j) != 0 && cnt(j) != i) {
        val cur = (num + j) % m
        if(cnt(cur) == 0) {
          cnt(cur) = i
        }
      }
    }
    cnt(num) = i
    if(cnt(0) != 0) {
      println("YES")
      System.exit(0)
    }
  }

  println("NO")

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data: Array[Int] = in.next().split(" ").map(_.toInt % m)
  val groupped = data.groupBy(i => i).map(i => (i._1, i._2.length)).toArray

  def solution(data: Array[(Int, Int)], index: Int, sum: Int): Boolean = {
    if (sum == 0) true
    else if (index == data.length) false
    else
      solution(data, index + 1, sum) || (1 to groupped(index)._2).map(i => (i * groupped(index)._1) % m).toSet.exists{
        j => if (sum == -1) solution(data, index + 1, j) else solution(data, index + 1, (sum + j) % m)
      }
  }

  if (solution(groupped, 0, -1))
    println("YES")
  else
    println("NO")

}

import scala.io.StdIn._
object ModuloSum {
  def add(current: Seq[Int],v: Int, m: Int) = {
    def mapper(i: Int) = (i+v)%m
    ((current.map(mapper) :+ v) ++ current).distinct
  }
  def main (args: Array[String]) {
    val l1 = readLine().split(" ")
    val N = l1(0).toInt
    val M = l1(1).toInt
    val l2 = readLine().split(" ").map(_.toInt%M)
    val result = (if(N>=M) Seq(0) else l2.foldLeft(Seq[Int]()) { (B, i) => add(B, i, M)}).toSet(0)
    if(result) println("YES") else println("NO")
  }
}

import scala.io.StdIn._
object ModuloSum {
  def main (args: Array[String]) {
    val l1 = readLine().split(" ")
    val N = l1(0).toInt
    val M = l1(1).toInt
    val l2 = readLine().split(" ").map(_.toInt%M)
    def add(current: Seq[Int],v: Int) = {
      def mapper(i: Int) = (i+v)%M
      ((current.map(mapper) :+ v) ++ current).distinct
    }
    val result = (if(N>=M) Seq(0) else l2.foldLeft(Seq[Int]())(add)).toSet(0)
    if(result) println("YES") else println("NO")
  }
}

import scala.io.StdIn._
object ModuloSum {
  def main (args: Array[String]) {
    val l1 = readLine().split(" ")
    val N = l1(0).toInt
    val M = l1(1).toInt
    val l2 = readLine().split(" ").map(_.toInt%M)
    def add(current: Seq[Int],v: Int) = ((current.map(i => (i+v)%M) :+ v) ++ current).distinct
    if((if(N>=M) Seq(0) else l2.foldLeft(Seq[Int]())(add)).toSet(0)) println("YES") else println("NO")
  }
}

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

import scala.collection.mutable

object B {

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

  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)
    }
    return st.nextToken
  }

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

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

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val a = new Array[Int](n)
    val set = new mutable.HashSet[Int]()
    for (i <- 0 until n) {
      a(i) = nextInt % m
      for (s <- set.clone()) {
        set.add((s + a(i)) % m)
      }
      set.add(a(i))
      if (set.contains(0)) {
        out.println("YES")
        return 0
      }
    }
    out.println("NO")
    return 0
  }
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val A = readLine().split(" ").map(_.toLong)

  if (n > m) println("YES")
  else {
    val rest = Array.ofDim[Boolean](n + 1, m)

    for (i <- A.indices) {
      rest(i + 1)((A(i) % m).toInt) = true
      if (rest(i + 1)(0)) {
        println("YES")
        System.exit(0)
      }
    }

    for {
      i <- 0 until n
      r <- 0 until m
    } {
      if (rest(i)(r)) {
        rest(i + 1)(((r + A(i)) % m).toInt) = true
        rest(i + 1)(r) = true

        if (rest(i + 1)(0)) {
          println("YES")
          System.exit(0)
        }
      }
    }

    println("NO")
  }
}

import java.util.Scanner
import java.io._
import scala.io.StdIn._

object HelloWorld {
    def add(seqs:Seq[Int], v:Int, m:Int) : Seq[Int] = {
        ((seqs.map( e => (e+v)%m ) :+ v%m) ++ seqs).distinct
    }
    def main(args:Array[String]) {
        //val sc = new Scanner(System.in)
        val r = readLine().split(" ").map(_.toInt)
        val n = r(0)
        val m = r(1)
        val nums = readLine().split(" ").map(_.toInt)
        if(n>=m)println("YES")
        else
        {
            val seq = nums.foldLeft( Seq[Int]() )( add(_:Seq[Int], _:Int, m) )
            if(seq.contains(0))println("YES")
            else println("NO")
        }
    }
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

object CF577B {

   class InputReader(val stream: InputStream) {
     var st: StringTokenizer = new StringTokenizer("")
     val reader = new BufferedReader(new InputStreamReader(stream), 32768);

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

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

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

     def nextDouble: Double = {
       return next.toDouble
     }
   }

   def solve(in: InputReader, out: PrintStream): Unit = {
     val n = in.nextInt()
     val m = in.nextInt()
     val a = Array.fill(n)(in.nextInt())
     val modM : Array[Boolean]  = Array.fill(m)(false)
     for( x <- a) {
       val mask = Array.fill(m)(false)
       for( mod <- m-1 to 0 by -1)
         if ( modM(mod) == true)
           mask((mod + x) % m) = true
       mask(x %m) = true
       for(mod <- 0 to m-1) modM(mod) = modM(mod) || mask(mod)
       if ( modM(0) ) {
         out.println("YES")
         return
       }
     }
     out.println("NO")
   }

   def main(args: Array[String]): Unit = {
     val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
     var in = new InputReader(System.in)
     var out = System.out
     if ( !isOnlineJudge ) {
       in = new InputReader(new FileInputStream("input.txt"))
       out = new PrintStream(new FileOutputStream("output.txt"))
     }
     solve(in,out)
   }

 }

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

object CF577B {

   class InputReader(val stream: InputStream) {
     var st: StringTokenizer = new StringTokenizer("")
     val reader = new BufferedReader(new InputStreamReader(stream), 32768);

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

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

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

     def nextDouble: Double = {
       return next.toDouble
     }
   }

   def solve(in: InputReader, out: PrintStream): Unit = {
     val n = in.nextInt()
     val m = in.nextInt()
     val a = Array.fill(n)(in.nextInt())
     val modM : Array[Boolean]  = Array.fill(m)(false)
     for( x <- a) {
       for( mod <- 0 to m-1)
         if ( modM(mod) == true)
           modM((mod + x) % m) = true
       modM(x %m) = true
     }
     if ( modM(0) ) out.println("YES") else out.println("NO")
   }

   def main(args: Array[String]): Unit = {
     val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
     var in = new InputReader(System.in)
     var out = System.out
     if ( !isOnlineJudge ) {
       in = new InputReader(new FileInputStream("input.txt"))
       out = new PrintStream(new FileOutputStream("output.txt"))
     }
     solve(in,out)
   }

 }

//package round319.b

import java.util.Scanner

/*
var n, m, i, j, cur, num: longint;
    cnt: array [0..1010] of longint;

begin
  fillchar(cnt, sizeof(cnt), 0);
  readln(n, m);
  for i := 1 to n do
  begin
    read(num);
    num := num mod m;
    for j := 0 to m - 1 do
    begin
      if ((cnt[j] = 0) or (cnt[j] = i)) then
        continue;
      cur := num + j;
      if (cur >= m) then
        cur := cur - m;
      if (cnt[cur] = 0) then
        cnt[cur] := i;
    end;
    cnt[num] := i;
    if (cnt[0] <> 0) then
    begin
      writeln('YES');
      halt;
    end;
  end;
  writeln('NO');
end.
 */

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

  val n = sc.nextInt
  val m = sc.nextInt
  val cnt = Array.fill(1010)(0)

  for(i <- 1 to n) {
    val num = sc.nextInt % m
    for(j <- 0 until m) {
      if(cnt(j) != 0) {
        val cur = (num + j) % m
        if(cnt(cur) == 0) {
          cnt(cur) = i
        }
      }
    }
    cnt(num) = i
    if(cnt(0) != 0) {
      println("YES")
      System.exit(0)
    }
  }

  println("NO")

}

//package round319.b

import java.util.Scanner

/*
var n, m, i, j, cur, num: longint;
    cnt: array [0..1010] of longint;

begin
  fillchar(cnt, sizeof(cnt), 0);
  readln(n, m);
  for i := 1 to n do
  begin
    read(num);
    num := num mod m;
    for j := 0 to m - 1 do
    begin
      if ((cnt[j] = 0) or (cnt[j] = i)) then
        continue;
      cur := num + j;
      if (cur >= m) then
        cur := cur - m;
      if (cnt[cur] = 0) then
        cnt[cur] := i;
    end;
    cnt[num] := i;
    if (cnt[0] <> 0) then
    begin
      writeln('YES');
      halt;
    end;
  end;
  writeln('NO');
end.
 */

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

  val n = sc.nextInt
  val m = sc.nextInt
  val cnt = Array.fill(1010)(0)

  for(i <- 1 to n) {
    val num = sc.nextInt % m
    println("actual num: " + num)
    for(j <- 0 until m) {
      if(cnt(j) != 0 && cnt(j) != i) {
        val cur = (num + j) % m
        if(cnt(cur) == 0) {
          cnt(cur) = i
        }
      }
    }
    cnt(num) = i
    if(cnt(0) != 0) {
      println("YES")
      System.exit(0)
    }
  }

  println("NO")

}

//package round319.b

import java.util.Scanner

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

  val n = sc.nextInt
  val m = sc.nextInt

  val a = Array.fill(n)(0)

  for(i <- 0 until n) {
    a(i) = sc.nextInt
  }

  var mo = Vector.fill(m+1)(0)
  for(i <- 0 until n) {
    val idx = a(i) % m
    mo = mo.updated(idx, mo(idx) + 1)
  }

  def canCover(x: Int, moo: Vector[Int]): Boolean = {
    if(x == 0) true
    else if(moo(x) > 0) true
    else {
      for(i <- 0 until m) {
        if(moo(i) > 0) {
          val moo2 = moo.updated(i, moo(i) - 1)
          if(canCover((m + x - moo(i)) % m, moo2)) {
            return true
          }
        }
      }
      false
    }
  }

  println(if(canCover(m, mo)) "YES" else "NO")

//  println(mo.toList)

}

//package round319.b

import java.util.Scanner

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

  val n = sc.nextInt
  val m = sc.nextInt

  val a = Array.fill(n)(0)

  for(i <- 0 until n) {
    a(i) = sc.nextInt
  }

  var mo = Vector.fill(m+1)(0)
  for(i <- 0 until n) {
    val idx = a(i) % m
    mo = mo.updated(idx, mo(idx) + 1)
  }

  def canCover(x: Int, moo: Vector[Int]): Boolean = {
    if(x == 0) true
    else if(moo(x) > 0) true
    else {
      for(i <- 0 until m) {
        if(moo(i) > 0) {
          val moo2 = moo.updated(i, moo(i) - 1)
          if(canCover((m + x - moo(i)) % m, moo2)) {
            return true
          }
        }
      }
      false
    }
  }

  println(if(canCover(m, mo)) "YES" else "NO")
}

//package round319.b

import java.util.Scanner

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

  val n = sc.nextInt
  val m = sc.nextInt

  val a = Array.fill(n)(0)

  for(i <- 0 until n) {
    a(i) = sc.nextInt
  }

  var mo = Vector.fill(m+1)(0)
  for(i <- 0 until n) {
    val idx = a(i) % m
    mo = mo.updated(idx, mo(idx) + 1)
  }

  def canCover(x: Int, moo: Vector[Int]): Boolean = {
    if(x % m == 0) true
    else if(moo(x) > 0) true
    else {
      for(i <- 0 until m) {
        if(moo(i) > 0) {
          val moo2 = moo.updated(i, moo(i) - 1)
          if(canCover((m + x - moo(i)) % m, moo2)) {
            return true
          }
        }
      }
      false
    }
  }

  println(if(canCover(m, mo)) "YES" else "NO")
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data: Array[Int] = in.next().split(" ").map(_.toInt % m)
  val groupped = data.groupBy(i => i).map(i => (i._1, i._2.length)).toArray

  def solution(data: Array[(Int, Int)], index: Int, sum: Int): Boolean = {
    if (sum == 0) true
    else if (index == data.length) false
    else
      solution(data, index + 1, -1) || (1 to groupped(index)._2).map(i => (i * groupped(index)._1) % m).toSet.exists{
        j => if (sum == -1) solution(data, index + 1, j) else solution(data, index + 1, (sum + j) % m)
      }
  }

  if (solution(groupped, 0, -1))
    println("YES")
  else
    println("NO")

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toLong)
  val data = in.next().split(" ").map(_.toLong % m)
  val groupped: Map[Long, Long] = data.groupBy(t => t).map(t => (t._1, t._2.length % m))
  val dataArr = Array.ofDim[Long](m.toInt)
  groupped.foreach { case(a, count) =>
    dataArr(a.toInt) = count
  }

  val cache = scala.collection.mutable.Map.empty[(Int, Int), Boolean]

  def solution(position: Int, sum: Long, took: Boolean): Boolean = {
    if (sum == 0 && took)
      true
    else if (position >= m) false
    else if (dataArr(position) == 0)
      solution(position + 1, sum, took)
    else
      (0l to dataArr(position)).exists{i =>
        solution(position + 1, (sum + i * position) % m, took || i > 0)}
  }

  if (data.contains(0) || groupped.exists(_._2 == 0) || solution(0, 0, false)) {
    println("YES")
  } else {
    println("NO")
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt % m)
  val groupped: Map[Int, Int] = data.groupBy(t => t).map(t => (t._1, t._2.length % m))
  val dataArr = Array.ofDim[Int](m)
  groupped.foreach { case(a, count) =>
    dataArr(a) = count
  }

  val cache = scala.collection.mutable.Map.empty[(Int, Int), Boolean]

  def solution(position: Int, sum: Int, took: Boolean): Boolean = {
    if (sum == 0 && took)
        true
    else if (position >= m) false
    else if (dataArr(position) == 0)
      solution(position + 1, sum, took)
    else
      (0 to dataArr(position)).exists{i =>
        solution(position + 1, (sum + i * position) % m, took || i > 0)}
  }

  if (data.contains(0) || groupped.exists(_._2 == 0) || solution(0, 0, false)) {
    println("YES")
  } else {
    println("NO")
  }

}

import scala.io.StdIn._

object ModuloSum {

  def add(current: Seq[Int],v: Int, m: Int) = {
    def mapper(i: Int) = (i+v)%m
    ((current.map(mapper) :+ v) ++ current).distinct
  }
  def main (args: Array[String]) {
    val l1 = readLine().split(" ")
    val N = l1(0).toInt
    val M = l1(1).toInt
    val l2 = readLine().split(" ").map(_.toInt)
    if (N>=M) println("YES")
    else {
      val t1 = l2.foldLeft(Seq[Int]()) {
        (B, i) => add(B, i, M)
      }
      if(t1.contains(0)) println("YES") else println("NO")
    }
  }
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val A = readLine().split(" ").map(_.toLong)

  if (n > m) println("YES")
  else {
    val rest = Array.ofDim[Boolean](n + 1, m)

    for (i <- A.indices) {
      rest(i + 1)((A(i) % m).toInt) = true
    }

    for {
      i <- 0 until n
      r <- 0 until m
    } {
      if (rest(i)(r)) {
        rest(i + 1)(((r + A(i)) % m).toInt) = true
        rest(i + 1)(r) = true

        if (rest(i + 1)(0)) {
          println("YES")
          System.exit(0)
        }
      }
    }
  }

  println("NO")
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val A = readLine().split(" ").map(_.toLong)

  if (n > m) println("YES")
  else {
    val rest = Array.ofDim[Boolean](n + 1, m)

    for (i <- A.indices) {
      rest(i + 1)((A(i) % m).toInt) = true
      if (rest(i + 1)(0)) {
        println("YES")
        System.exit(0)
      }
    }

    for {
      i <- 0 until n
      r <- 0 until m
    } {
      if (rest(i)(r)) {
        rest(i + 1)(((r + A(i)) % m).toInt) = true
        rest(i + 1)(r) = true

        if (rest(i + 1)(0)) {
          println("YES")
          System.exit(0)
        }
      }
    }
  }

  println("NO")
}

import scala.io.StdIn._

object B extends App {
  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val A = readLine().split(" ").map(_.toLong)

  def sum(current: Long, array: Array[Long]): Boolean = {
    if (current > 0 && current % m == 0) true
    else if (array.isEmpty) false
    else {
      sum(current + array.head, array.tail) ||
        sum(current, array.tail)
    }
  }

  println(if (sum(0, A)) "YES" else "NO")

}

import scala.io.StdIn._

object B extends App {
  val A = Array(1, 2, 3)
  val m = 5

  def sum(current: Int, array: Array[Int]): Boolean = {
    if (current > 0 && current % m == 0) true
    else if (array.isEmpty) false
    else {
      sum(current + array.head, array.tail) ||
        sum(current, array.tail)
    }
  }

  println(if (sum(0, A)) "YES" else "NO")

}