You are given a table $$$a$$$ of size $$$n \times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \cdot m + j$$$, that is $$$a_{ij} = (i - 1) \cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.  For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$$$ and $$$(1, 1) \rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^4$$$) — the number of rows and columns of the table $$$a$$$ respectively.

For each test case output a single integer — a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.

NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table.

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.max
  import scala.List

  val n = readInt()

  for (i <- 1 to n){
    val x = readLine().split(" ").map(_.toLong)
    val y = x(1) * (x(1)+1) / 2 + x(0) * ( x(0) - 1) * x(1) / 2 + (x(0) -1) * x(1)
    println(y)
  }
}


You are given a tree (a connected undirected graph without cycles) of $$$n$$$ vertices. Each of the $$$n - 1$$$ edges of the tree is colored in either black or red.You are also given an integer $$$k$$$. Consider sequences of $$$k$$$ vertices. Let's call a sequence $$$[a_1, a_2, \ldots, a_k]$$$ good if it satisfies the following criterion:  We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $$$a_1$$$ and ending at $$$a_k$$$.  Start at $$$a_1$$$, then go to $$$a_2$$$ using the shortest path between $$$a_1$$$ and $$$a_2$$$, then go to $$$a_3$$$ in a similar way, and so on, until you travel the shortest path between $$$a_{k-1}$$$ and $$$a_k$$$. If you walked over at least one black edge during this process, then the sequence is good.   Consider the tree on the picture. If $$$k=3$$$ then the following sequences are good: $$$[1, 4, 7]$$$, $$$[5, 5, 3]$$$ and $$$[2, 3, 7]$$$. The following sequences are not good: $$$[1, 4, 6]$$$, $$$[5, 5, 5]$$$, $$$[3, 7, 3]$$$.There are $$$n^k$$$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $$$10^9+7$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$2 \le k \le 100$$$), the size of the tree and the length of the vertex sequence. Each of the next $$$n - 1$$$ lines contains three integers $$$u_i$$$, $$$v_i$$$ and $$$x_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$x_i \in \{0, 1\}$$$), where $$$u_i$$$ and $$$v_i$$$ denote the endpoints of the corresponding edge and $$$x_i$$$ is the color of this edge ($$$0$$$ denotes red edge and $$$1$$$ denotes black edge).

Print the number of good sequences modulo $$$10^9 + 7$$$.

NoteIn the first example, all sequences ($$$4^4$$$) of length $$$4$$$ except the following are good:   $$$[1, 1, 1, 1]$$$ $$$[2, 2, 2, 2]$$$ $$$[3, 3, 3, 3]$$$ $$$[4, 4, 4, 4]$$$ In the second example, all edges are red, hence there aren't any good sequences.

//package codeforces.contest1139

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {
    val setX: Set[Int] = graph.getOrElse(x, Set())
    val setY: Set[Int] = graph.getOrElse(y, Set())

    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def addSingleVertices(graph: Graph, v: List[Int]): Graph = {
    v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))
  }

  def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {
    for {
      neighbors <- graph.get(v)
      neighbor <- neighbors
      if neighbor != p
    } {
      set += neighbor
      connectedVertexSet(neighbor, v)
    }
  }

  def connectedVertexSet(v: Int, p: Int, set: Set[Int])(implicit graph: Graph): Set[Int] = {
    graph.get(v).map(neighbors => neighbors.filter(_ != p).foldLeft(set + v)((res, neighbor) => connectedVertexSet(neighbor, v, res)))
      .getOrElse(set + v)
  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          //          val vertexSet = collection.mutable.Set[Int](root)
          //          connectedVertexSet(root, -1)(graph, vertexSet)
          val vertexSet = connectedVertexSet(root, -1, Set[Int]())(graph)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      val g = addSingleVertices(graph, List(x, y))
      if (color == 0)
        addBidirectionalEdge(g, x, y, color == 1)
      else
        g
    }

    val connectedComponentsSizes = connectedComponentSizesList(graph)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}

//package codeforces.contest1139

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {
    val setX: Set[Int] = graph.getOrElse(x, Set())
    val setY: Set[Int] = graph.getOrElse(y, Set())

    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def addSingleVertices(graph: Graph, v: List[Int]): Graph = {
    v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))
  }

  def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {
    for {
      neighbors <- graph.get(v)
      neighbor <- neighbors
      if neighbor != p
    } {
      set += neighbor
      connectedVertexSet(neighbor, v)
    }
  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          val vertexSet = collection.mutable.Set[Int](root)
          connectedVertexSet(root, -1)(graph, vertexSet)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    //    val graph = collection.mutable.Map[Int, Set[Int]]()
    //
    //    1 until n foreach (_ => {
    //      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
    //      graph += (x -> graph.getOrElse(x, Set())) += (y -> graph.getOrElse(y, Set()))
    //
    //      if (color == 0) {
    //        val setX: Set[Int] = graph.getOrElse(x, Set())
    //        val setY: Set[Int] = graph.getOrElse(y, Set())
    //
    //        graph += (x -> (setX + y)) += (y -> (setY + x))
    //      }
    //
    //    })

    val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      val g = addSingleVertices(graph, List(x, y))
      if (color == 0)
        addBidirectionalEdge(g, x, y, color == 1)
      else
        g
    }

    val connectedComponentsSizes = connectedComponentSizesList(graph.toMap)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}

//package codeforces.contest1139

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {
    for {
      neighbors <- graph.get(v)
      neighbor <- neighbors
      if neighbor != p
    } {
      set += neighbor
      connectedVertexSet(neighbor, v)
    }
  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          val vertexSet = collection.mutable.Set[Int](root)
          connectedVertexSet(root, -1)(graph, vertexSet)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    val graph = collection.mutable.Map[Int, Set[Int]]()

    1 until n foreach (_ => {
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      graph += (x -> graph.getOrElse(x, Set())) += (y -> graph.getOrElse(y, Set()))

      if (color == 0) {
        val setX: Set[Int] = graph.getOrElse(x, Set())
        val setY: Set[Int] = graph.getOrElse(y, Set())

        graph += (x -> (setX + y)) += (y -> (setY + x))
      }

    })

    //    (1 until n).foldLeft(graph) { case (graph: Graph, _) =>
    //      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
    //      val g = addSingleVertices(graph, List(x, y))
    //      if (color == 0)
    //        addBidirectionalEdge(g, x, y, color == 1)
    //      else
    //        g
    //    }

    val connectedComponentsSizes = connectedComponentSizesList(graph.toMap)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}

