This problem is given in two editions, which differ exclusively in the constraints on the number $$$n$$$.You are given an array of integers $$$a[1], a[2], \dots, a[n].$$$ A block is a sequence of contiguous (consecutive) elements $$$a[l], a[l+1], \dots, a[r]$$$ ($$$1 \le l \le r \le n$$$). Thus, a block is defined by a pair of indices $$$(l, r)$$$.Find a set of blocks $$$(l_1, r_1), (l_2, r_2), \dots, (l_k, r_k)$$$ such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks $$$(l_i, r_i)$$$ and $$$(l_j, r_j$$$) where $$$i \neq j$$$ either $$$r_i < l_j$$$ or $$$r_j < l_i$$$.  For each block the sum of its elements is the same. Formally, $$$$$$a[l_1]+a[l_1+1]+\dots+a[r_1]=a[l_2]+a[l_2+1]+\dots+a[r_2]=$$$$$$ $$$$$$\dots =$$$$$$ $$$$$$a[l_k]+a[l_k+1]+\dots+a[r_k].$$$$$$  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks $$$(l_1', r_1'), (l_2', r_2'), \dots, (l_{k'}', r_{k'}')$$$ satisfying the above two requirements with $$$k' > k$$$.     The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.

The first line contains integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given array. The second line contains the sequence of elements $$$a[1], a[2], \dots, a[n]$$$ ($$$-10^5 \le a_i \le 10^5$$$).

In the first line print the integer $$$k$$$ ($$$1 \le k \le n$$$). The following $$$k$$$ lines should contain blocks, one per line. In each line print a pair of indices $$$l_i, r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the bounds of the $$$i$$$-th block. You can print blocks in any order. If there are multiple answers, print any of them.

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 cum = cumSum(A)
    debug(cum)

    // [l, r)
    case class Range(l: Int, r: Int)

    val G = mutable.HashMap[Long, Array[Range]]()
    val C = mutable.HashMap[Long, Int]().withDefaultValue(0)
    REP(N) { l =>
      TO(l + 1, N) { r =>
        val v = cum(r) - cum(l)
        C(v) = C(v) + 1
      }
    }
    C.keys.foreach { v =>
      G(v) = Array.ofDim(C(v))
    }
    REP(N) { l =>
      TO(l + 1, N) { r =>
        val v = cum(r) - cum(l)
        val id = C(v) - 1
        C(v) = id
        G(v)(id) = Range(l, r)
      }
    }

    DEBUG {
      G.foreach { case (v, as) =>
        debug(s"A v:$v")
        debug(as.mkString(","))
      }
    }

    var ans: ArrayBuffer[Range] = null
    G.foreach { case (v, as) =>
      import java.util
      import java.util.Comparator
      val res = ArrayBuffer[Range]()
      util.Arrays.sort(as, new Comparator[Range] {
        override def compare(o1: Range, o2: Range): Int = Integer.compare(o1.r, o2.r) //　終端で昇順ソートする
      })

      var r = 0
      REP(as.length) { i =>
        if (as(i).l >= r) {
          res += as(i)
          r = as(i).r
        }
      }

      debug(s"dump res v:$v")
      debug(res.mkString(","))

      if (ans == null || res.length > ans.length) ans = res
    }

    out.println(ans.length)
    REP(ans.length) { i =>
      val rg = ans(i)
      out.println(s"${rg.l+1} ${rg.r}")
    }
  }

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

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)

  class Zipper {
    type A = Long
    var gen = 0
    val id = mutable.HashMap[A, Int]()
    var len = 0

    def get(x: A): Int = {
      id.getOrElseUpdate(x, {
        val i = gen
        gen += 1
        len += 1
        i
      })
    }
  }

  def solve(): Unit = {
    val NN = 1.2e6.toInt

    val N = ni()
    val A = na(N)
    val cum = cumSum(A)
    debug(cum)

    // [l, r)
    case class Range(l: Int, r: Int)

    val zip = new Zipper
    val G = Array.ofDim[Array[Range]](NN)
    val C = Array.ofDim[Int](NN)
    REP_r(N, 1) { r =>
      TO(0, r - 1) { l =>
        val v = cum(r) - cum(l)
        val id = zip.get(v)
        C(id) = C(id) + 1
      }
    }
    REP(zip.len) { i =>
      G(i) = Array.ofDim(C(i))
    }

    // 作るときにR順になるようにする。idを振るのが逆順なのでRを逆順でループする
    REP_r(N, 1) { r =>
      // Lはどうでもいい
      TO(0, r - 1) { l =>
        val v = cum(r) - cum(l)
        val id = zip.get(v)
        C(id) -= 1
        val i = C(id)
        G(id)(i) = Range(l, r)
      }
    }

    DEBUG {
      REP(zip.len) { i =>
        debug(G(i).mkString(","))
      }
    }

    var ans, res: Array[Range] = Array.ofDim[Range](1.2e6.toInt)
    var len = 0
    var ptr = 0

    REP(zip.len) { i =>
      val as = G(i)
      ptr = 0
      var r = 0
      REP(as.length) { i =>
        if (as(i).l >= r) {
          res(ptr) = as(i)
          ptr += 1
          r = as(i).r
        }
      }

//      debug(s"dump res v:$v")
//      debug(res.mkString(","))

      if (ans == null || ptr > len) {
        len = ptr
        val tmp = ans
        ans = res
        res = tmp
      }
    }

    out.println(len)
    REP(len) { i =>
      val rg = ans(i)
      out.println(s"${rg.l+1} ${rg.r}")
    }
  }

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


