It is the hard version of the problem. The only difference is that in this version $$$3 \le k \le n$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$  — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$3 \le k \le n$$$). It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.

import scala.io.StdIn.readLine

object MyNewClass extends App {
  val t = readLine.toInt
  for (_ <- 1 to t) {
    val xs = readLine.split(' ').toList.map(x => x.toInt)
    val n = xs(0)
    val k = xs(1)
    val values = n - k + 3 match {
      case x if x % 2 == 1  => List(1, (x-1)/2, (x-1)/2) ++ List.fill(k-3)(1)
      case x if x % 4 == 2  => List(2, (x-2)/2, (x-2)/2) ++ List.fill(k-3)(1)
      case x if x % 4 == 0 =>  List(x/4, x/4, x/2) ++ List.fill(k-3)(1)
    }
    println(values.map(x => x.toString()).mkString(" "))
  }
}


Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$ — the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.

The first line contains one integer $$$n$$$ — the number of vertices in the tree ($$$2 \le n \le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \le s_v \le 10^9$$$), where erased values are replaced by $$$-1$$$.

Output one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.

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 from, to = Array.ofDim[Int](N - 1)
    REP(N - 1) { i =>
      from(i) = ni() - 1
      to(i) = i + 1
    }
    val S = na(N)
    val g = packUGraph(N, from, to)
    val (depth, parent, queue) = traceBfs(g)

    val INF = 1e6.toInt

    REP_r(N) { i =>
      val v = queue(i)
      if (depth(v) % 2 == 1) {
        // Sが決まっていない
        assert(S(v) == -1)

        // Sが決まっていない場合は、子供の中で一番小さいものに合わせる
        var ms = INF
        REP(g(v).length) { j =>
          val u = g(v)(j)
          if (parent(v) != u && S(u) != -1) {
            ms = min(ms, S(u))
          }
        }
        S(v) = if (ms == INF) -1 else ms
      }
    }

    val A = Array.ofDim[Int](N)
    REP(N) { i =>
      val v = queue(i)

      //登って行くときに未決定だったSをparentのものにする
      if (depth(v) % 2 == 1 && S(v) == -1) {
        S(v) = S(parent(v))
      }
      if (v == 0) A(v) = S(v)
      else A(v) = S(v) - S(parent(v))
    }

    if (A.exists(_ < 0)) {
      out.println(-1)
    } else {
      val ans = sumL(A)
      out.println(ans)
    }
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

  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.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.t6)
    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
//        ver.vv = 0
        val vv = if (ver.children != Nil) ver.children.map(_.sum).min - sum else 0
        if (vv < 0 ) possible = false
        ver.vv = vv
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Long = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(x => debug(x+""))

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""

val t6 = """
5
1 2 2 3
1 -1 2 3 -1
""" //3
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.t6)
    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
//        ver.vv = 0
        val vv = if (ver.children != Nil) ver.children.map(_.sum).min - sum else 0
        if (vv < 0 ) possible = false
        ver.vv = vv
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Int = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(x => debug(x+""))

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""

val t6 = """
5
1 2 2 3
1 -1 2 3 -1
""" //3
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
        ver.vv = 0
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Int = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(x => debug(x+""))

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    //runTest(Test.sa1)
    //debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
        ver.vv = 0
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Int = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(println)

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""
}

}


Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that $$$n$$$ persons took part in that party. To make the party funnier, each person wore one hat among $$$n$$$ kinds of weird hats numbered $$$1, 2, \ldots n$$$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the $$$i$$$-th person said that there were $$$a_i$$$ persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $$$b_i$$$ be the number of hat type the $$$i$$$-th person was wearing, Chouti wants you to find any possible $$$b_1, b_2, \ldots, b_n$$$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of persons in the party. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n-1$$$), the statements of people.

If there is no solution, print a single line "Impossible". Otherwise, print "Possible" and then $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$). If there are multiple answers, print any of them.