//package codeforces.contest1139

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {
    val setX: Set[Int] = graph.getOrElse(x, Set())
    val setY: Set[Int] = graph.getOrElse(y, Set())

    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def addSingleVertices(graph: Graph, v: List[Int]): Graph = {
    v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))
  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          val vertexSet = connectedVertexSet(root, graph)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def connectedVertexSet(v: Int, graph: Graph): Set[Int] = {
    def connectedVertexSet(v: Int, p: Int, set: Set[Int] = Set()): Set[Int] =
      graph.get(v).map(_.filter(_ != p).foldLeft(set + v)((res, neighbor) => connectedVertexSet(neighbor, v, res))).getOrElse(set + v)

    connectedVertexSet(v, -1)
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      val g = addSingleVertices(graph, List(x, y))
      if (color == 0)
        addBidirectionalEdge(g, x, y, color == 1)
      else
        g
    }

    val connectedComponentsSizes = connectedComponentSizesList(graph)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}

//package codeforces.contest1139
import scala.collection.immutable.TreeSet

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {
    val setX: Set[Int] = graph.getOrElse(x, Set())
    val setY: Set[Int] = graph.getOrElse(y, Set())

    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def addSingleVertices(graph: Graph, v: List[Int]): Graph = {
    v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))
  }

  def connectedVertexSet(v: Int, p: Int, set: Set[Int])(implicit graph: Graph): Set[Int] = {
    graph.get(v).map(neighbors => neighbors.filter(_ != p).foldLeft(set + v)((res, neighbor) => connectedVertexSet(neighbor, v, res)))
      .getOrElse(set + v)
  }

//  def connectedComponentSizesList(graph: Graph): List[Int] = {
//    graph.keySet.foldLeft((TreeSet[Int](), List[Int]())) {
//      case ((visited: Set[Int], result: List[Int]), root: Int) =>
//        if (!visited(root)) {
//          val vertexSet = connectedVertexSet(root, -1, Set[Int]())(graph)
//          (visited ++ vertexSet, vertexSet.size :: result)
//        } else
//          (visited, result)
//    }._2
//  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          //          val vertexSet = collection.mutable.Set[Int](root)
          //          connectedVertexSet(root, -1)(graph, vertexSet)
          val vertexSet = connectedVertexSet(root, -1, Set[Int]())(graph)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      val g = addSingleVertices(graph, List(x, y))
      if (color == 0)
        addBidirectionalEdge(g, x, y, color == 1)
      else
        g
    }

    val connectedComponentsSizes = connectedComponentSizesList(graph)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}

//package codeforces.contest1139

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {
    val setX: Set[Int] = graph.getOrElse(x, Set())
    val setY: Set[Int] = graph.getOrElse(y, Set())

    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def addSingleVertices(graph: Graph, v: List[Int]): Graph = {
    v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))
  }

  def connectedVertexSet(root: Int, graph: Graph): Set[Int] = {
    def connectedVertexSet(v: Int, p: Int)(implicit set: collection.mutable.Set[Int]): Unit= {
      for {
        neighbors <- graph.get(v)
        neighbor <- neighbors
        if neighbor != p
      } {
        set += neighbor
        connectedVertexSet(neighbor, v)
      }
    }

    val result = collection.mutable.Set[Int](root)
    connectedVertexSet(root, -1)(result)
    result.toSet
  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          val vertexSet = connectedVertexSet(root, graph)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      val g = addSingleVertices(graph, List(x, y))
      if (color == 0)
        addBidirectionalEdge(g, x, y, color == 1)
      else
        g
    }

    val connectedComponentsSizes = connectedComponentSizesList(graph)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}

//package codeforces.contest1139

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {
    val setX: Set[Int] = graph.getOrElse(x, Set())
    val setY: Set[Int] = graph.getOrElse(y, Set())

    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def addSingleVertices(graph: Graph, v: List[Int]): Graph = {
    v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))
  }

  def connectedVertexSet(v: Int, p: Int)(implicit graph: Graph, set: collection.mutable.Set[Int]): Unit = {
    for {
      neighbors <- graph.get(v)
      neighbor <- neighbors
      if neighbor != p
    } {
      set += neighbor
      connectedVertexSet(neighbor, v)
    }
  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          val vertexSet = collection.mutable.Set[Int](root)
          connectedVertexSet(root, -1)(graph, vertexSet)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      val g = addSingleVertices(graph, List(x, y))
      if (color == 0)
        addBidirectionalEdge(g, x, y, color == 1)
      else
        g
    }

    val connectedComponentsSizes = connectedComponentSizesList(graph)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}

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 java.util.Arrays

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

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

  def solve(): Unit = {
    val N, K = ni()
    val uf = new UnionFind(N)
    REP(N - 1) { _ =>
      val from, to = ni() - 1
      val c = ni()
      if (c == 0) uf.unite(from, to)
    }

    val C = Array.ofDim[Int](N)
    REP(N) { i =>
      C(uf.find(i)) += 1
    }

    var minus = 0L
    REP(N) { i =>
      if (C(i) > 0) {
        // longを超えないだろ
        minus += powMod(C(i), K, MOD)
      }
    }

    val ans = (MOD + powMod(N, K, MOD) - minus % MOD) % MOD
    out.println(ans)
  }

  def powMod(x: Int, n: Int, m: Int): Int = {
    def step(x: Long, n: Int, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1).toInt
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    REP(n) (i => par(i) = i)
    val rank: Array[Int] = Array.fill[Int](n)(1) // 集合の要素数
    private val visits = Array.ofDim[Int](n) // 訪れた場所をfind毎に用意するのがもったいないのでつかいまわす

    def find(x: Int): Int = {
      var ptr = 0
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          visits(ptr) = x
          ptr += 1
          step(par(x))
        }
      }

      val res = step(x)
      REP(ptr){ i => par(visits(i)) = res }
      res
    }

    def unite(x: Int, y: Int): Int = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 == y1) x1
      else {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
          y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += rank(y1)
          x1
        }
      }
    }

    /**
      * xを解決する必要がないときは直にrankをみる
      */
    def cntNodes(x: Int): Int = rank(find(x))
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }

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