You are given a number $$$n$$$ (divisible by $$$3$$$) and an array $$$a[1 \dots n]$$$. In one move, you can increase any of the array elements by one. Formally, you choose the index $$$i$$$ ($$$1 \le i \le n$$$) and replace $$$a_i$$$ with $$$a_i + 1$$$. You can choose the same index $$$i$$$ multiple times for different moves.Let's denote by $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ the number of numbers from the array $$$a$$$ that have remainders $$$0$$$, $$$1$$$ and $$$2$$$ when divided by the number $$$3$$$, respectively. Let's say that the array $$$a$$$ has balanced remainders if $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ are equal.For example, if $$$n = 6$$$ and $$$a = [0, 2, 5, 5, 4, 8]$$$, then the following sequence of moves is possible:   initially $$$c_0 = 1$$$, $$$c_1 = 1$$$ and $$$c_2 = 4$$$, these values are not equal to each other. Let's increase $$$a_3$$$, now the array $$$a = [0, 2, 6, 5, 4, 8]$$$;  $$$c_0 = 2$$$, $$$c_1 = 1$$$ and $$$c_2 = 3$$$, these values are not equal. Let's increase $$$a_6$$$, now the array $$$a = [0, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 3$$$, $$$c_1 = 1$$$ and $$$c_2 = 2$$$, these values are not equal. Let's increase $$$a_1$$$, now the array $$$a = [1, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 2$$$, $$$c_1 = 2$$$ and $$$c_2 = 2$$$, these values are equal to each other, which means that the array $$$a$$$ has balanced remainders. Find the minimum number of moves needed to make the array $$$a$$$ have balanced remainders.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^4$$$) — the length of the array $$$a$$$. It is guaranteed that the number $$$n$$$ is divisible by $$$3$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$150\,000$$$.

For each test case, output one integer — the minimum number of moves that must be made for the $$$a$$$ array to make it have balanced remainders.

NoteThe first test case is explained in the statements.In the second test case, you need to make one move for $$$i=2$$$.The third test case you need to make three moves:   the first move: $$$i=9$$$;  the second move: $$$i=9$$$;  the third move: $$$i=2$$$. In the fourth test case, the values $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ initially equal to each other, so the array $$$a$$$ already has balanced remainders.

import java.util.Scanner
object Main extends App{
    def compute: Int = {
        val n = scanner.nextInt()
        var count0 = 0
        var count1 = 0
        var count2 = 0
        for(i <- 0 to n - 1){
            val temp = scanner.nextInt()
            val remainder = temp % 3
            (temp % 3) match {
                case 0 => count0 += 1
                case 1 => count1 += 1
                case 2 => count2 += 1
            }
        }
        scanner.nextLine()
        var ans = 0
        if(count0 > n / 3) {
            if(count1 < n / 3){
                val temp = n / 3 - count1
                val r = Math.min(temp, count0 - n / 3)
                ans += r
                count0 -= r
                count1 += r
            }
            if(count2 < n / 3){
                val temp = n / 3 - count2
                val r = Math.min(temp, count0 - n / 3)
                ans += (2 * r)
                count0 -= r
                count2 += r
            }
        }
        if(count2 > n / 3) {
            if(count0 < n / 3){
                val temp = n / 3 - count0
                val r = Math.min(temp, count2 - n / 3)
                ans += r
                count2 -= r
                count0 += r
            }
            if(count1 < n / 3){
                val temp = n / 3 - count1
                val r = Math.min(temp, count2 - n / 3)
                ans += (2 * r)
                count2 -= r
                count1 += r
            }
        }
        if(count1 > n / 3){
            if(count2 < n / 3){
                val temp = n / 3 - count2
                val r = Math.min(temp, count1 - n / 3)
                ans += r
                count1 -= r
                count2 += r
            }
            if(count0 < n / 3){
                val temp = n / 3 - count0
                val r = Math.min(temp, count1 - n / 3)
                ans += (2 * r)
                count1 -= r
                count0 += r
            }
        }
        return ans
    }
    val scanner = new Scanner(System.in)
    val t = scanner.nextInt()
    for (i <- 0 to t - 1)  {
        println(compute)
    }
}

import java.util.Scanner
object Main extends App{
    def compute: Int = {
        val n = scanner.nextInt()
        var count0 = 0
        var count1 = 0
        var count2 = 0
        for(i <- 0 to n - 1){
            val temp = scanner.nextInt()
            val remainder = temp % 3
            (temp % 3) match {
                case 0 => count0 += 1
                case 1 => count1 += 1
                case 2 => count2 += 1
            }
        }
        scanner.nextLine()
        var ans = 0
        if(count0 > n / 3) {
            if(count1 < n / 3){
                val temp = n / 3 - count1
                val r = Math.min(temp, count0 - n / 3)
                ans += r
                count0 -= r
            }
            if(count2 < n / 3){
                val temp = n / 3 - count2
                val r = Math.min(temp, count0 - n / 3)
                ans += (2 * r)
                count0 -= r
            }
        }
        if(count2 > n / 3) {
            if(count1 < n / 3){
                val temp = n / 3 - count1
                val r = Math.min(temp, count2 - n / 3)
                ans += r
                count2 -= r
            }
            if(count0 < n / 3){
                val temp = n / 3 - count0
                val r = Math.min(temp, count2 - n / 3)
                ans += (2 * r)
                count2 -= r
            }
        }
        if(count1 > n / 3){
            ans += (count1 - n / 3)
        }
        return ans
    }
    val scanner = new Scanner(System.in)
    val t = scanner.nextInt()
    for (i <- 0 to t - 1)  {
        println(compute)
    }
}


Let's call some positive integer classy if its decimal representation contains no more than $$$3$$$ non-zero digits. For example, numbers $$$4$$$, $$$200000$$$, $$$10203$$$ are classy and numbers $$$4231$$$, $$$102306$$$, $$$7277420000$$$ are not.You are given a segment $$$[L; R]$$$. Count the number of classy integers $$$x$$$ such that $$$L \le x \le R$$$.Each testcase contains several segments, for each of them you are required to solve the problem separately.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of segments in a testcase. Each of the next $$$T$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$1 \le L_i \le R_i \le 10^{18}$$$).

Print $$$T$$$ lines — the $$$i$$$-th line should contain the number of classy integers on a segment $$$[L_i; R_i]$$$.

object ClassyNumbers {

  def main(args: Array[String]): Unit = {
    println {
      (for (_ <- 1 to io.StdIn.readInt()) yield {
        val Array(l, r) = io.StdIn.readLine().split(" ").map(_.toLong)

        val Classy = 4

        def solve(digits: Seq[Int]): Int = {

          val Idx = digits.size

          val dp = Array.fill[Option[Int]](Idx, Classy, 2)(None)

          def loop(idx: Int, flag: Boolean, classy: Int): Int = {

            if (classy == Classy)
              0
            else if (idx == Idx)
              1
            else
              dp(idx)(classy)(if (flag) 1 else 0).getOrElse {
                val res: Int = (1 to (if (flag) digits(idx) else 9))
                  .foldLeft(0)(
                    (acc, i) =>
                      acc + loop(idx + 1, flag && i == digits(idx), classy + 1)
                  ) + loop(idx + 1, flag && 0 == digits(idx), classy)

                dp(idx)(classy)(if (flag) 1 else 0) = Some(res)
                res
              }
          }

          loop(0, flag = true, 0)
        }

        val lDigits = (l - 1).toString.map(_ - '0')
        val rDigits = r.toString.map(_ - '0')

        solve(rDigits) - solve(lDigits)

      }).mkString("\n")
    }
  }

}

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 = 1e6.toInt
    val C = Array.ofDim[Int](N, 4)

    def len(i: Long) = i.toString.count(_ != '0')

    REP(N) { i =>
      if (i == 0) C(0)(0) = 1
      else {
        REP(4) { j =>
          C(i)(j) = C(i - 1)(j)
        }

        val cnt = i.toString.count(_ != '0')
        if (cnt <= 3) C(i)(cnt) += 1
      }
    }

    def cnt(x: Long): Long = {
      if (x < N) {
        C(x.toInt).sum

      } else if (x >= N && x < 1e12.toLong) {
        val q = (x / N).toInt
        val m = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          res += C(m)(i)
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            res += C(q - 1)(i).toLong * C(N - 1)(j)
          }
        }

        res

      } else {
        val q = (x / N / N).toInt
        val m1 = (x / N % N).toInt
        val m2 = (x % N).toInt

        var res = 0L

        // 10^12以降の値が固定の場合、10^12以下の値も制限される
        val i = len(q)
        val j = len(m1)
        REP(4 - (j + i)) { k =>
          res += C(m2)(k)
        }

        if (m1 > 0) {
          REP(4 - i) { j =>
            REP(4 - (j + i)) { k =>
              res += C(m1 - 1)(j) * C(N - 1)(k)
            }
          }
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            REP(4 - (j + i)) { k =>
              res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)
            }
          }
        }

        res
      }
    }

    REP(ni()) { _ =>
      val l, r = nl()
      val ans = cnt(r) - cnt(l - 1)
      out.println(ans)
    }
  }

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

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

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

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

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

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

