Polycarp is an organizer of a Berland ICPC regional event. There are $$$n$$$ universities in Berland numbered from $$$1$$$ to $$$n$$$. Polycarp knows all competitive programmers in the region. There are $$$n$$$ students: the $$$i$$$-th student is enrolled at a university $$$u_i$$$ and has a programming skill $$$s_i$$$.Polycarp has to decide on the rules now. In particular, the number of members in the team.Polycarp knows that if he chooses the size of the team to be some integer $$$k$$$, each university will send their $$$k$$$ strongest (with the highest programming skill $$$s$$$) students in the first team, the next $$$k$$$ strongest students in the second team and so on. If there are fewer than $$$k$$$ students left, then the team can't be formed. Note that there might be universities that send zero teams.The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is $$$0$$$.Help Polycarp to find the strength of the region for each choice of $$$k$$$ from $$$1$$$ to $$$n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of universities and the number of students. The second line of each testcase contains $$$n$$$ integers $$$u_1, u_2, \dots, u_n$$$ ($$$1 \le u_i \le n$$$) — the university the $$$i$$$-th student is enrolled at. The third line of each testcase contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$) — the programming skill of the $$$i$$$-th student. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print $$$n$$$ integers: the strength of the region — the total skill of the members of the present teams — for each choice of team size $$$k$$$.

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

}


Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.Your task is to find the number of successful students in the group.

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of students and the number of subjects, correspondingly. Next n lines each containing m characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.

Print the single number — the number of successful students in the given group.

NoteIn the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.In the second sample test each student is the best at at least one subject.

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

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

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


You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.How many operations will you need to perform until the next operation does not have any points to delete?

Input contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc. The number of the points is between 1 and 106.

Output one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.

NoteIn the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied.

import scala.collection.mutable.ArrayBuffer

object D extends App {

  case class Segment(var n: Int, c: Char)

  val s = readLine

  var prev = '-'
  var sameCount = 0
  val segments = ArrayBuffer.empty[Segment]

  for (c <- s) {
    if (c == prev) {
      sameCount += 1
    } else {
      if (sameCount > 0) segments += Segment(sameCount, prev)
      prev = c
      sameCount = 1
    }
  }

  segments += Segment(sameCount, prev)

  var res = 0

  while (segments.size > 1) {

    res += 1

    segments.head.n -= 1
    segments.last.n -= 1
    for (i <- 1 until segments.size - 1) segments(i).n -= 2

    val nonEmptySegments = segments.filter(_.n > 0)

    segments.clear()
    for (segment <- nonEmptySegments) {
      if (segments.isEmpty || segments.last.c != segment.c) {
        segments += segment
      } else {
        segments.last.n += segment.n
      }
    }
  }

  println(res)
}


Vasya has his favourite number $$$n$$$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $$$d_1, d_2, \ldots, d_k$$$, such that $$$1 \leq d_i \leq 9$$$ for all $$$i$$$ and $$$d_1 + d_2 + \ldots + d_k = n$$$.Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $$$d_1, d_2, \ldots, d_k$$$. Help him!

The first line contains a single integer $$$n$$$ — the number that Vasya wants to split ($$$1 \leq n \leq 1000$$$).

In the first line print one integer $$$k$$$ — the number of digits in the partition. Note that $$$k$$$ must satisfy the inequality $$$1 \leq k \leq n$$$. In the next line print $$$k$$$ digits $$$d_1, d_2, \ldots, d_k$$$ separated by spaces. All digits must satisfy the inequalities $$$1 \leq d_i \leq 9$$$. You should find a partition of $$$n$$$ in which the number of different digits among $$$d_1, d_2, \ldots, d_k$$$ will be minimal possible among all partitions of $$$n$$$ into non-zero digits. Among such partitions, it is allowed to find any. It is guaranteed that there exists at least one partition of the number $$$n$$$ into digits.