//package codeforces.contest1139

object EdgyTrees {
  type Graph = Map[Int, Set[Int]]

  def addBidirectionalEdge(graph: Graph, x: Int, y: Int, color: Boolean): Graph = {
    val setX: Set[Int] = graph.getOrElse(x, Set())
    val setY: Set[Int] = graph.getOrElse(y, Set())

    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def addSingleVertices(graph: Graph, v: List[Int]): Graph = {
    v.foldLeft(graph)((g, v) => g + (v -> g.getOrElse(v, Set())))
  }

  def connectedVertexSet(v: Int, graph: Graph): Set[Int] = {
    def connectedVertexSet(v: Int, p: Int)(implicit set: collection.mutable.Set[Int]): Unit= {
      for {
        neighbors <- graph.get(v)
        neighbor <- neighbors
        if neighbor != p
      } {
        set += neighbor
        connectedVertexSet(neighbor, v)
      }
    }

    val result = collection.mutable.Set[Int]()
    connectedVertexSet(v, -1)(result)
    result.toSet
  }

  def connectedComponentSizesList(graph: Graph): List[Int] = {
    val visited = collection.mutable.Set[Int]()
    graph.keySet.foldLeft(List[Int]()) {
      case (result: List[Int], root: Int) =>
        if (!visited(root)) {
          val vertexSet = connectedVertexSet(root, graph)
          visited ++= vertexSet
          vertexSet.size :: result
        } else result
    }
  }

  def power(n: Int, k: Int, mod: Int): Int = {
    (1 to k).foldLeft(1l)((res, _) => (res * n) % mod).toInt
  }

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

    val graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { case (graph: Graph, _) =>
      val Array(x, y, color) = io.StdIn.readLine().split(" ").map(_.toInt)
      val g = addSingleVertices(graph, List(x, y))
      if (color == 0)
        addBidirectionalEdge(g, x, y, color == 1)
      else
        g
    }

    val connectedComponentsSizes = connectedComponentSizesList(graph)

    val mod = 1000000007

    val result = power(n, k, mod) - connectedComponentsSizes.foldLeft(0l)((res, size) => (res + power(size, k, mod)) % mod) // n^k - sigma p^k

    println(if (result < 0) result + mod else result)
  }
}


Suppose you have a special $$$x$$$-$$$y$$$-counter. This counter can store some value as a decimal number; at first, the counter has value $$$0$$$. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either $$$x$$$ or $$$y$$$ to its value. So all sequences this counter generates are starting from $$$0$$$. For example, a $$$4$$$-$$$2$$$-counter can act as follows:  it prints $$$0$$$, and adds $$$4$$$ to its value, so the current value is $$$4$$$, and the output is $$$0$$$;  it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$8$$$, and the output is $$$04$$$;  it prints $$$8$$$, and adds $$$4$$$ to its value, so the current value is $$$12$$$, and the output is $$$048$$$;  it prints $$$2$$$, and adds $$$2$$$ to its value, so the current value is $$$14$$$, and the output is $$$0482$$$;  it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$18$$$, and the output is $$$04824$$$. This is only one of the possible outputs; for example, the same counter could generate $$$0246802468024$$$ as the output, if we chose to add $$$2$$$ during each step.You wrote down a printed sequence from one of such $$$x$$$-$$$y$$$-counters. But the sequence was corrupted and several elements from the sequence could be erased.Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string $$$s$$$ — the remaining data of the sequence. For all $$$0 \le x, y < 10$$$, calculate the minimum number of digits you have to insert in the string $$$s$$$ to make it a possible output of the $$$x$$$-$$$y$$$-counter. Note that you can't change the order of digits in string $$$s$$$ or erase any of them; only insertions are allowed.

The first line contains a single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^6$$$, $$$s_i \in \{\text{0} - \text{9}\}$$$) — the remaining data you have. It's guaranteed that $$$s_1 = 0$$$.

Print a $$$10 \times 10$$$ matrix, where the $$$j$$$-th integer ($$$0$$$-indexed) on the $$$i$$$-th line ($$$0$$$-indexed too) is equal to the minimum number of digits you have to insert in the string $$$s$$$ to make it a possible output of the $$$i$$$-$$$j$$$-counter, or $$$-1$$$ if there is no way to do so.

NoteLet's take, for example, $$$4$$$-$$$3$$$-counter. One of the possible outcomes the counter could print is $$$0(4)8(1)4(7)0$$$ (lost elements are in the brackets).One of the possible outcomes a $$$2$$$-$$$3$$$-counter could print is $$$0(35)8(1)4(7)0$$$.The $$$6$$$-$$$8$$$-counter could print exactly the string $$$0840$$$.

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

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

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

  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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val A = ns().map(_ - '0')
    val C = Array.ofDim[Int](A.length - 1)
    REP(A.length - 1) { i =>
      C(i) = (10 + A(i + 1) - A(i)) % 10
    }
    debug(C)

    val INF = 1e9.toInt
    // x, yどちらかが１回以上つかわれている
    def makeTrans(x: Int, y: Int): Array[Int] = {
      val dp = Array.fill[Int](10)(INF)
      REP(10) { i =>
        REP(10) { j =>
          val m = (i * x + j * y) % 10
          if (i + j > 0) dp(m) = min(dp(m), i + j)
        }
      }
      dp
    }

    val ans = Array.fill[Int](10, 10)(-1)
    REP(10) { x =>
      TO(x, 9) { y =>
        val t = makeTrans(x, y)
        debug(s"x:$x y:$y")
        debug(t)
        var cnt = 0
        var ok = true
        REP(C.length) { i =>
          val v = t(C(i))
//          debug(s"x:$x y:$y i:$i v:$v")
          ok &&= v != INF
          cnt += max(0, v - 1)
        }
        if (ok) {
//          debug(s"x:$x y:$y cnt:$cnt")
          ans(x)(y) = cnt
          ans(y)(x) = cnt
        }
      }
    }

    REP(10) { i =>
      out.println(ans(i).mkString(" "))
    }
  }
}

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

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

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

  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 = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val A = ns().map(_ - '0')
    val C = Array.ofDim[Int](A.length - 1)
    REP(A.length - 1) { i =>
      C(i) = (10 + A(i + 1) - A(i)) % 10
    }

    val INF = 1e9.toInt
    def makeTrans(x: Int, y: Int): Array[Int] = {
      val dp = Array.fill[Int](10)(INF)
      dp(0) = 0
      REP(10) { i =>
        REP(10) { j =>
          val m = (i * x + j * y) % 10
          dp(m) = min(dp(m), i + j)
        }
      }
      dp
    }

    val ans = Array.fill[Int](10, 10)(-1)
    REP(10) { x =>
      TO(x, 9) { j =>
        val t = makeTrans(x, j)
        debug(s"x:$x y:$j")
        debug(t)
        var cnt = 0
        var ok = true
        REP(C.length) { k =>
          val v = t(C(k))
          ok &&= v != INF
          cnt += max(0, v - 1)
        }
        if (ok) {
          ans(x)(j) = cnt
          ans(j)(x) = cnt
        }
      }
    }

    REP(10) { i =>
      out.println(ans(i).mkString(" "))
    }
  }
}