object Main {
  def main(args: Array[String]): 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 T = ni()
    rep(T) { _ =>
      val l, r = nl()
      val ans = f(r.toString.toCharArray) - f((l - 1).toString.toCharArray)
      out.println(ans)
    }
  }

  def f(D: Array[Char]): Int = {
    val N: Int = D.length
    val memo = Array.fill[Int](N, 4)(-1)
    def g(i: Int, k: Int, f: Boolean): Int = {
      if (k < 0) 0
      else if (i == N) 1
      else {
        if (f && memo(i)(k) != -1) {
          memo(i)(k)
        } else {
          var res = 0
          val d = if (f) 9 else D(i) - '0'
          rep(d + 1) { j =>
            val newF = f || j < d
            val newK = if (j == 0) k else k - 1 // 0以外の時kの値を減らす
            res += g(i + 1, newK, newF)
          }
          if (f) memo(i)(k) = res
          res
        }
      }
    }

    g(0, 3, f = false)
  }

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

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 T = ni()
    rep(T) { _ =>
      val l, r = nl()
      val ans = f(r) - f(l - 1)
      out.println(ans)
    }
  }

  val pow10 = Array.ofDim[Long](19)
  pow10(0) = 1
  rep(18)(i => pow10(i + 1) = pow10(i) * 10)

  /**
    * @return (log10の整数値, 最大桁の値)
    */
  def log10(x: Long): (Int, Int) = {
    var a = x
    var i = 0
    while(a >= 10) {
      a /= 10
      i += 1
    }
    (i, a.toInt)
  }

  def f(x: Long): Int = {
    val (n, _) = log10(x)
    val N = n + 1
    val dp = Array.ofDim[Int](N + 1, 2, 4)
    dp(0)(0)(3) = 1

    rep(N) { i =>
      val D = (x / pow10(n - i) % 10).toInt
      rep(2) { f =>
        rep(4) { k =>
          val d = if (f == 1) 9 else D
          rep(d + 1) { j =>
            val newF = f | (if(j < d) 1 else 0)
            val newK = if (j == 0) k else k - 1
            if (newK >= 0) dp(i + 1)(newF)(newK) += dp(i)(f)(k)
          }
        }
      }
    }

    var res = 0
    rep(2) { f =>
      rep(4) { k =>
        res += dp(N)(f)(k)
      }
    }
    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 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
  }
}

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 T = ni()
    rep(T) { _ =>
      val l, r = nl()
      val ans = f(r.toString.toCharArray) - f((l - 1).toString.toCharArray)
      out.println(ans)
    }
  }

  def f(D: Array[Char]): Int = {
    val N = D.length
    val dp = Array.ofDim[Int](N + 1, 2, 4)
    dp(0)(0)(3) = 1

    rep(N) { i =>
      rep(2) { f =>
        rep(4) { k =>
          val d = if (f == 1) 9 else D(i) - '0'
          rep(d + 1) { j =>
            val newF = f | (if(j < d) 1 else 0)
            val newK = if (j == 0) k else k - 1
            if (newK >= 0) dp(i + 1)(newF)(newK) += dp(i)(f)(k)
          }
        }
      }
    }

    var res = 0
    rep(2) { f =>
      rep(4) { k =>
        res += dp(N)(f)(k)
      }
    }
    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 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
  }
}

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 = 1e6.toInt
    val C = Array.ofDim[Int](N, 4)

    def len(i: Long) = i.toString.count(_ != '0')

    REP(N) { i =>
      if (i == 0) C(0)(0) = 1
      else {
        REP(4) { j =>
          C(i)(j) = C(i - 1)(j)
        }

        val cnt = i.toString.count(_ != '0')
        if (cnt <= 3) C(i)(cnt) += 1
      }
    }

    def cnt(x: Long): Long = {
      if (x < N) {
        C(x.toInt).sum

      } else if (x >= N && x < 1e12.toLong) {
        val q = (x / N).toInt
        val m = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          res += C(m)(i)
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            res += C(q - 1)(i).toLong * C(N - 1)(j)
          }
        }

        res

      } else {
        val q = (x / N / N).toInt
        val m1 = (x / N % N).toInt
        val m2 = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        val i = len(q)
        REP(4 - i) { j =>
          REP(4 - (j + i)) { k =>
            res += C(m1)(j).toLong * C(m2)(k)
          }
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            REP(4 - (j + i)) { k =>
              res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)
            }
          }
        }

        res
      }
    }

    REP(ni()) { _ =>
      val l, r = nl()
      val ans = cnt(r) - cnt(l - 1)
      out.println(ans)
    }
  }

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

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

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

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

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

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