NoteIn the first test, the number $$$1$$$ can be divided into $$$1$$$ digit equal to $$$1$$$.In the second test, there are $$$3$$$ partitions of the number $$$4$$$ into digits in which the number of different digits is $$$1$$$. This partitions are $$$[1, 1, 1, 1]$$$, $$$[2, 2]$$$ and $$$[4]$$$. Any of these partitions can be found. And, for example, dividing the number $$$4$$$ to the digits $$$[1, 1, 2]$$$ isn't an answer, because it has $$$2$$$ different digits, that isn't the minimum possible number.

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


Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: If i ≠ n, move from pile i to pile i + 1; If pile located at the position of student is not empty, remove one box from it.GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed.

The first line contains two integers n and m (1 ≤ n, m ≤ 105), the number of piles of boxes and the number of GukiZ's students.  The second line contains n integers a1, a2, ... an (0 ≤ ai ≤ 109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty.

In a single line, print one number, minimum time needed to remove all the boxes in seconds.

NoteFirst sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second).Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds.Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished.

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


Polycarp must pay exactly $$$n$$$ burles at the checkout. He has coins of two nominal values: $$$1$$$ burle and $$$2$$$ burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other.Thus, Polycarp wants to minimize the difference between the count of coins of $$$1$$$ burle and $$$2$$$ burles being used. Help him by determining two non-negative integer values $$$c_1$$$ and $$$c_2$$$ which are the number of coins of $$$1$$$ burle and $$$2$$$ burles, respectively, so that the total value of that number of coins is exactly $$$n$$$ (i. e. $$$c_1 + 2 \cdot c_2 = n$$$), and the absolute value of the difference between $$$c_1$$$ and $$$c_2$$$ is as little as possible (i. e. you must minimize $$$|c_1-c_2|$$$).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line. This line contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the number of burles to be paid by Polycarp.

For each test case, output a separate line containing two integers $$$c_1$$$ and $$$c_2$$$ ($$$c_1, c_2 \ge 0$$$) separated by a space where $$$c_1$$$ is the number of coins of $$$1$$$ burle and $$$c_2$$$ is the number of coins of $$$2$$$ burles. If there are multiple optimal solutions, print any one.

NoteThe answer for the first test case is "334 333". The sum of the nominal values of all coins is $$$334 \cdot 1 + 333 \cdot 2 = 1000$$$, whereas $$$|334 - 333| = 1$$$. One can't get the better value because if $$$|c_1 - c_2| = 0$$$, then $$$c_1 = c_2$$$ and $$$c_1 \cdot 1 + c_1 \cdot 2 = 1000$$$, but then the value of $$$c_1$$$ isn't an integer.The answer for the second test case is "10 10". The sum of the nominal values is $$$10 \cdot 1 + 10 \cdot 2 = 30$$$ and $$$|10 - 10| = 0$$$, whereas there's no number having an absolute value less than $$$0$$$.

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


Mr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.Mr. Kitayuta wants you to process the following q queries.In the i-th query, he gives you two integers — ui and vi.Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.

The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), denoting the number of the vertices and the number of the edges, respectively. The next m lines contain space-separated three integers — ai, bi (1 ≤ ai < bi ≤ n) and ci (1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj). The next line contains a integer — q (1 ≤ q ≤ 100), denoting the number of the queries. Then follows q lines, containing space-separated two integers — ui and vi (1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.

For each query, print the answer in a separate line.

NoteLet's consider the first sample.     The figure above shows the first sample.    Vertex 1 and vertex 2 are connected by color 1 and 2.  Vertex 3 and vertex 4 are connected by color 3.  Vertex 1 and vertex 4 are not connected by any single color.

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

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

}

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


You are given a sequence of numbers a1, a2, ..., an, and a number m.Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.

The first line contains two numbers, n and m (1 ≤ n ≤ 106, 2 ≤ m ≤ 103) — the size of the original sequence and the number such that sum should be divisible by it. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).