You are given an array $$$s$$$ consisting of $$$n$$$ integers.You have to find any array $$$t$$$ of length $$$k$$$ such that you can cut out maximum number of copies of array $$$t$$$ from array $$$s$$$.Cutting out the copy of $$$t$$$ means that for each element $$$t_i$$$ of array $$$t$$$ you have to find $$$t_i$$$ in $$$s$$$ and remove it from $$$s$$$. If for some $$$t_i$$$ you cannot find such element in $$$s$$$, then you cannot cut out one more copy of $$$t$$$. The both arrays can contain duplicate elements.For example, if $$$s = [1, 2, 3, 2, 4, 3, 1]$$$ and $$$k = 3$$$ then one of the possible answers is $$$t = [1, 2, 3]$$$. This array $$$t$$$ can be cut out $$$2$$$ times.   To cut out the first copy of $$$t$$$ you can use the elements $$$[1, \underline{\textbf{2}}, 3, 2, 4, \underline{\textbf{3}}, \underline{\textbf{1}}]$$$ (use the highlighted elements). After cutting out the first copy of $$$t$$$ the array $$$s$$$ can look like $$$[1, 3, 2, 4]$$$.  To cut out the second copy of $$$t$$$ you can use the elements $$$[\underline{\textbf{1}}, \underline{\textbf{3}}, \underline{\textbf{2}}, 4]$$$. After cutting out the second copy of $$$t$$$ the array $$$s$$$ will be $$$[4]$$$. Your task is to find such array $$$t$$$ that you can cut out the copy of $$$t$$$ from $$$s$$$ maximum number of times. If there are multiple answers, you may choose any of them.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$s$$$ and the desired number of elements in $$$t$$$, respectively. The second line of the input contains exactly $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2 \cdot 10^5$$$).

Print $$$k$$$ integers — the elements of array $$$t$$$ such that you can cut out maximum possible number of copies of this array from $$$s$$$. If there are multiple answers, print any of them. The required array $$$t$$$ can contain duplicate elements. All the elements of $$$t$$$ ($$$t_1, t_2, \dots, t_k$$$) should satisfy the following condition: $$$1 \le t_i \le 2 \cdot 10^5$$$.

NoteThe first example is described in the problem statement.In the second example the only answer is $$$[7, 3, 1, 3]$$$ and any its permutations. It can be shown that you cannot choose any other array such that the maximum number of copies you can cut out would be equal to $$$2$$$.In the third example the array $$$t$$$ can be cut out $$$5$$$ times.

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val S = na(N)
    val C = Array.ofDim[Int](2e5.toInt + 1)
    rep(N) { i =>
      C(S(i)) += 1
    }

    case class Elm(cnt: Int, num: Int) extends Comparable[Elm] {
      override def compareTo(o: Elm): Int = Integer.compare(o.cnt, cnt) // desc
    }

    val queue = new java.util.PriorityQueue[Elm]()
    rep(C.length) { i =>
      if (C(i) > 0) queue.add(Elm(C(i), i))
    }

    val times = Array.ofDim[Int](2e5.toInt + 1)
    val ans = ArrayBuffer[Int]()
    while (ans.length < K) {
      val a = queue.poll()
      ans += a.num
      times(a.num) += 1
      queue.add(Elm(C(a.num) / (times(a.num) + 1) , a.num))
    }

    out.println(ans.mkString(" "))
  }

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

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

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

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

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

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

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

object D extends App {
	def pred(x: Int) = (for (e <- f) yield e / x).sum >= k

	def binSearch(pred: Int => Boolean, a: Int, b: Int) = {
		var st = a
		var nd = b
		var ans = 0

		while (st <= nd) {
			val mid = (st + nd) / 2

			if (pred(mid)) {
				ans = ans max mid
				st = mid + 1
			}

			else nd = mid - 1
		}

		ans
	}

	val MAX = 2 * 100000

	val n = InputReader.nextInt
	var k = InputReader.nextInt
	val arr = InputReader.readLine.split(" ").map(_.toInt)

	var f = Array.fill(MAX + 1)(0)

	for (e <- arr) f(e) += 1

	val ans = binSearch(pred, 1, n)

	for(i <- 1 to MAX) f(i) /= ans

	val out = new PrintWriter(System.out)

	for {
		e <- arr
		if f(e) > 0
		if k > 0
	} {
		out.print(s"$e ")
		f(e) -= 1
		k -= 1
	}

	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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

object D extends App {
	def pred(x: Int) = (for (e <- f) yield e / x).sum >= k

	def binSearch(pred: Int => Boolean, a: Int, b: Int) = {
		var st = a
		var nd = b
		var ans = 0

		while (st <= nd) {
			val mid = (st + nd) / 2

			if (pred(mid)) {
				ans = ans max mid
				st = mid + 1
			}

			else nd = mid - 1
		}

		ans
	}

	val MAX = 2 * 100000

	val n = InputReader.nextInt
	var k = InputReader.nextInt
	val arr = InputReader.readLine.split(" ").map(_.toInt)

	var f = Array.fill(MAX + 1)(0)