object Main {
  def main(args: Array[String]): 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 = 1e6.toInt
    val C = Array.ofDim[Int](N, 4)

    def len(i: Long) = i.toString.count(_ != '0')

    REP(N) { i =>
      if (i == 0) C(0)(0) = 1
      else {
        REP(4) { j =>
          C(i)(j) = C(i - 1)(j)
        }

        val cnt = i.toString.count(_ != '0')
        if (cnt <= 3) C(i)(cnt) += 1
      }
    }

    def cnt(x: Long): Long = {
      if (x < N) {
        C(x.toInt).sum

      } else if (x >= N && x < 1e12.toLong) {
        val q = (x / N).toInt
        val m = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          res += C(m)(i)
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            res += C(q - 1)(i).toLong * C(N - 1)(j)
          }
        }

        res

      } else {
        val q = (x / N / N).toInt
        val m1 = (x / N % N).toInt
        val m2 = (x % N).toInt

        var res = 0L

        // 10^6以降の値が固定の場合、10^6以下の値も制限される
        REP(4 - len(q)) { i =>
          REP(4 - i) { j =>
            res += C(m1)(i).toLong * C(m2)(j)
          }
        }

        // x-1 以下のの場合は10^6以下が自由になる
        REP(4) { i =>
          REP(4 - i) { j =>
            REP(4 - j) { k =>
              res += C(q - 1)(i).toLong * C(N - 1)(j) * C(N - 1)(k)
            }
          }
        }

        res
      }
    }

    REP(ni()) { _ =>
      val l, r = nl()
      val ans = cnt(r) - cnt(l - 1)
      out.println(ans)
    }
  }

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