NoteIn the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $$$1$$$.In the answer to the second example, the first and the second person wore the hat with type $$$1$$$ and all other wore a hat of type $$$2$$$.So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.In the third example, it can be shown that no solution exists.In the first and the second example, other possible configurations are possible.

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 C = Array.ofDim[Int](N + 1)
    REP(N) { i =>
      C(A(i)) += 1
    }

    def validate: Option[Array[mutable.Queue[Int]]] = {
      var id = 1
      val res = Array.fill[mutable.Queue[Int]](N)(mutable.Queue())

      REP(N + 1) { i =>
        if (C(i) > 0) {
          val cnt = N - i
          if (C(i) < cnt || cnt == 0) return None
          else {
            REP(C(i) / cnt) { d =>
              REP(cnt) { _ => res(i) += id }
              id += 1
            }
          }
        }
      }
      Some(res)
    }

    def mkAns(groups: Array[mutable.Queue[Int]]): Option[Array[Int]] = {
      val ans = Array.ofDim[Int](N)
      REP(N) { i =>
        if (groups(A(i)).isEmpty) return None
        else ans(i) = groups(A(i)).dequeue()
      }
      Some(ans)
    }

    validate match {
      case None => out.println("Impossible")
      case Some(groups) =>
        mkAns(groups) match {
          case None =>
            out.println("Impossible")

          case Some(ans) =>
            out.println("Possible")
            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[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  //val counts = Array.fill(bs.max + 1) { 0 }
  //for (b <- bs) counts(b) += 1
  val counts = new mutable.ArrayOps.ofInt(bs).groupBy(identity).map {
    case (k, v) => k -> v.length
  }

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  //val counts = Array.fill(bs.max + 1) { 0 }
  //for (b <- bs) counts(b) += 1
  val counts = bs.groupBy(identity).map {
    case (k, v) => k -> v.length
  }

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  val counts = bs.groupBy(identity).map {
    case (k, v) => k -> v.size
  }

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  val counts = Array.fill(bs.max + 1) { 0 }
  for (b <- bs) counts(b) += 1

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}


Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.  Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).  Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  def buffered(thunk: => Unit) =
    Console.withOut(new java.io.BufferedOutputStream(Console.out)) {
      thunk
	  Console.flush
    }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  buffered {
  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }
  }
}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  Console.setOut(new java.io.PrintStream(Console.out))

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

  Console.flush
}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  Console.setOut(new java.io.PrintStream(Console.out, false))

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

  Console.flush
}

import java.util.Scanner
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

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

  object Input {
    import java.lang.Character._

    lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))
    var buf: Array[Char] = Array()
    var pos: Int = 0

    def next(): String = {
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      while (isWhitespace(buf(pos))) {
        pos += 1
      }
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      val s = pos
      while (pos < buf.length && !isWhitespace(buf(pos))) {
        pos += 1
      }
      new java.lang.String(buf, s, pos - s)
    }

    def nextInt(): Int = next.toInt

    def nextLong(): Long = next.toLong

    def nextFloat(): Float = next.toFloat

    def nextDouble(): Double = next.toDouble

    val nextString: () => String = next _
  }

  import Input._

  def solve(): Unit = {
    val N, M = nextInt
    val A: Array[Long] = Array.fill(N)(nextLong)

    var sumY = 0L
    var i = 0
    while (i < M) {
      (nextInt: @switch) match {
        case 1 =>
          val v = nextInt - 1
          val x = nextLong - sumY
          A(v) = x
        case 2 =>
          val y = nextLong
          sumY += y
        case 3 =>
          val q = nextInt - 1
          out.println(A(q) + sumY)
      }
      i += 1
    }
  }

  solve
  out.flush
}

object Main {
  def readLineOfNums(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  val result = new StringBuilder()
  def performCommand(array: Array[Long], sum: Long) = {
    val cmd = readLineOfNumsI()
    cmd(0) match {
      case 1 =>
        array(cmd(1)-1) = cmd(2) - sum
        sum
      case 2 =>
        sum + cmd(1)
      case 3 =>
        result.append(array(cmd(1)-1) + sum).append("\n")
        sum
    }
  }
  def main(args: Array[String]) = {
    val Array(n, m) = readLineOfNumsI()
    val array = readLineOfNums()
    var sum: Long = 0
    for (i <- 1 to m)
      sum = performCommand(array, sum)
    print(result)
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val a: Array[Long] = in.next().split(' ').map(_.toLong)
  var y = 0l
  val result = (1 to m).foldLeft(List.empty[Long]) {
    case (list, _) =>
    val data = in.next().split(' ').map(_.toInt).toList
    data match {
      case (1 :: v :: x :: Nil) =>
        a(v - 1) = x - y
        list
      case (2 :: y1 :: Nil) =>
        y += y1
        list
      case (3 :: v :: Nil) =>
        (a(v - 1) + y) :: list
    }
  }
  println(result.reverse.mkString("\n"))
}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

  Console.flush
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts
  val as = readInts
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val op = readInts
    op(0) match {
      case 1 => as(op(1) - 1) = op(2) - delta
      case 2 => delta += op(1)
      case 3 => println(as(op(1) - 1) + delta)
    }
  }

}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  Console.withOut(new java.io.BufferedOutputStream(Console.out)) {
  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }
Console.flush
}
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)
  def readLongs = readString.split(" ").map(_.toLong)

  val Array(n, m) = readInts
  val as = readLongs
  var delta = 0L

  var t = 0
  while (t < m) {
    t += 1
    val op = readInts
    op(0) match {
      case 1 => as(op(1) - 1) = op(2) - delta
      case 2 => delta += op(1)
      case 3 => println(as(op(1) - 1) + delta)
    }
  }

}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  Console.withOut(new java.io.BufferedOutputStream(Console.out)) {
  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }
}
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  // N integers
  // array A = A_1, ..., A_n
  // M operations
  // * A_(V_i) = X_i
  // * Increase each A_i by Y_i ... A_i = A_i + Y_i
  // * A_(Q_i)

  def solve(): Unit = {
    val N, M = sc.nextInt
    val A: Array[Long] = Array.fill(N)(sc.nextLong)

    var sumY = 0
    0 until M foreach { i =>
      sc.nextInt match {
        case 1 =>
          val v, x = sc.nextInt
          A(v - 1) = x
        case 2 =>
          sumY += sc.nextInt
        case 3 =>
          out.println(A(sc.nextInt  - 1) + sumY)
      }
    }
  }

  solve
  out.close
}

object B extends App {

  val scan = new java.util.Scanner(Console.in)

  val (n, m) = (scan.nextInt, scan.nextInt)
  val as = Array.fill(n)(scan.nextInt)
  var delta = 0
println(util.Properties.versionString)
  var t = 0
  while (t < m) {
    t += 1
    scan.nextInt match {
      case 1 => as(scan.nextInt - 1) = scan.nextInt - delta
      case 2 => delta += scan.nextInt
      case 3 => println(as(scan.nextInt - 1) + delta)
    }
  }

}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(t - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

}


You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \rightarrow 10 \rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$).

object CodeforcesRound667a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

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

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

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a, b) = rll_int
    val diff = Math.abs(b - a)
    val res = diff / 10 + (if (diff % 10 > 0) 1 else 0)
    writer.println(res)
  }

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

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

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

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

}

//package codeforces.contests._1409

object YetAnotherTwoIntegersProblem {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val Array(a, b) = io.StdIn.readLine.split(" ").map(_.toInt)
      println {
        val d = (a - b).abs

        if (d % 10 == 0) d / 10 else d / 10 + 1
      }
    }
  }
}

/**
 * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
 */
import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    // Write your solution here
    /*
    int t;
    cin >> t;
    while (t--) {
      int a, b;
      cin >> a >> b;
      cout << (abs(a - b) + 9) / 10 << endl;
    }

    return 0;
    */
    val t = readInt

    for (_ <- 0 until t) {
      val splitLine = readLine.split(" ")
      val a = splitLine(0).toInt
      val b = splitLine(1).toInt

      println((math.abs(a - b) + 9) / 10)
    }
  }
}

/**
 * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
 */
import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    // Write your solution here
    val t = readInt

    for (_ <- 0 until t) {
      val splitLine = readLine.split(" ").map(_.toInt)
      val a = splitLine(0)
      val b = splitLine(1)

      println((math.abs(a - b) + 9) / 10)
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine.toInt
    for (_ <- 0 until t) {
      val arr = StdIn.readLine.split(" ").map(_.toInt)
      val res = ((arr.max - arr.min).abs + 9) / 10
      println(res)

    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toInt)
    val c           = (a - b).abs

    val ans = c / 10 + (if (c % 10 == 0) 0 else 1)

    println(ans)
  }
}

import scala.collection.mutable.ArrayBuffer

object A 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 inputLines = in.nextInt()

    inputLines.times {
      val a = in.nextInt()
      val b = in.nextInt()
      val r = math.abs(a - b)

      if (r % 10 == 0) {
        println(r / 10)
      } else {
        println(1 + (r / 10))
      }
    }
  }

  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 nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

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


You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.

The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 100$$$). Each of the next $$$T$$$ lines contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 1000$$$) — the description of test cases.

For each test case output two lines. In the first line output a single integer $$$m$$$ — the number of chosen integers. In the second line output $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order.

import java.io.BufferedReader
import java.io.InputStreamReader

object Main {
    def main(args: Array[String]) = {
        val cin = new BufferedReader(new InputStreamReader(System.in))
        val T = cin.readLine.toInt
        for (t <- 1 to T) {
            val n::k::Nil = cin.readLine.split(" ").map(_.toInt).toList
            val l = (k+1)/2
            println(n-l)
            for (x <- l to n)
			    if (x != k)
				    print(x+" ")
	        println() } } }

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader

object AAntiKnapsack {
  def solve(n: Int, k: Int): (Int, String) = {
    val higher = (1 to n).dropWhile(_ <= k)
    val res = (Math.ceil(k.toFloat / 2).toInt until k) ++ higher
    (res.length, res.mkString("", " ", ""))
  }

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//    "3\n3 2\n5 3\n1 1".getBytes)))
    //              "1\n3\n0 0 3".getBytes)))
    val inputs = file.readLine.toInt
    var i = 0
    while (i < inputs) {
      val n::k::Nil = file.readLine.split(" ").map(_.toInt).toList
      solve(n, k).productIterator.foreach(println)
      i += 1
    }
  }
}