	for (e <- arr) f(e) += 1

	val ans = binSearch(pred, 1, n)

	f = f.map(_ / ans)

	val out = new PrintWriter(System.out)

	for(e <- arr) {
		if(f(e) > 0 && k > 0) {
			out.print(s"$e ")
			f(e) -= 1
			k -= 1
		}
	}

	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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

object D extends App {
	def pred(x: Int) = (for (e <- f) yield e / x).sum >= k

	def binSearch(pred: Int => Boolean, a: Int, b: Int) = {
		var st = a
		var nd = b
		var ans = 0

		while (st <= nd) {
			val mid = (st + nd) / 2

			if (pred(mid)) {
				ans = ans max mid
				st = mid + 1
			}

			else nd = mid - 1
		}

		ans
	}

	def constructAnswer(x: Int) = {
		val arr = Array.fill(k)(0)
		var p = 0

		for ((e, i) <- f.zipWithIndex) {
			var v = e / x

			while (p < k && v > 0) {
				arr(p) = i
				p += 1
				v -= 1
			}
		}

		arr
	}

	val MAX = 2 * 100000

	val n = InputReader.nextInt
	val k = InputReader.nextInt
	val arr = InputReader.readLine.split(" ").map(_.toInt)

	val f = Array.fill(MAX + 1)(0)

	for (e <- arr) f(e) += 1

	val ans = binSearch(pred, 1, n)

	val out = new PrintWriter(System.out)
	constructAnswer(ans).foreach(x => out.print(s"$x "))
	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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

object D extends App {
	def pred(x: Int) = (for (e <- f) yield e / x).sum >= k

	def binSearch(pred: Int => Boolean, a: Int, b: Int) = {
		var st = a
		var nd = b
		var ans = 0

		while (st <= nd) {
			val mid = (st + nd) / 2

			if (pred(mid)) {
				ans = ans max mid
				st = mid + 1
			}

			else nd = mid - 1
		}

		ans
	}

	def constructAnswer(x: Int) = {
		val arr = Array.fill(k)(0)
		var p = 0

		for ((e, i) <- f.zipWithIndex) {
			var v = e / x

			while (p < k && v > 0) {
				arr(p) = i
				p += 1
				v -= 1
			}
		}

		arr
	}

	val MAX = 2 * 100000

	val n = InputReader.nextInt
	val k = InputReader.nextInt
	val arr = InputReader.readLine.split(" ").map(_.toInt)

	val f = Array.fill(MAX + 1)(0)

	for (e <- arr) f(e) += 1

	val ans = binSearch(pred, 1, n)

	constructAnswer(ans).foreach(x => print(s"$x "))
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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

object D extends App {
	def pred(x: Int) = (for (e <- f) yield e / x).sum >= k

	def binSearch(pred: Int => Boolean, a: Int, b: Int) = {
		var st = a
		var nd = b
		var ans = 0

		while (st <= nd) {
			val mid = (st + nd) / 2

			if (pred(mid)) {
				ans = ans max mid
				st = mid + 1
			}

			else nd = mid - 1
		}

		ans
	}

	def constructAnswer(x: Int) = {
		val arr = Array.fill(k)(0)
		var p = 0

		for ((e, i) <- f.zipWithIndex) {
			var v = e / x

			while (p < k && v > 0) {
				arr(p) = i
				p += 1
				v -= 1
			}
		}

		arr
	}

	val MAX = 2 * 100000

	val n = InputReader.nextInt
	val k = InputReader.nextInt
	val arr = InputReader.readLine.split(" ").map(_.toInt)

	val f = Array.fill(MAX + 1)(0)

	for (e <- arr) f(e) += 1

	val ans = binSearch(pred, 1, n)

	val out = new PrintWriter(System.out)
	out.println(constructAnswer(ans).mkString(" "))
	out.close
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

object CF_521_3_D {
  def solve(n: Int, k: Int, ss: Seq[Int]): Seq[Int] = {
    val counts: Map[Int, Int] = ss.groupBy(identity).mapValues(_.size)
    // sort biggest first so we can stop early
    val ordered = counts.toSeq.sortWith(_._2 > _._2).toStream
    // `trial` is the number of copies of t. Start with 1 and increase until it's not possible to build such a Seq
    // It's possible if we can find k or more elements that have enough copies.
    def isPossible(trial: Int, xs: Seq[(Int, Int)], found: Int, out: Seq[Int]): Option[Seq[Int]] =
      if(found >= k) Some(out.take(k))
      else if(xs.isEmpty) None
      else {
        val (e, c) = xs.head
        // instances is the number of instances of xs.head we'll use
        val instances = c/trial
        if (instances < 1) None
        else {
          val add = Seq.fill(instances)(e)
          isPossible(trial, xs.tail, found + instances, out ++ add)
        }
      }
    def find(trial: Int, best: Seq[Int]): Seq[Int] = {
      val poss = isPossible(trial, ordered, 0, Vector.empty)
      poss match {
        case None => best
        case Some(seq) => find(trial + 1, seq)
      }
    }

    find(1,Seq.empty)
  }

  // Specify Input and Output formats here:
  def formatIn(i: Input) = (i.int, i.int, {i.nextLine; i.intSeq})
  def formatOut(out: Seq[Int]) = out.mkString(" ")

//     ~~~ Boilerplate that doesn't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

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

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

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
}

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val S = na(N)
    val C = Array.ofDim[Int](2e5.toInt + 1)
    rep(N) { i =>
      C(S(i)) += 1
    }

    case class Elm(cnt: Int, num: Int) extends Comparable[Elm] {
      override def compareTo(o: Elm): Int = Integer.compare(o.cnt, cnt) // desc
    }

    val queue = new java.util.PriorityQueue[Elm]()
    rep(C.length) { i =>
      if (C(i) > 0) queue.add(Elm(C(i), i))
    }

    val times = Array.ofDim[Int](2e5.toInt + 1)
    val ans = ArrayBuffer[Int]()
    while (ans.length < K) {
      val a = queue.poll()
      ans += a.num
      times(a.num) += 1
      queue.add(Elm(a.cnt / (times(a.num) + 1) , a.num))
    }