There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product si·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.

The first line of the input contains two space-separated integers n and p (3 ≤ n ≤ 100 000, 2 ≤ p ≤ 109) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th shark — two space-separated integers li and ri (1 ≤ li ≤ ri ≤ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.

Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows: (1, 420, 420420): note that s0·s1 = 420, s1·s2 = 176576400, and s2·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1, 420, 420421): now, the product s2·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1, 421, 420420): total is 4000  (1, 421, 420421): total is 0.  (2, 420, 420420): total is 6000.  (2, 420, 420421): total is 6000.  (2, 421, 420420): total is 6000. (2, 421, 420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money.

/**
  * Created by octavian on 01/02/2016.
  */
object Flowers {

  val GIVES = 2 * 1000

  def main(args: Array[String]) {
    //System.setIn(new FileInputStream("./src/flowers.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/flowers.out")))

    val Array(n, p) = readLine.split(" ").map(_.toInt)
    var notProb = Vector.empty[Double]

    for(i <- 0 until n) {
      val Array(a, b) = readLine.split(" ").map(_.toInt)
      val div = b/p - (a - 1)/p
      //println("notDiv is: " + notDiv)
      notProb :+= (b - a + 1 - div).toDouble/(b - a + 1)
    }

    var result: BigDecimal = 0.0
    for(i <- 0 until n) {
      result += GIVES * (1 - notProb(i) * notProb((i + 1)%n))
    }

    println(result)
  }
}

import scala.io.StdIn

object Main {
  final val V = 1000
  def main(args: Array[String]) {
    val Array(n, p) = StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)(0.0)
    for (i <- 0 until n) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)
      a(i) = (r / p - (l - 1) / p).toDouble / (r - l + 1).toDouble
    }
    var ans = 0.0
    for (i <- 0 until n) {
      ans += 1000 * (1 - (1 - a((i + n - 1) % n)) * (1 - a(i)))
      ans += 1000 * (1 - (1 - a(i)) * (1 - a((i + 1) % n)))
    }
    println(ans)
  }
}

import scala.collection.mutable.ListBuffer

object C {
  def main(args: Array[String]) {
    val Array(n, p) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val P = (1 to n).map(x => {
      val q = scala.io.StdIn.readLine.split(" ").map(_.toInt)
      val c2 = q(1) / p
      val c1 = (q(0)-1) / p
      1.0 - 1.0 * (c2-c1)/(q(1) - q(0)+1)
    })

    println((1 to n).map(i => 1.0 - P(i%n)*P((i+1)%n)).sum * 2000)
  }
}

import scala.collection._

object C extends App {

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

  val Array(n, p) = readInts(2)
  val ls, rs = Array.ofDim[Int](n + 1)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }
  ls(n) = ls(0)
  rs(n) = rs(0)

  var res = 0d

  for (i <- 0 until n) {
    val j = if (i == 0) n - 1 else i - 1
    val cnt0 = rs(j) / p - (ls(j) - 1) / p
    val cnt1 = rs(i) / p - (ls(i) - 1) / p
    val cnt2 = rs(i + 1) / p - (ls(i + 1) - 1) / p
    val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)
    val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)
    val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)

    res += 2 * prob1 + prob0 * (1d - prob1) + prob2 * (1d - prob1)
  }

  println(res * 1000d)
}

// So you like object Task
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

object Task {

    def calcProbability(shark: (Long, Long), p: Long): Double = {
        val total = shark._2 - shark._1 + 1
        val prime = shark._2 / p - (shark._1 - 1) / p
        prime.toDouble / total

    }