In the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.

NoteIn the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.In the third sample test you need to choose two numbers 3 on the ends.In the fourth sample test you can take the whole subsequence.

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

 }

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

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.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")

}


One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $$$s$$$ towards a faraway galaxy. Recently they've received a response $$$t$$$ which they believe to be a response from aliens! The scientists now want to check if the signal $$$t$$$ is similar to $$$s$$$.The original signal $$$s$$$ was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal $$$t$$$, however, does not look as easy as $$$s$$$, but the scientists don't give up! They represented $$$t$$$ as a sequence of English letters and say that $$$t$$$ is similar to $$$s$$$ if you can replace all zeros in $$$s$$$ with some string $$$r_0$$$ and all ones in $$$s$$$ with some other string $$$r_1$$$ and obtain $$$t$$$. The strings $$$r_0$$$ and $$$r_1$$$ must be different and non-empty.Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings $$$r_0$$$ and $$$r_1$$$) that transform $$$s$$$ to $$$t$$$.

The first line contains a string $$$s$$$ ($$$2 \le |s| \le 10^5$$$) consisting of zeros and ones — the original signal. The second line contains a string $$$t$$$ ($$$1 \le |t| \le 10^6$$$) consisting of lowercase English letters only — the received signal. It is guaranteed, that the string $$$s$$$ contains at least one '0' and at least one '1'.

Print a single integer — the number of pairs of strings $$$r_0$$$ and $$$r_1$$$ that transform $$$s$$$ to $$$t$$$. In case there are no such pairs, print $$$0$$$.

NoteIn the first example, the possible pairs $$$(r_0, r_1)$$$ are as follows:  "a", "aaaaa"  "aa", "aaaa"  "aaaa", "aa"  "aaaaa", "a"  The pair "aaa", "aaa" is not allowed, since $$$r_0$$$ and $$$r_1$$$ must be different.In the second example, the following pairs are possible:   "ko", "kokotlin"  "koko", "tlin"

object E 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, t = readLine

  val n = t.length
  val PRIME = 1303L
  val MOD = 1000000007L
  val MODB = BigInt(MOD)
  var pmul = 1L

  val ps, pinvs = Array.ofDim[Long](n + 1)
  val hs = Array.ofDim[Long](n + 1)

  var h = 0L
  for (i <- 0 to t.length) {
    ps(i) = pmul
    pinvs(i) = BigInt(pmul).modInverse(MODB).toLong
    hs(i) = h
    if (i < n) h = (h + t(i) * pmul) % MOD
    pmul = pmul * PRIME % MOD
  }

  def hash(from: Int, until: Int) = (hs(until) - hs(from) + MOD) * pinvs(from) % MOD

  val zeros = s.count(_ == '0')
  val ones = s.count(_ == '1')
  val firstZero = s.indexOf('0')
  val firstOne = s.indexOf('1')

  var res = 0L

  var r0len = 1
  while (r0len <= n) {
    val remain = n.toLong - zeros.toLong * r0len
    if (remain > 0 && remain % ones == 0) {
      val r1len = (remain / ones).toInt
      val r0pos = firstZero * r1len
      val r1pos = firstOne * r0len
      if (r0pos + r0len <= n && r1pos + r1len <= n) {
        val r0hash = hash(r0pos, r0pos + r0len)
        val r1hash = hash(r1pos, r1pos + r1len)
        if (r0hash != r1hash) {
          var pos = 0
          var i = 0
          var ok = true
          while (i < s.length && ok) {
            if (s(i) == '0') {
              if (hash(pos, pos + r0len) != r0hash) ok = false
              pos += r0len
            } else {
              if (hash(pos, pos + r1len) != r1hash) ok = false
              pos += r1len
            }
            i += 1
          }
          //println(r0len, r1len, r0hash, r1hash, ok)
          if (ok) res += 1
        }
      }
    }
    r0len += 1
  }

  println(res)
}