    out.println(ans.mkString(" "))
  }

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

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

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

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

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

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


Mr. F has $$$n$$$ positive integers, $$$a_1, a_2, \ldots, a_n$$$.He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.

The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$) — the number of integers Mr. F has. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 1.5 \cdot 10^7$$$).

Print an integer — the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers. You should not remove all of the integers. If there is no solution, print «-1» (without quotes).

NoteIn the first example, the greatest common divisor is $$$1$$$ in the beginning. You can remove $$$1$$$ so that the greatest common divisor is enlarged to $$$2$$$. The answer is $$$1$$$.In the second example, the greatest common divisor is $$$3$$$ in the beginning. You can remove $$$6$$$ and $$$9$$$ so that the greatest common divisor is enlarged to $$$15$$$. There is no solution which removes only one integer. So the answer is $$$2$$$.In the third example, there is no solution to enlarge the greatest common divisor. So the answer is $$$-1$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)

    val g = gcd(A)
    rep(N) { i =>
      A(i) /= g
    }

    val NN = (1e7 + 5e6).toInt
    val prime = Array.ofDim[Int](1e6.toInt)
    val factor = Array.ofDim[Int](NN + 1)
    val C = Array.ofDim[Int](NN + 1)
    var pp = 0

    2 to NN foreach { i =>
      if (factor(i) == 0) {
        factor(i) = i
        prime(pp) = i
        pp += 1
      }

      def fill(p: Int): Unit = {
        if (p < pp && prime(p) * i <= NN) {
          factor(prime(p) * i) = prime(p)
          if (prime(p) != i)
            fill(p + 1)
        }
      }

      fill(0)
    }

    var mx = 0
    def incrFactor(x: Int, pre: Int): Unit = {
      if (x > 1) {
        val f = factor(x)
        if (f != pre) {
          C(f) += 1
          mx = max(mx, C(f))
        }
        incrFactor(x / f, f)
      }
    }

    A foreach { a =>
      incrFactor(a, -1)
    }

    val ans = if (mx == 0) -1 else N - mx
    out.println(ans)
  }

  def gcd(a: Int, b: Int): Int = {
    if (b == 0) a
    else gcd(b, a % b)
  }

  def gcd(as: Array[Int]): Int = {
    var res = as(0)
    rep(as.length - 1, 1) { i =>
      res = gcd(res, as(i))
    }
    res
  }

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

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

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

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

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


Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...The string $$$s$$$ he found is a binary string of length $$$n$$$ (i. e. string consists only of 0-s and 1-s).In one move he can choose two consecutive characters $$$s_i$$$ and $$$s_{i+1}$$$, and if $$$s_i$$$ is 1 and $$$s_{i + 1}$$$ is 0, he can erase exactly one of them (he can choose which one to erase but he can't erase both characters simultaneously). The string shrinks after erasing.Lee can make an arbitrary number of moves (possibly zero) and he'd like to make the string $$$s$$$ as clean as possible. He thinks for two different strings $$$x$$$ and $$$y$$$, the shorter string is cleaner, and if they are the same length, then the lexicographically smaller string is cleaner.Now you should answer $$$t$$$ test cases: for the $$$i$$$-th test case, print the cleanest possible string that Lee can get by doing some number of moves.Small reminder: if we have two strings $$$x$$$ and $$$y$$$ of the same length then $$$x$$$ is lexicographically smaller than $$$y$$$ if there is a position $$$i$$$ such that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$.

The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  Next $$$2t$$$ lines contain test cases — one per two lines. The first line of each test case contains the integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The second line contains the binary string $$$s$$$. The string $$$s$$$ is a string of length $$$n$$$ which consists only of zeroes and ones. It's guaranteed that sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

Print $$$t$$$ answers — one per test case. The answer to the $$$i$$$-th test case is the cleanest string Lee can get after doing some number of moves (possibly zero).

NoteIn the first test case, Lee can't perform any moves.In the second test case, Lee should erase $$$s_2$$$.In the third test case, Lee can make moves, for example, in the following order: 11001101 $$$\rightarrow$$$ 1100101 $$$\rightarrow$$$ 110101 $$$\rightarrow$$$ 10101 $$$\rightarrow$$$ 1101 $$$\rightarrow$$$ 101 $$$\rightarrow$$$ 01.

import java.util.StringTokenizer

import scala.io.StdIn

object Main {
  object Scanner {
    private var st: StringTokenizer = _

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

    def nextInt: Int = nextToken().toInt
    def nextLong: Long = nextToken().toLong
    def nextShort: Short = nextToken().toShort
    def nextByte: Byte = nextToken().toByte
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to Scanner.nextInt) {
      val n = Scanner.nextInt
      val s = StdIn.readLine()
      var m1 = 0
      while (m1 < n && s(m1) == '0') {
        m1 += 1
      }
      var m2 = 0
      while (m2 < n && s(n - m2 - 1) == '1') {
        m2 += 1
      }
      if (m1 + m2 == n) {
        println(s)
      } else {
        for (_ <- 1 to m1) {
          print('0')
        }
        print('0')
        for (_ <- 1 to m2) {
          print('1')
        }
        println()
      }
    }
  }
}

object ProblemB extends App {

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

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

    def nextToken(): String = {
      while (st == null || !st.hasMoreTokens) {
        st = new StringTokenizer(in.readLine);
      }
      return st.nextToken();
    }

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()
  for (_ <- 1 to t) {
    val m = in.nextInt()
    val s = in.nextToken()
    var hasOne = false
    var onePosition = -1
    var lastZero = -1

    for (i <- 0 until s.length) {
      if (s(i) == '0' && hasOne) {
        lastZero = i
      } else if (s(i) == '1' && !hasOne) {
        hasOne = true
        onePosition = i
      }
    }

    val res = if (hasOne && lastZero != -1) {
      s.take(onePosition) + s.takeRight(s.length - lastZero)
    } else {
      s
    }

    println(res)
  }

}


Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to:   dr(n) = S(n), if S(n) < 10;  dr(n) = dr( S(n) ), if S(n) ≥ 10. For example, dr(4098)  =  dr(21)  =  3.Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n)  =  S( S( S( S(n) ) ) ) (n ≤ 101000).Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.

The first line contains two integers k and d (1 ≤ k ≤ 1000; 0 ≤ d ≤ 9).

In a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.