    def solve(in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val p = in.nextLong()
        val probs = Array.fill(n) { calcProbability((in.nextLong(), in.nextLong()), p) }
        val ones = 4000.0 * probs.sum
        val twos = 2000.0 * (0 until n).map(i => probs(i) * probs((i + 1) % n)).sum
        println(ones - twos)

    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch  {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while(!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

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

    def close(): Unit = {
        inputStream.close()
    }
}

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

object Solution {

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

  def main(args: Array[String]) {
    val Array(n, p) = readInts(2)
    val a = Array.fill[Double](n)(0)

    (1 to n).foreach { i =>
      val Array(l, r) = readInts(2)
      a(i-1) = (r / p - (l - 1) / p).toDouble / (r - l + 1)
    }

    var res: Double = 0
    for (i <- 0 to n-1) {
      res += 2000 * a(i)
      if (i == 0) res += 1000 * (1 - a(i)) * (a(i+1) + a(n-1))
      else if (i == n-1) res += 1000* (1 - a(i)) * (a(0) + a(i-1))
      else res += 1000* (1 - a(i)) * (a(i-1) + a(i+1))
    }

    println(res)

//    Console.withOut(new java.io.BufferedOutputStream(Console.out))
//    println(res.mkString("\n"))
//    Console.flush
  }
}

import scala.collection._

object C extends App {

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

  val Array(n, p) = readInts(2)
  val ls, rs = Array.ofDim[Int](n + 1)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }
  ls(n) = ls(0)
  rs(n) = rs(0)

  var res = 0d

  for (i <- 0 until n) {
    val j = if (i == 0) n - 1 else i - 1
    val cnt0 = rs(j) / p - (ls(j) - 1) / p
    val cnt1 = rs(i) / p - (ls(i) - 1) / p
    val cnt2 = rs(i + 1) / p - (ls(i + 1) - 1) / p
    val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)
    val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)
    val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)

    res += 1d - (1d - prob0) * (1d - prob1) * (1d - prob2)
  }

  println(res * 3000d)
}

import scala.collection._

object C extends App {

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

  val Array(n, p) = readInts(2)
  val ls, rs = Array.ofDim[Int](n + 1)

  for (i <- 0 until n) {
    val Array(l, r) = readInts(2)
    ls(i) = l
    rs(i) = r
  }
  ls(n) = ls(0)
  rs(n) = rs(0)

  var res = 0d

  for (i <- 0 until n) {
    val j = if (i == 0) n - 1 else i - 1
    val cnt0 = rs(j) / p - ls(j) / p
    val cnt1 = rs(i) / p - ls(i) / p
    val cnt2 = rs(i + 1) / p - ls(i + 1) / p
    val prob0 = cnt0.toDouble / (rs(j) - ls(j) + 1)
    val prob1 = cnt1.toDouble / (rs(i) - ls(i) + 1)
    val prob2 = cnt2.toDouble / (rs(i + 1) - ls(i + 1) + 1)

    res += 1d - (1d - prob0) * (1d - prob1) * (1d - prob2)
  }

  println(res * 3000d)
}


In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma - mb, where a is the most loaded server and b is the least loaded one.In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.Write a program to find the minimum number of seconds needed to balance the load of servers.

The first line contains positive number n (1 ≤ n ≤ 105) — the number of the servers.  The second line contains the sequence of non-negative integers m1, m2, ..., mn (0 ≤ mi ≤ 2·104), where mi is the number of tasks assigned to the i-th server.

Print the minimum number of seconds required to balance the load.

NoteIn the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.In the second example the load is already balanced.A possible sequence of task movements for the third example is:  move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5);  then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4);  then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum.toFloat / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s, b + (middle - el).toLong)
    case ((s, b), el) => (s + (el - middle).toLong, b)
  }
  println(Math.max(res._1, res._2))

}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val scanner = new Scanner(System.in)
    def next = scanner.next.toInt

    val count = next
    val sizes = 0.until(count).map(_ => next)

    println(countSwaps(sizes))
  }

  def countSwaps(initialSizes: IndexedSeq[Int]) = {
    val count = initialSizes.size
    val targetSizes = targetSizesClosure(initialSizes)
    val sizes = initialSizes.sorted

    var result = 0
    for (i <- 0 until count) {
      val diff = targetSizes(i) - sizes(i)
      if (diff > 0)
        result += diff
    }

    result
  }

  def targetSizesClosure(initialSizes: IndexedSeq[Int]) = {
    val n = initialSizes.size
    val s = initialSizes.foldLeft(0)(_ + _)
    val d = s / n
    val stair = n - s % n

    index: Int => if (index < stair) d else d + 1
  }
}

/*
 * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/
 */

object Main extends App {
  import java.{util => ju}
  import scala.annotation._
  import scala.collection._
  import scala.collection.{mutable => mu}
  import scala.collection.JavaConverters._
  import scala.math._