NoteFor the first test sample dr(5881)  =  dr(22)  =  4.For the second test sample dr(36172)  =  dr(19)  =  dr(10)  =  1.

import java.util.Scanner

object Sum {
  class Sum{
  def max(a:Char,b:Char):Char=
     if (a<b)
        a
    else
        b
  }
  def taskA(){
    val F=new Sum
      val in = new Scanner(System.in)
      val s=readLine()
      var ans = if(s(0)!='-') s else s.substring(0,s.length()-2)+F.max(s(s.length()-1),s(s.length()-2))
      if(ans(0)=='-' && ans(1)=='0'){
        print(0)
      }
      else
          print(ans)

  }
  def taskB(){
    val in = new Scanner(System.in)
    val s = in.nextLine()
    var arr=new Array[Int](s.length()+5)
    arr(0)=0
    for{i<-1 to s.length()-1}
        if (s(i)==s(i-1)){
          arr(i)=arr(i-1)+1
        }
        else
          arr(i)=arr(i-1)
    val k = in.nextInt()

    for{i<-1 to k}{
        val left=in.nextInt()
        var l = if(left>1) left-1 else 0
        val r=in.nextInt()
        var ans = arr(r-1)-arr(l)
        println(ans)
    }

  }

  def taskA_206(){
    val in=new Scanner(System.in)
    val k=in.nextInt()
    val v=in.nextInt()
    val b=if(k>1 && v==0) false else true
    if(b){
        print(v)
        for{i<-1 to k-1}print(0)
    }
    else
      print("No solution")
  }
  def main(args: Array[String]) {
    taskA_206
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  var Array(k, d) = in.next().split(" ").map(_.toInt)
  if (d == 0 && k > 1)
    println("No solution")
  else {
    print(d)
    print("0" * (k - 1))
  }

}

object A355 {

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

  def main(args: Array[String]): Unit = {
    val Array(k, d) = readInts(2)
    if(d == 0 && k > 1)
      println("No solution")
    else
      println((Array(d) ++ Array.fill(k-1)(0)).mkString(""))
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object P355A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val K, D = sc.nextInt

  def solve(): Unit = {
    (K, D) match {
      case (1, 0) => out.println(0)
      case (_, 0) => out.println("No solution")
      case _      => out.println(D.toString + "0" * (K - 1))
    }
  }

  solve
  out.close
}

object Main {
  def main(args: Array[String]): Unit = {
    val kd = readLine().split(" ").map(_.toInt)
    val k = kd(0)
    val d = kd(1)

    if (k == 1) println(d)
    else if (d == 0) println("No solution")
    else println((Seq(d) ++ (1 to (k - 1)).map(_ => 0)).mkString)
  }
}

import java.util.Scanner

object Sum {
  class Sum{
  def max(a:Char,b:Char):Char=
     if (a<b)
        a
    else
        b
  }
  def taskA(){
    val F=new Sum
      val in = new Scanner(System.in)
      val s=readLine()
      var ans = if(s(0)!='-') s else s.substring(0,s.length()-2)+F.max(s(s.length()-1),s(s.length()-2))
      if(ans(0)=='-' && ans(1)=='0'){
        print(0)
      }
      else
          print(ans)

  }
  def taskB(){
    val in = new Scanner(System.in)
    val s = in.nextLine()
    var arr=new Array[Int](s.length()+5)
    arr(0)=0
    for{i<-1 to s.length()-1}
        if (s(i)==s(i-1)){
          arr(i)=arr(i-1)+1
        }
        else
          arr(i)=arr(i-1)
    val k = in.nextInt()

    for{i<-1 to k}{
        val left=in.nextInt()
        var l = if(left>1) left-1 else 0
        val r=in.nextInt()
        var ans = arr(r-1)-arr(l)
        println(ans)
    }

  }

  def taskA_206(){
    val in=new Scanner(System.in)
    val k=in.nextInt()
    val v=in.nextInt()
    print(v)
    for{i<-1 to k-1}print(0)
  }
  def main(args: Array[String]) {
    taskA_206
  }
}

object A355 {

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

  def main(args: Array[String]): Unit = {
    val Array(k, d) = readInts(2)
    if(d == 0)
      println("0")
    else
      println((Array(d) ++ Array.fill(k-1)(0)).mkString(""))
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object A355 {

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

  def main(args: Array[String]): Unit = {
    val Array(k, d) = readInts(2)
    println((Array(d) ++ Array.fill(k-1)(0)).mkString(""))
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

object P355A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val K, D = sc.nextInt

  def solve(): Unit = {

    @tailrec
    def loop(acc: Int, x: Int): Int = if (x == 1) acc
                                      else loop(acc * 10, x - 1)

    (K, D) match {
      case (1, 0) => out.println(0)
      case (_, 0) => out.println("No solution")
      case _      => out.println(loop(D, K))
    }
  }

  solve
  out.close
}

object Main {
  def main(args: Array[String]): Unit = {
    val kd = readLine().split(" ").map(_.toInt)
    val k = kd(0)
    val d = kd(1)

    if (k == 1) println(d)
    else if (d == 0) println((Seq(1, 9) ++ (1 to (k - 2)).map(_ => 0)).mkString)
    else println((Seq(d) ++ (1 to (k - 1)).map(_ => 0)).mkString)
  }
}


Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a $$$n\times m$$$ grid (rows are numbered from $$$1$$$ to $$$n$$$, and columns are numbered from $$$1$$$ to $$$m$$$). You have a chess piece, and it stands at some cell $$$(S_x,S_y)$$$ which is not on the border (i.e. $$$2 \le S_x \le n-1$$$ and $$$2 \le S_y \le m-1$$$).From the cell $$$(x,y)$$$, you can move your chess piece to $$$(x,y')$$$ ($$$1\le y'\le m, y' \neq y$$$) or $$$(x',y)$$$ ($$$1\le x'\le n, x'\neq x$$$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.

The only line of the input contains four integers $$$n$$$, $$$m$$$, $$$S_x$$$ and $$$S_y$$$ ($$$3\le n,m\le 100$$$, $$$2 \le S_x \le n-1$$$, $$$2 \le S_y \le m-1$$$) — the number of rows, the number of columns, and the initial position of your chess piece, respectively.

You should print $$$n\cdot m$$$ lines. The $$$i$$$-th line should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$), denoting the $$$i$$$-th cell that you visited. You should print exactly $$$nm$$$ pairs $$$(x_i, y_i)$$$, they should cover all possible pairs $$$(x_i, y_i)$$$, such that $$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$. We can show that under these constraints there always exists a solution. If there are multiple answers, print any.

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

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

  (0 until n).foldLeft((sx, sy)) {
    case ((x, y), i) =>
      val moves = (x, y) +: (1 to m).collect { case j if j != y => (x, j) }

      moves.foreach { case (x, y) => println(s"$x $y") }

      moves.last match {
        case (1, y) => (n, y)
        case (x, y) => (x - 1, y)
      }
  }
}

import scala.io.StdIn._

object taskB extends App {

  val input: Array[Int] = readLine.split(" ").map(_.toInt)
 // println(s"${input(0)} ${input(1)} ${input(2)} ${input(3)}")
  val sizeX = input(0)
  val sizeY = input(1)
  var locX = input(2)
  var locY = input(3)

  println(locX +" "+ locY)

  def visitWholeLine(): Unit = {
    (2 to sizeY).foreach {_ =>
      if (locY == sizeY) locY = 1
      else locY += 1
      println(locX +" "+ locY)
    }
  }

  visitWholeLine()
  (2 to sizeX).foreach { _ =>
    if (locX == sizeX) locX = 1
    else locX += 1
    println(locX +" "+ locY)

    visitWholeLine()
  }

}

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n  = in.nextInt()
    val m  = in.nextInt()
    val x1 = in.nextInt()
    val y1 = in.nextInt()

    println(s"$x1 $y1")
    println(s"1 $y1")
    println(s"1 1")

    1.to(n)
      .foreach(r => {
        var start = if (r % 2 == 1) 1 else m
        val inc   = if (r % 2 == 1) 1 else -1
        1.to(m)
          .foreach(_ => {
            val curRow = r
            val curCol = start
            if (!((curRow == x1 && curCol == y1) || (curRow == 1 && curCol == y1) || (curRow == 1 && curCol == 1))) {
              println(s"$curRow $curCol")
            }
            start = start + inc
          })
      })
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

import scala.io.StdIn._

object taskB extends App {

  val input: Array[Int] = readLine.split(" ").map(_.toInt)
 // println(s"${input(0)} ${input(1)} ${input(2)} ${input(3)}")
  val sizeX = input(0)
  val sizeY = input(1)
  var locX = input(2)
  var locY = input(3)

  var visited: List[(Int, Int)] = List((locX, locY))

  def visitWholeLine(): Unit = {
    (2 to sizeY).foreach {_ =>
      if (locY == sizeY) locY = 1
      else locY += 1
      println(locX +" "+ locY)
    }
  }

  visitWholeLine()
  (2 to sizeX).foreach { _ =>
    if (locX == sizeX) locX = 1
    else locX += 1
    println(locX +" "+ locY)

    visitWholeLine()
  }

}

import scala.io.StdIn._

object taskB extends App {

  val input: Array[Int] = readLine.split(" ").map(_.toInt)
 // println(s"${input(0)} ${input(1)} ${input(2)} ${input(3)}")
  val sizeX = input(0)
  val sizeY = input(1)
  var locX = input(2)
  var locY = input(3)

  var visited: List[(Int, Int)] = List((locX, locY))

  def visitWholeLine(): Unit = {
    (2 to sizeY).foreach {_ =>
      if (locY == sizeY) locY = 1
      else locY += 1
      visited = visited :+ (locX, locY)
    }
  }

  visitWholeLine()
  (2 to sizeX).foreach { _ =>
    if (locX == sizeX) locX = 1
    else locX += 1

    visitWholeLine()
  }

  visited.foreach { x =>
    println(s"${x._1} ${x._2}")
  }

}


You are given a positive integer $$$n$$$. Your task is to find any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$, or determine that there are no such integers.Here $$$a \oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \oplus 4 = 6$$$ and $$$3 \oplus 1=2$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$. If no such integers exist, print $$$-1$$$.

NoteIn the first test case, $$$a=3$$$, $$$b=3$$$, $$$c=1$$$, so $$$(3 \oplus 3)+(3 \oplus 1) + (3 \oplus 1)=0+2+2=4$$$.In the second test case, there are no solutions.In the third test case, $$$(2 \oplus 4)+(4 \oplus 6) + (2 \oplus 6)=6+2+4=12$$$.

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {
  import java.util.StringTokenizer
  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val n = tokenizer.nextToken().toInt
    for (i <- 1 to n) {
      tokenizer = new StringTokenizer(input.readLine())
      val j = tokenizer.nextToken().toInt
      if (j % 2 != 0) {
        output.println(-1)
      }
      else {
        output.println((j/2).toString + " " +(j/2).toString + " " + "0" )
      }
    }
  }

}

import scala.io.StdIn._

object Main extends App {

  val t = readInt()

  (1 to t).foreach(_ => solution());

  def solution() = {
    val n = readInt()
    if (n % 2 == 0)
      println(s"0 ${n / 2} ${n / 2}")
    else
      println(-1)

  }

}

import scala.io.StdIn

object Main extends App {
  val t = StdIn.readInt()
  for(i <- 0 until t){
    val n = StdIn.readInt()
    if (n % 2 == 1) {
      println(-1)
    } else {
      println("0 0 " + n / 2)
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {
  import java.util.StringTokenizer
  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val n = tokenizer.nextToken().toInt
    for (i <- 1 to n) {
      tokenizer = new StringTokenizer(input.readLine())
      val j = tokenizer.nextToken().toInt
      if (i % 2 != 0) {
        output.println(-1)
      }
      else {
        output.println((j/2).toString + " " +(j/2).toString + " " + "0" )
      }
    }
  }

}

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {
  import java.util.StringTokenizer
  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val n = tokenizer.nextToken().toInt
    for (i <- 1 to n) {
      tokenizer = new StringTokenizer(input.readLine())
      val j = tokenizer.nextToken().toInt
      if (i % 2 == 0) {
        output.println(-1)
      }
      else {
        output.println((j/2).toString + " " +(j/2).toString + " " + "0" )
      }
    }
  }

}