  val sc = new ju.Scanner(System.in)
  val n = sc.nextInt
  val m = Array.fill(n)(sc.nextInt).sorted
  val tot = m.sum
  val res = Array.tabulate(n)(i => (tot + i) / n)
  println((0 until n).map(i => (m(i) - res(i)) max 0).sum)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val sum = data.sum
  val middle = sum / n
  if (sum % n == 0) {
    println(data.map(i => Math.abs(middle - i)).sum / 2)
  } else {
    val big = sum % n
    val res = data.foldLeft((0l, 0l)) {
      case ((s, b), el) if el < middle => (s + middle - el, b)
      case ((s, b), el) => (s + el - middle - 1, b + 1)
    }
    println((res._1 + Math.abs(res._2 - big)) / 2)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum.toFloat / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s, b + (middle - el).toLong)
    case ((s, b), el) => (s + (middle - el).toLong, b)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el <= middle => (s + middle - el, b)
    case ((s, b), el) => (s, b + middle - el)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val sum = data.sum
  val middle = sum / n
  if (sum % n == 0) {
    val res = data.map(i => Math.abs(middle - i)).sum
    println( res / 2 + res % 2)
  } else {
    val big = sum % n
    val res = data.foldLeft((0l, 0l)) {
      case ((s, b), el) if el < middle => (s + middle - el, b)
      case ((s, b), el) => (s + el - middle - 1, b + 1)
    }
    val rez = res._1 + Math.abs(res._2 - big)
    println(rez / 2 + rez % 2)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s + middle - el, b)
    case ((s, b), el) => (s, b + middle - el)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  val middle = data.sum.toFloat / n
  val res = data.foldLeft((0l, 0l)) {
    case ((s, b), el) if el < middle => (s + (middle - el).toLong, b)
    case ((s, b), el) => (s, b + (middle - el).toLong)
  }
  println(Math.max(res._1, res._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val sum = data.sum
  val middle = sum / n
  if (sum % n == 0) {
    println(data.map(i => Math.abs(middle - i)).sum / 2)
  } else {
    val big = sum % n
    val res = data.foldLeft((0, 0)) {
      case ((s, b), el) if el < middle => (s + middle - el, b)
      case ((s, b), el) => (s + el - middle - 1, b + 1)
    }
    println((res._1 + Math.abs(res._2 - big)) / 2)

  }

}


Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.There are $$$n$$$ solutions, the $$$i$$$-th of them should be tested on $$$a_i$$$ tests, testing one solution on one test takes $$$1$$$ second. The solutions are judged in the order from $$$1$$$ to $$$n$$$. There are $$$k$$$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.At any time moment $$$t$$$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $$$i$$$, then it is being tested on the first test from time moment $$$t$$$ till time moment $$$t + 1$$$, then on the second test till time moment $$$t + 2$$$ and so on. This solution is fully tested at time moment $$$t + a_i$$$, and after that the testing process immediately starts testing another solution.Consider some time moment, let there be exactly $$$m$$$ fully tested solutions by this moment. There is a caption "System testing: $$$d$$$%" on the page with solutions, where $$$d$$$ is calculated as$$$$$$d = round\left(100\cdot\frac{m}{n}\right),$$$$$$where $$$round(x) = \lfloor{x + 0.5}\rfloor$$$ is a function which maps every real to the nearest integer.Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $$$q$$$, and the caption says "System testing: $$$q$$$%". Find the number of interesting solutions.Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.

The first line contains two positive integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1000$$$, $$$1 \le k \le 100$$$) standing for the number of submissions and the number of testing processes respectively. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 150$$$), where $$$a_i$$$ is equal to the number of tests the $$$i$$$-th submission is to be run on.

Output the only integer — the number of interesting submissions.

NoteConsider the first example. At time moment $$$0$$$ both solutions start testing. At time moment $$$49$$$ the first solution is fully tested, so at time moment $$$49.5$$$ the second solution is being tested on the test $$$50$$$, and the caption says "System testing: $$$50$$$%" (because there is one fully tested solution out of two). So, the second solution is interesting.Consider the second example. At time moment $$$0$$$ the first and the second solutions start testing. At time moment $$$32$$$ the first solution is fully tested, the third solution starts testing, the caption says "System testing: $$$25$$$%". At time moment $$$32 + 24.5 = 56.5$$$ the third solutions is being tested on test $$$25$$$, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment $$$32 + 33 = 65$$$, the fourth solution is fully tested at time moment $$$65 + 1 = 66$$$. The captions becomes "System testing: $$$75$$$%", and at time moment $$$74.5$$$ the second solution is being tested on test $$$75$$$. So, this solution is also interesting. Overall, there are two interesting solutions.

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 A = na(N)
    var p = 0
    val W = Array.ofDim[Int](K, 3) // (cur, size, pos)

    var m = -K // 最初に読み込む分減らしておく
    val end = Array.ofDim[Boolean](K)
    val interesting = Array.ofDim[Boolean](N)
    var t = 0
    while(m < N) {
      REP(K) { i =>
        if (!end(i) && W(i)(0) >= W(i)(1)) {
          m += 1
          if (p == N) {
            end(i) = true
            debug(s"$t m:$m")
          } else {
            W(i)(0) = 1
            W(i)(1) = A(p) + 1
            W(i)(2) = p
            p += 1
            debug(s"$t: p:$p")
          }
        }
      }

      val caption = math.round(100.toDouble * m / N)
//      debug(s"$t $caption")
      REP(K) { i =>
        if (!end(i) && caption == W(i)(0)) {
          debug(s"$t: caption:$caption ${W(i)(0)} ${W(i)(1)} ${W(i)(2)}")
          interesting(W(i)(2)) = true
        }
      }

      REP(K) { i =>
        if (!end(i)) W(i)(0) += 1
      }
      t += 1
    }

    val ans = interesting.count(identity)
    out.println(ans)

  }

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


You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is a vertex number $$$1$$$.A tree is a connected undirected graph with $$$n-1$$$ edges.You are given $$$m$$$ queries. The $$$i$$$-th query consists of the set of $$$k_i$$$ distinct vertices $$$v_i[1], v_i[2], \dots, v_i[k_i]$$$. Your task is to say if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. The next $$$m$$$ lines describe queries. The $$$i$$$-th line describes the $$$i$$$-th query and starts with the integer $$$k_i$$$ ($$$1 \le k_i \le n$$$) — the number of vertices in the current query. Then $$$k_i$$$ integers follow: $$$v_i[1], v_i[2], \dots, v_i[k_i]$$$ ($$$1 \le v_i[j] \le n$$$), where $$$v_i[j]$$$ is the $$$j$$$-th vertex of the $$$i$$$-th query. It is guaranteed that all vertices in a single query are distinct. It is guaranteed that the sum of $$$k_i$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum\limits_{i=1}^{m} k_i \le 2 \cdot 10^5$$$).

For each query, print the answer — "YES", if there is a path from the root to some vertex $$$u$$$ such that each of the given $$$k$$$ vertices is either belongs to this path or has the distance $$$1$$$ to some vertex of this path and "NO" otherwise.

NoteThe picture corresponding to the example:Consider the queries.The first query is $$$[3, 8, 9, 10]$$$. The answer is "YES" as you can choose the path from the root $$$1$$$ to the vertex $$$u=10$$$. Then vertices $$$[3, 9, 10]$$$ belong to the path from $$$1$$$ to $$$10$$$ and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which also belongs to this path.The second query is $$$[2, 4, 6]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=2$$$. Then the vertex $$$4$$$ has distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$6$$$ has distance $$$1$$$ to the vertex $$$2$$$ which belongs to this path.The third query is $$$[2, 1, 5]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=5$$$ and all vertices of the query belong to this path.The fourth query is $$$[4, 8, 2]$$$. The answer is "YES" as you can choose the path to the vertex $$$u=9$$$ so vertices $$$2$$$ and $$$4$$$ both have distance $$$1$$$ to the vertex $$$1$$$ which belongs to this path and the vertex $$$8$$$ has distance $$$1$$$ to the vertex $$$7$$$ which belongs to this path.The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex $$$u$$$.

import scala.collection.mutable

object E {
  import InOut._
  def main(args: Array[String]): Unit = {}

  val n, m = nextInt

  val adjs = {
    val adjBuilders = Array.fill(n) { new mutable.ArrayBuilder.ofInt }
    for (_ <- 1 until n) {
      val u, v = nextInt - 1
      adjBuilders(u) += v
      adjBuilders(v) += u
    }
    adjBuilders.map(_.result())
  }

  val depths, parents, tIn, tOut = Array.fill(n)(0)
  var t = 0

  def dfs(u: Int, p: Int, depth: Int): Unit = {
    tIn(u) = t
    t += 1
    parents(u) = p
    depths(u) = depth
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != p) {
        dfs(v, u, depth + 1)
      }
      i += 1
    }
    tOut(u) = t
    t += 1
  }

  dfs(0, 0, 0)

  for (_ <- 1 to m) {
    val k = nextInt
    val vs = nextInts(k).map(_ - 1)
    val deepest = vs.maxBy(depths)
    val hasAll = vs.forall { v =>
      val p = parents(v)
      tIn(p) <= tIn(deepest) && tOut(p) >= tOut(deepest)
    }
    out.println(if (hasAll) "YES" else "NO")
  }

  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

import scala.collection.mutable

object E {
  import InOut._
  def main(args: Array[String]): Unit = {}

  val n, m = nextInt
  val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }
  for (_ <- 1 until n) {
    val u, v = nextInt - 1
    adjBuilders(u) += v
    adjBuilders(v) += u
  }
  val adjs = adjBuilders.map(_.result())

  val depths = Array.fill(n)(0)
  val pathSets = Array.ofDim[Set[Int]](n)

  def dfs(u: Int, p: Int, depth: Int, pathSet: Set[Int]): Unit = {
    //parents(u) = p
    depths(u) = depth
    var pathSetHere = pathSet
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != p) {
        pathSetHere += v
      }
      i += 1
    }
    pathSets(u) = pathSetHere
    i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != p) {
        dfs(v, u, depth + 1, pathSetHere)
      }
      i += 1
    }
  }

  dfs(0, -1, 0, Set(0))

  for (_ <- 1 to m) {
    val k = nextInt
    val vs = nextInts(k)
    var i = 0
    var node = 0
    while (i < vs.length) {
      val v = vs(i) - 1
      if (depths(v) > depths(node)) node = v
      i += 1
    }
    val pathSet = pathSets(node)
    val hasAll = vs.forall(pathSet)
    out.println(if (hasAll) "YES" else "NO")
  }

  out.flush()

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}