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.

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
)

func MIN(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}

func MAX(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		ARRAY := make([]int, n)

		ZEROO := 0
		ONE := 0
		TWO := 0
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARRAY[i])
			if ARRAY[i]%3 == 0 {
				ZEROO = ZEROO + 1
			}
			if ARRAY[i]%3 == 1 {
				ONE = ONE + 1
			}
			if ARRAY[i]%3 == 2 {
				TWO = TWO + 1
			}
		}

		k := int(n / 3)

		if ONE == k && TWO == k && ZEROO == k {
			fmt.Println(0)
		} else {
			if ONE == k || TWO == k || ZEROO == k {
				if ONE == k {
					if TWO > ZEROO {
						fmt.Println(TWO - k)
					} else {
						fmt.Println(2*k - 2*TWO)
					}
				}
				if TWO == k {
					if ZEROO > ONE {
						fmt.Println(ZEROO - k)
					} else {
						fmt.Println(2*k - 2*ZEROO)
					}
				}
				if ZEROO == k {
					if ONE > TWO {
						fmt.Println(ONE - k)
					} else {
						fmt.Println(2*k - 2*ONE)
					}
				}
			} else {
				if ONE > k {
					if ZEROO < k {
						fmt.Println(ONE - ZEROO)
					} else {
						fmt.Println(ZEROO - TWO)
					}
				}
				if TWO > k && ONE < k {
					fmt.Println(TWO - ONE)
				}
				if ZEROO > k && ONE < k && TWO < k {
					fmt.Println(ZEROO - TWO)
				}
			}

		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
)

func MIN(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}

func MAX(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		ARRAY := make([]int, n)

		ZERO := 0
		ONE := 0
		TWO := 0
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARRAY[i])
			if ARRAY[i]%3 == 0 {
				ZERO = ZERO + 1
			}
			if ARRAY[i]%3 == 1 {
				ONE = ONE + 1
			}
			if ARRAY[i]%3 == 2 {
				TWO = TWO + 1
			}
		}

		k := int(n / 3)

		if ONE == k && TWO == k && ZERO == k {
			fmt.Println(0)
		} else {
			if ONE == k || TWO == k || ZERO == k {
				if ONE == k {
					if TWO > ZERO {
						fmt.Println(TWO - k)
					} else {
						fmt.Println(2*k - 2*TWO)
					}
				}
				if TWO == k {
					if ZERO > ONE {
						fmt.Println(ZERO - k)
					} else {
						fmt.Println(2*k - 2*ZERO)
					}
				}
				if ZERO == k {
					if ONE > TWO {
						fmt.Println(ONE - k)
					} else {
						fmt.Println(2*k - 2*ONE)
					}
				}
			} else {
				if ONE > k {
					if ZERO < k {
						fmt.Println(ONE - ZERO)
					} else {
						fmt.Println(ZERO - TWO)
					}
				}
				if TWO > k && ONE < k {
					fmt.Println(TWO - ONE)
				}
				if ZERO > k && ONE < k && TWO < k {
					fmt.Println(ZERO - TWO)
				}
			}

		}
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	//"math"
	"os"
)

func run(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)
	defer out.Flush()

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var n int
		Fscan(in, &n)
		bucket := make([]int, 3)

		for i := 0; i < n; i++ {
			var num int
			Fscan(in, &num)
			bucket[num % 3]++
		}

		ans := 0
		for i := 0; i < 6; i++ {
			for j, val := range bucket {
				if val > n / 3 {
					move := val - n / 3
					bucket[j] -= move
					bucket[(j+1) % 3] += move
					ans += move
				}
			}
		}
		Fprintln(out, ans)
	}

}

func main() { run(os.Stdin, os.Stdout) }

func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	//"math"
	"os"
)

func run(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)
	defer out.Flush()

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var n int
		Fscan(in, &n)
		bucket := make([]int, 3)

		for i := 0; i < n; i++ {
			var num int
			Fscan(in, &num)
			bucket[num % 3]++
		}

		var vec, target []int
		for i, val := range bucket {
			if val < n / 3 {
				vec = append(vec, i)
			} else {
				target = append(target, i)
			}
		}
		ans := 0
		if len(vec) == 1 {
			for i, val := range bucket {
				if (i + 1) % 3 == vec[0] {
					ans += val - n / 3
				} else if (i + 2) % 3 == vec[0] {
					ans += (val - n / 3) << 1
				}
			}

		} else if len(target) == 1 {
			ans += n / 3 - bucket[(target[0] + 1) % 3]
			ans += 2 * (n / 3 - bucket[(target[0] + 2) % 3])
		}
		Fprintln(out, ans)
	}

}

func main() { run(os.Stdin, os.Stdout) }

func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

func sstring() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		n := sint64()
		a := sint64s(n)
		printf("%d\n", sol(n, a))
	}
}

func sol(n int64, a []int64) int64 {
	m := [3]int64{0, 0, 0}
	for i := range a {
		m[a[i]%3]++
	}
	ret := int64(0)
	t := n / 3
	for range "xx" {
		for i := range m {
			if m[i] > t {
				diff := m[i] - t
				ret += diff
				m[i] -= diff
				m[(i+1)%3] += diff
			}
		}
	}
	if !(m[0] == t && m[1] == t && m[2] == t) {
		panic("oh no")
	}
	return ret
}

func max(a ...int64) int64 {
	ret := a[0]
	for _, i := range a {
		if i > ret {
			ret = i
		}
	}
	return ret
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 4096), 1e9)
	// this template is new version.
	// use getI(), getS(), getInts(), getF()
	cases := getI()
	forEach(int(cases), func(i int) {
		arrLen := getI()
		nums := getInts(arrLen)
		rems := [3]int64{0, 0, 0}
		forEach(len(nums), func(i int) {
			rems[nums[i]%3]++
		})
		var moves int64
		for (rems[0] != rems[1]) || (rems[1] != rems[2]) {
			if rems[0] > rems[1] {
				moves++
				rems[0]--
				rems[1]++
			}

			if rems[1] > rems[2] {
				moves++
				rems[1]--
				rems[2]++
			}

			if rems[2] > rems[0] {
				moves++
				rems[2]--
				rems[0]++
			}
		}
		out(moves)
	})
}

// !------- HELPERS -------!

func out(x ...interface{}) {
	fmt.Fprintln(wr, x...)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(wr, f, a...)
}

func getI() int64 {
	s := getS()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func getF() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int64) []int64 {
	ret := make([]int64, N)
	for i := range ret {
		ret[i] = getI()
	}
	return ret
}

func getS() string {
	if !sc.Scan() {
		panic(sc.Err())
	}
	return sc.Text()
}

func sortInts(data []int64) {
	sort.Slice(data, func(i, j int) bool { return data[i] < data[j] })
}

func joinInts(s []int64) string {
	return strings.Trim(fmt.Sprintf("%v", s), "[]")
}

func forEach(n int, fn func(int)) {
	for i := 0; i < n; i++ {
		fn(i)
	}
}

// min, max, asub, abs
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

func min(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

// min for n entry
func nmin(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = min(ret, e)
	}
	return ret
}

// max for n entry
func nmax(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

func asub(a, b int64) int64 {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, 4096), 1e9)
	// this template is new version.
	// use getI(), getS(), getInts(), getF()
	cases := getI()
	forEach(int(cases), func(i int) {
		arrLen := getI()
		nums := getInts(arrLen)
		rems := []int64{0, 0, 0}
		forEach(len(nums), func(i int) {
			rems[nums[i]%3]++
		})
		var moves int64
		for (rems[0] != rems[1]) || (rems[1] != rems[2]) {
			if rems[0] > rems[1] {
				moves++
				rems[0]--
				rems[1]++
			}

			if rems[1] > rems[2] {
				moves++
				rems[1]--
				rems[2]++
			}

			if rems[2] > rems[0] {
				moves++
				rems[2]--
				rems[0]++
			}
		}
		out(moves)
	})
}

// !------- HELPERS -------!

func out(x ...interface{}) {
	fmt.Fprintln(wr, x...)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(wr, f, a...)
}

func getI() int64 {
	s := getS()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func getF() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func getInts(N int64) []int64 {
	ret := make([]int64, N)
	for i := range ret {
		ret[i] = getI()
	}
	return ret
}

func getS() string {
	if !sc.Scan() {
		panic(sc.Err())
	}
	return sc.Text()
}

func sortInts(data []int64) {
	sort.Slice(data, func(i, j int) bool { return data[i] < data[j] })
}

func joinInts(s []int64) string {
	return strings.Trim(fmt.Sprintf("%v", s), "[]")
}

func forEach(n int, fn func(int)) {
	for i := 0; i < n; i++ {
		fn(i)
	}
}

// min, max, asub, abs
func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

func min(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

// min for n entry
func nmin(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = min(ret, e)
	}
	return ret
}

// max for n entry
func nmax(a ...int64) int64 {
	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

func asub(a, b int64) int64 {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int64) int64 {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int64, x int64) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

package main

import (
    "bufio"
    "io"
    "os"
    . "fmt"
    // . "math"
)
var input io.Reader = bufio.NewReader(os.Stdin)
func main() {
    var t int
    Fscan(input, &t)
    for i := 0; i < t; i++ {
        var n int
        Fscan(input, &n)
        a := make([]int, n)

        ans := 0
        x := make([]int, 3)
        for i := 0; i < n; i++ {
            Fscan(input, &a[i])
            x[a[i]%3] ++
        }

        // for i := 0; i < 3; i++ {
        //     Print(x[i], " ")
        // }
        // Println()

        for i := 0; i < 2; i++ {
            for j := 0; j < 3; j++ {
                if x[j] > n / 3 {
                    ans += x[j] - n / 3
                    x[(j + 1) % 3] += x[j] - n / 3
                    x[j] = n / 3
                }
            }
        }
        Println(ans)
    }
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

var (
	in  = bufio.NewReader(os.Stdin)
	out = bufio.NewWriter(os.Stdout)
)

func scan(a ...interface{}) {
	fmt.Fscan(in, a...)
}
func printf(f string, a ...interface{}) {
	fmt.Fprintf(out, f, a...)
}

func solve() {
	var n, x int
	scan(&n)
	var a [3]int
	for i := 0; i < n; i++ {
		scan(&x)
		a[x%3]++
	}
	m := int(n / 3)
	i20 := math.Max(0, math.Min(float64(m-a[0]), math.Max(0, float64(a[2]-m))))
	i21 := math.Max(0, math.Min(float64(m-a[1]), math.Max(0, float64(a[2]-m))))

	i01 := math.Max(0, math.Min(float64(m-a[1]), math.Max(0, float64(a[0]-m))))
	i02 := math.Max(0, math.Min(float64(m-a[2]), math.Max(0, float64(a[0]-m))))

	i12 := math.Max(0, math.Min(float64(m-a[2]), math.Max(0, float64(a[1]-m))))
	i10 := math.Max(0, math.Min(float64(m-a[0]), math.Max(0, float64(a[1]-m))))
	printf("%d\n", int((i20+i01+i12)+(i21+i02+i10)*2))
}
func main() {
	defer out.Flush()
	n := 0
	scan(&n)
	for i := 0; i < n; i++ {
		solve()
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		var t0, t1, t2 int
		for i := 0; i < n; i++ {
			var v int
			fmt.Fscan(in, &v)
			if v%3 == 0 {
				t0++
			} else if v%3 == 1 {
				t1++
			} else {
				t2++
			}
		}

		z := n / 3
		var tot int
		if t0 < z {
			g := max(0, min(z-t0, t2-z))
			t0 += g
			t2 -= g
			tot += g

			g = max(0, min(z-t0, t1-z))
			t0 += g
			t1 -= g
			tot += (g * 2)
		}
		if t1 < z {
			g := max(0, min(z-t1, t0-z))
			t1 += g
			t0 -= g
			tot += g

			g = max(0, min(z-t1, t2-z))
			t1 += g
			t2 -= g
			tot += (g * 2)
		}
		if t2 < z {
			g := max(0, min(z-t2, t1-z))
			t2 += g
			t1 -= g
			tot += g

			g = max(0, min(z-t2, t0-z))
			t2 += g
			t0 -= g
			tot += (g * 2)
		}
		fmt.Fprintln(out, tot)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	reader  = bufio.NewReader(os.Stdin)
	t, n, b int
)

func solve(n int, c [3]int) int {
	var x int
	for c[0] != n/3 || c[1] != n/3 || c[2] != n/3 {
		if c[0] > n/3 {
			x += c[0] - n/3
			c[1] += c[0] - n/3
			c[0] = n / 3
		} else if c[1] > n/3 {
			x += c[1] - n/3
			c[2] += c[1] - n/3
			c[1] = n / 3
		} else {
			x += c[2] - n/3
			c[0] += c[2] - n/3
			c[2] = n / 3
		}
	}
	return x
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		var c [3]int
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &b)
			c[b%3]++
		}
		fmt.Println(solve(n, c))
	}
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func scanf(f string, args ...interface{})  { fmt.Fscanf(reader, f, args...) }
func printf(f string, args ...interface{}) { fmt.Fprintf(writer, f, args...) }

func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}

func getMinElement(arr []int) int {
	m := int(math.MaxInt32)
	for i := 0; i < 3; i++ {
		m = min(m, arr[i])
	}
	return m
}

func main() {
	defer writer.Flush()

	var t int
	scanf("%d\n", &t)

	for t > 0 {
		var n int
		scanf("%d\n", &n)
		arr := make([]int, n)
		cnt := make([]int, 3)
		for i := 0; i < n; i++ {
			if i == n-1 {
				scanf("%d\n", &arr[i])
			} else {
				scanf("%d ", &arr[i])
			}
			cnt[arr[i]%3]++ // storing the counts of remainders
		}

		ans := 0
		for getMinElement(cnt) != n/3 {
			for i := 0; i < 3; i++ {
				if cnt[i] > n/3 {
					ans++
					cnt[i]--
					cnt[(i+1)%3]++
				}
			}
		}
		printf("%d\n", ans)
		t--
	}
}

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		res := solve(A)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(A []int) int {
	cnt := make([]int, 3)
	for _, a := range A {
		cnt[a%3]++
	}
	expect := len(A) / 3
	// 0 -> 1 -> 2 -> 0
	var res int
	change := func(a, b, c int) {
		if cnt[a] < expect && cnt[c] > expect {
			x := min(expect-cnt[a], cnt[c]-expect)
			res += x
			cnt[a] += x
			cnt[c] -= x
		}

		if cnt[a] < expect && cnt[b] > expect {
			x := min(expect-cnt[a], cnt[b]-expect)
			res += 2 * x
			cnt[a] += x
			cnt[b] -= x
		}
	}

	change(0, 1, 2)
	change(1, 2, 0)
	change(2, 0, 1)

	return res
}

func min(a, b int) int {
	if a <= b {
		return a
	}
	return b
}

package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

var bytes []byte

func nextByte() byte {
	b := bytes[0]
	bytes = bytes[1:]
	return b
}

func ScanInt64() int64 {
	var negative bool
	var result int64

	b := nextByte()

	for ; b < '0' || b > '9'; b = nextByte() {
		if b == '-' {
			negative = true
		}
	}

	for ; '0' <= b && b <= '9'; b = nextByte() {
		result = (result << 3) + (result << 1) + int64(b-'0')
	}

	if negative {
		return -result
	} else {
		return result
	}
}

func ScanInt() int {
	return int(ScanInt64())
}

func ScanString() string {
	builder := strings.Builder{}

	for b := nextByte(); b != '\r'; b = nextByte() {
		if b != '\n' {
			builder.WriteByte(b)
		}
	}

	return builder.String()
}

func init() {
	f, err := os.Open("in.txt")

	if err == nil {
		defer f.Close()
	} else {
		f = os.Stdin
	}

	bytes, _ = ioutil.ReadAll(bufio.NewReader(f))
}

func main() {
	for t := ScanInt(); t > 0; t-- {
		n := ScanInt()
		var c [3]int

		for i := 0; i < n; i++ {
			a := ScanInt()
			c[a%3]++
		}

		moves := 0

		for i := 0; i < 6; i++ {
			curr := i % 3
			next := (i + 1) % 3
			goal := n / 3

			if c[curr] > goal {
				moves += c[curr] - goal
				c[next] += c[curr] - goal
				c[curr] = goal
			}
		}

		fmt.Println(moves)
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1490B(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	max := func(a, b int) int {
		if a > b {
			return a
		}
		return b
	}

	var T, n, v int
	for Fscan(in, &T); T > 0; T-- {
		c := [3]int{}
		for Fscan(in, &n); n > 0; n-- {
			Fscan(in, &v)
			c[v%3]++
		}
		Fprintln(out, max(max(c[1]-c[0], c[2]-c[1]), c[0]-c[2]))
	}
}

func main() { CF1490B(os.Stdin, os.Stdout) }

package main

import (
	. "fmt"
	"os"
	"bufio"
)

func main(){
	in := bufio.NewReader(os.Stdin);
	out := bufio.NewWriter(os.Stdout);
 	defer out.Flush();
 	var t int;
 	Fscan(in, &t);
 	for i:=0;i<t;i++ {
 		var n int;
 		Fscan(in, &n);
 		a := make([]int, n);

 		c := make([]int, 3);
 		for i:=0;i<n;i++ {
 			Fscan(in, &a[i]);
 			c[a[i]%3]++;
 		}
 		ans := 0;
 		for j:=0;j<2;j++ {
	 		for i:=0;i<3;i++ {
	 			if c[i] > n/3 {
	 				ans += c[i]-n/3;
	 				c[(i+1)%3] += c[i]-n/3;
	 				c[i] = n/3;
	 			}
	 		}
	 	}
 		Fprint(out, ans, "\n");
 	}
 }

package main

import (
	"bufio"
	. "fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T, n, no, c, c0, c1, c2 int
	c = 0
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n)
		for i := 0; i < n; i++ {
			Fscan(in, &no)
			if no%3 == 0 {
				c0++
			} else if no%3 == 1 {
				c1++
			} else {
				c2++
			}
		}
		av := (c0 + c1 + c2) / 3
		if c0 > av {
			c += c0 - av
			if c+c1 > av {
				c += c + c1 - av
			} else {
				c += (av - c - c1) * 2
			}
		} else {
			c += (av - c0)
			if c2-c > av {
				c += (c2 - c - av) * 2
			} else {
				c += (av - c2 + c)
			}
		}

		Fprintln(out, c)
		c = 0
		c0, c1, c2 = 0, 0, 0
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
)

func MIN(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}

func MAX(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		ARRAY := make([]int, n)

		ZERO := 0
		ONE := 0
		TWO := 0
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARRAY[i])
			if ARRAY[i]%3 == 0 {
				ZERO = ZERO + 1
			}
			if ARRAY[i]%3 == 1 {
				ONE = ONE + 1
			}
			if ARRAY[i]%3 == 2 {
				TWO = TWO + 1
			}
		}

		k := int(n / 3)

		if ONE == k && TWO == k && ZERO == k {
			fmt.Println(0)
		} else {
			if ONE == k || TWO == k || ZERO == k {
				if ONE == k {
					if TWO > ZERO {
						fmt.Println(TWO - k)
					} else {
						fmt.Println(2*TWO - 2*k)
					}
				}
				if TWO == k {
					if ZERO > ONE {
						fmt.Println(ZERO - k)
					} else {
						fmt.Println(2*ZERO - 2*k)
					}
				}
				if ZERO == k {
					if ONE > TWO {
						fmt.Println(ONE - k)
					} else {
						fmt.Println(2*ONE - 2*k)
					}
				}
			} else {
				if ONE > k {
					if ZERO < k {
						fmt.Println(ONE - ZERO)
					} else {
						fmt.Println(ZERO - TWO)
					}
				}
				if TWO > k && ONE < k {
					fmt.Println(TWO - ONE)
				}
				if ZERO > k && ONE < k && TWO < k {
					fmt.Println(ZERO - TWO)
				}
			}

		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
)

func MIN(x, y int) int {
	if x > y {
		return y
	} else {
		return x
	}
}

func MAX(x, y int) int {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })
var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		ARRAY := make([]int, n)

		ZERO := 0
		ONE := 0
		TWO := 0
		for i := 0; i < n; i++ {
			fmt.Fscan(input, &ARRAY[i])
			if ARRAY[i]%3 == 0 {
				ZERO = ZERO + 1
			}
			if ARRAY[i]%3 == 1 {
				ONE = ONE + 1
			}
			if ARRAY[i]%3 == 2 {
				TWO = TWO + 1
			}
		}

		k := int(n / 3)

		if ONE == k && TWO == k && ZERO == k {
			fmt.Println(0)
		} else {
			if ONE == k || TWO == k || ZERO == k {
				if ONE == k {
					if TWO > ZERO {
						fmt.Println(TWO - k)
					} else {
						fmt.Println(2*TWO - 2*k)
					}
				}
				if TWO == k {
					if ZERO > ONE {
						fmt.Println(ZERO - k)
					} else {
						fmt.Println(2*ZERO - 2*k)
					}
				}
				if ZERO == k {
					if ONE > TWO {
						fmt.Println(ONE - k)
					} else {
						fmt.Println(2*ONE - 2*k)
					}
				}
			} else {
				if ONE > k {
					if ZERO < k {
						fmt.Println(ONE - TWO)
					} else {
						fmt.Println(ZERO - TWO)
					}
				}
				if TWO > k && ONE < k {
					fmt.Println(TWO - ONE)
				}
				if ZERO > k && ONE < k && TWO < k {
					fmt.Println(ZERO - TWO)
				}
			}

		}
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	//"math"
	"os"
)

func run(r io.Reader, w io.Writer) {
	in := bufio.NewReader(r)
	out := bufio.NewWriter(w)
	defer out.Flush()

	var t int
	for Fscan(in, &t); t > 0; t-- {
		var n int
		Fscan(in, &n)
		bucket := make([]int, 3)

		for i := 0; i < n; i++ {
			var num int
			Fscan(in, &num)
			bucket[num % 3]++
		}

		var vec, target []int
		for i, val := range bucket {
			if val < n / 3 {
				vec = append(vec, i)
			} else {
				target = append(target, i)
			}
		}
		ans := 0
		if len(vec) == 1 {
			multiplier := 1
			for i, val := range bucket {
				if i == vec[0] {
					continue
				}
				ans += multiplier * (val - n / 3)
				multiplier <<= 1
			}

		} else if len(target) == 1 {
			ans += n / 3 - bucket[(target[0] + 1) % 3]
			ans += 2 * (n / 3 - bucket[(target[0] + 2) % 3])
		}
		Fprintln(out, ans)
	}

}

func main() { run(os.Stdin, os.Stdout) }

func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

func sstring() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		n := sint64()
		a := sint64s(n)
		printf("%d\n", sol(n, a))
	}
}

func sol(n int64, a []int64) int64 {
	m := [3]int64{0, 0, 0}
	for i := range a {
		m[a[i]%3]++
	}
	mx := max(m[0], m[1], m[2])
	i := 0
	for m[i] != mx { // land on max
		i++
	}
	t := n / 3
	ret := int64(0)
	for j := 0; j < 3; j++ {
		p := (i + j) % 3
		tmp := m[p]
		diff := tmp - t // tmp > t
		ret += diff
		m[p] -= diff
		m[(p+1)%3] += diff
	}
	if !(m[0] == t && m[1] == t && m[2] == t) {
		panic("oh no")
	}
	return ret
}

func max(a ...int64) int64 {
	ret := a[0]
	for _, i := range a {
		if i > ret {
			ret = i
		}
	}
	return ret
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

func init() {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 4096), 1e9)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	s := sstring()
	i := int64(0)
	if s[0] == '-' {
		for _, r := range s[1:] {
			i *= 10
			i -= int64(r - '0')
		}
		return i
	}
	for _, r := range s {
		i *= 10
		i += int64(r - '0')
	}
	return i
}

func sint64s(n int64) []int64 {
	a := make([]int64, n)
	for i := range a {
		a[i] = sint64()
	}
	return a
}

func sstring() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func main() {
	defer writer.Flush()
	for t := sint64(); t > 0; t-- {
		n := sint64()
		a := sint64s(n)
		printf("%d\n", sol(n, a))
	}
}

func sol(n int64, a []int64) int64 {
	m := []int64{0, 0, 0}
	for i := range a {
		m[a[i]%3]++
	}
	mx := max(m...)
	i := 0
	for m[i] != mx {
		i++
	}
	t := n / 3
	ret := int64(0)
	for j := 0; j < 3; j++ {
		p := (i + j) % 3
		tmp := m[p]
		diff := tmp - t // tmp > t
		ret += diff
		m[p] -= diff
		m[(p+1)%3] += diff
	}
	return ret
}

func max(a ...int64) int64 {
	ret := a[0]
	for _, i := range a {
		if i > ret {
			ret = i
		}
	}
	return ret
}

package main

import (
    "bufio"
    "io"
    "os"
    . "fmt"
    // . "math"
)
var input io.Reader = bufio.NewReader(os.Stdin)
func main() {
    var t int
    Fscan(input, &t)
    for i := 0; i < t; i++ {
        var n int
        Fscan(input, &n)
        a := make([]int, n)

        ans := 0
        x := make([]int, 3)
        for i := 0; i < n; i++ {
            Fscan(input, &a[i])
            x[a[i]%3] ++
        }

        // for i := 0; i < 3; i++ {
        //     Print(x[i], " ")
        // }
        // Println()

        for i := 0; i < 2; i++ {
            for j := 0; j < 3; j++ {
                if x[j] > n / 3 {
                    ans += x[j] - n / 3
                    x[(j + 1) / 3] += x[j] - n / 3
                    x[j] = n / 3
                }
            }
        }
        Println(ans)
    }
}


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]$$$.

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

var dp = [22][11][2]int64{}
var vis = [22][11][2]bool{}
var n int
var s string

func fun(pos, cur, is int) int64 {
	if cur > 3 {
		return 0
	}
	if pos == n {
		return 1
	}
	if vis[pos][cur][is] {
		return dp[pos][cur][is]
	}
	vis[pos][cur][is] = true
	var res int64
	if is == 1 {
		if s[pos] == '0' {
			res = fun(pos+1, cur, 1)
		} else {
			res = fun(pos+1, cur+1, 1)
			for i := '0'; i < rune(s[pos]); i = i + 1 {
				if i == '0' {
					res = res + fun(pos+1, cur, 0)
				} else {
					res = res + fun(pos+1, cur+1, 0)
				}
			}
		}
	} else {
		for i := '0'; i <= '9'; i = i + 1 {
			if i == '0' {
				res = res + fun(pos+1, cur, 0)
			} else {
				res = res + fun(pos+1, cur+1, 0)
			}
		}
	}
	dp[pos][cur][is] = res
	return res
}

func main() {
	defer writer.Flush()
	var T int
	var l, r, ans int64
	scanf("%d\n", &T)
	for t := 0; t < T; t = t + 1 {
		dp = [22][11][2]int64{}
		vis = [22][11][2]bool{}
		scanf("%d %d\n", &l, &r)
		s = strconv.FormatInt(r, 10)
		n = len(s)

		ans = fun(0, 0, 1)

		dp = [22][11][2]int64{}
		vis = [22][11][2]bool{}
		l = l - 1
		s = strconv.FormatInt(l, 10)
		n = len(s)
		//printf("%d\n", ans)
		ans = ans - fun(0, 0, 1)
		printf("%d\n", ans)

	}

}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"strconv"
)

// github.com/EndlessCheng/codeforces-go
func CF1036C(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	calc := func(u int64) int {
		s := strconv.FormatInt(u, 10)
		n := len(s)
		dp := make([][4]int, n)
		for i := range dp {
			for j := range dp[i] {
				dp[i][j] = -1
			}
		}
		var f func(p, sum int, isUpper bool) int
		f = func(p, sum int, isUpper bool) (cnt int) {
			if sum > 3 {
				return
			}
			if p >= n {
				return 1
			}
			dv := &dp[p][sum]
			if !isUpper && *dv >= 0 {
				return *dv
			}
			defer func() {
				if !isUpper {
					*dv = cnt
				}
			}()
			up := byte('9')
			if isUpper {
				up = s[p]
			}
			for digit := byte('0'); digit <= up; digit++ {
				tmp := sum
				if digit > '0' {
					tmp++
				}
				cnt += f(p+1, tmp, isUpper && digit == up)
			}
			return
		}
		return f(0, 0, true)
	}

	var t, l, r int64
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &l, &r)
		Fprintln(out, calc(r)-calc(l-1))
	}
}

func main() { CF1036C(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }

var dp = [22][11][2]int64{}
var vis = [22][11][2]bool{}
var n int
var s string

func fun(pos, cur, is int) int64 {
	if cur > 3 {
		return 0
	}
	if pos == n {
		return 1
	}
	if vis[pos][cur][is] {
		return dp[pos][cur][is]
	}
	vis[pos][cur][is] = true
	var res int64
	if is == 1 {
		if s[pos] == '0' {
			res = fun(pos+1, 0, 1)
		} else {
			res = fun(pos+1, cur+1, 1)
			for i := '0'; i < rune(s[pos]); i = i + 1 {
				if i == '0' {
					res = res + fun(pos+1, 0, 0)
				} else {
					res = res + fun(pos+1, cur+1, 0)
				}
			}
		}
	} else {
		for i := '0'; i <= '9'; i = i + 1 {
			if i == '0' {
				res = res + fun(pos+1, 0, 0)
			} else {
				res = res + fun(pos+1, cur+1, 0)
			}
		}
	}
	dp[pos][cur][is] = res
	return res
}

func main() {
	defer writer.Flush()
	var T int
	var l, r, ans int64
	scanf("%d\n", &T)
	for t := 0; t < T; t = t + 1 {
		dp = [22][11][2]int64{}
		vis = [22][11][2]bool{}
		scanf("%d %d\n", &l, &r)
		s = strconv.FormatInt(r, 10)
		n = len(s)

		ans = fun(0, 0, 1)

		dp = [22][11][2]int64{}
		vis = [22][11][2]bool{}
		l = l - 1
		s = strconv.FormatInt(l, 10)
		n = len(s)
		//printf("%d\n", ans)
		ans = ans - fun(0, 0, 1)
		printf("%d\n", ans)

	}

}

// 4
// 1 1000
// 1024 1024
// 65536 65536
// 999999 1000001
// outputCopy
// 1000
// 1
// 0
// 2

// [DAX_COMPENSATION_CANCELLATION_MESSAGE]
// en = "Rates not affected. A compensation of %s was added to your Cash Wallet."
// en_kh = "តម្លៃមិនរងផលប៉ះពាល់។ ការទូទាត់សំណង %s ត្រូវបានបន្ថែមទៅកាបូបលុយរបស់អ្នក។"
// en_id = "Nilai tidak terpengaruh. Ganti rugi sebesar %s sudah ditambahkan ke Dompet Tunai Anda."
// en_my = "Rating tidak terjejas. Ganti rugi sebanyak %s telah ditambahkan ke Dompet Tunai anda."
// en_sg = "Rates not affected. A compensation of %s was added to your Cash Wallet."
// en_us = "Rates not affected. A compensation of %s was added to your Cash Wallet."
// en_vn = "Không ảnh hưởng đến tỷ lệ hủy chuyến. Bạn đã được bồi thường %s vào Ví tiền mặt."
// th_th = "ไม่มีผลต่ออัตรายกเลิกงาน ค่าบริการจำนวน %s ถูกคืนเข้ากระเป๋าเงินของคุณแล้ว"
// my_my = "နှုန်းထားများမထိခိုက်စေပါ။ ပြန်ပေးရမည့်ပမာဏ %s ကို သင့်ငွေသားပိုက်ဆံအိတ်ထဲသို့ ထည့်ပြီးပါပြီ။"
// zh_cn = "取消率等不会受影响。%s 的补偿金额已添加到您的现金钱包中。"


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.

package main
import (
	"fmt"
)
func abs1(a int64) int64{
	if a<0{
		a=-a
	}
	return a
}
func main(){
	var n int64
	var a []int64
	var sum_mas int64
	var ans_first int64
	var ans_second int64

	fmt.Scanf("%d\n",&n)
	var i int64
	for i=0;i<n;i++{
		var v int64
		fmt.Scanf("%d",&v)
		a=append(a,v)
		sum_mas+=v
	}
	var ost int64;
	var ost1 int64;

	ost=(sum_mas/n)
	if sum_mas%n==0{
		ost1=ost
	}else{
		ost1=ost+1
	}
	for i=0;i<n;i++{
		if a[i]<ost{
			ans_first+=ost-a[i]
			ans_second+=ost-a[i]
		} else {
			if a[i]>ost1{
				ans_first+=a[i]-ost1
				ans_second+=ost1-a[i]
			}
		}
	}
	var ans_full int64
	ans_full=((ans_first+abs1(ans_second))/2)
	fmt.Println(ans_full)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	// "sort"
	// "strings"
)

var (
	reader  = bufio.NewReader(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	m := make([]int, n)
	sum, avg, second, mod := 0, 0, 0, 0

	for i := range m {
		m[i] = nextInt()
		sum += m[i]
	}

	avg = sum / n
	mod = sum % n

	for i := range m {
		if mod > 0 && m[i] >= avg+1 {
			second += m[i] - avg - 1
			mod--
		} else if m[i] > avg {
			second += m[i] - avg
		}
	}

	println(second)
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

func next() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

import (
	"os"
	"bufio"
	"sort"
	"strconv"
)

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func ReadInt() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	defer writer.Flush()
    scanner.Split(bufio.ScanWords)

	n := ReadInt()

	sum := 0

	v := make([]int, n)

	for i := 0; i < n; i++ {
		v[i] = ReadInt()
		sum += v[i]
	}

	div := sum/n
	rest := sum%n

	resp := 0

	sort.Slice(v, func (i, j int) bool {
		return v[i] > v[j]
		})

	for i := 0; i < rest; i++ {
		resp += abs(v[i] - (div + 1))
	}

	for i := rest; i < n; i++ {
		resp += abs(v[i] - div)
	}

	writer.WriteString(strconv.Itoa(resp/2))

}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10, 8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	totalTasks := 0
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
		totalTasks += mArr[idx]
	}

	avg := float64(totalTasks) / float64(len(mArr))

	respLow := 0
	respHigh := 0
	floorAvg := int(math.Floor(avg))
	ceilAvg := int(math.Ceil(avg))
	for i := 0; i < n; i++ {
		if float64(mArr[i]) < avg {
			respLow += floorAvg - mArr[i]
		} else {
			respHigh += mArr[i] - ceilAvg
		}
	}

	fmt.Println(int(math.Max(float64(respLow), float64(respHigh))))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	// "sort"
	// "strings"
)

var (
	reader  = bufio.NewReader(os.Stdin)
	writer  = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
)

//Wrong
func main() {
	defer writer.Flush()
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	m := make([]int, n)
	sum, avg, second := 0, 0, 0

	for i := range m {
		m[i] = nextInt()
		sum += m[i]
	}

	avg = sum / n

	if avg*n < sum {
		avg += 1
	}
	// println(avg, sum, m)
	for i := range m {
		if m[i] > avg {
			second += m[i] - avg
		}
	}

	println(second)
}

func scan(a ...interface{}) {
	fmt.Fscan(reader, a...)
}

func next() string {
	if !scanner.Scan() {
		panic(scanner.Err())
	}
	return scanner.Text()
}

func nextInt64() int64 {
	n, _ := strconv.ParseInt(next(), 0, 64)
	return n
}

func nextInt() int {
	n, _ := strconv.Atoi(next())
	return n
}

func nextFloat() float64 {
	n, _ := strconv.ParseFloat(next(), 64)
	return n
}

func println(a ...interface{})               { fmt.Fprintln(writer, a...) }
func print(a ...interface{})                 { fmt.Fprint(writer, a...) }
func printf(format string, a ...interface{}) { fmt.Fprintf(writer, format, a...) }

package main

import (
	"os"
	"bufio"
	"sort"
	"strconv"
)

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func ReadInt() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	defer writer.Flush()
    scanner.Split(bufio.ScanWords)

	n := ReadInt()

	sum := 0

	v := make([]int, n)

	for i := 0; i < n; i++ {
		v[i] = ReadInt()
		sum += v[i]
	}

	div := sum/n
	rest := sum%n

	resp := 0

	sort.Slice(v, func (i, j int) bool {
		return v[i] > v[j]
		})

	for i := 0; i < rest; i++ {
		resp += abs(v[i] - div + 1)
	}

	for i := rest; i < n; i++ {
		resp += abs(v[i] - div)
	}

	writer.WriteString(strconv.Itoa(resp/2))

}

package main

import (
	"os"
	"bufio"
	"sort"
	"strconv"
)

var scanner *bufio.Scanner = bufio.NewScanner(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)

func ReadInt() int {
	scanner.Scan()
	ans, _ := strconv.Atoi(scanner.Text())
	return ans
}

func main() {
	defer writer.Flush()
    scanner.Split(bufio.ScanWords)

	n := ReadInt()

	sum := 0

	v := make([]int, n)

	for i := 0; i < n; i++ {
		v[i] = ReadInt()
		sum += v[i]
	}

	obj := sum/n

	resp := 0

	sort.Slice(v, func (i, j int) bool {
		return v[i] < v[j]
		})

	for i := range v {
		if v[i] >= obj {
			break
		}
		resp += obj - v[i]
	}

	writer.WriteString(strconv.Itoa(resp))

}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10, 8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	totalTasks := 0
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
		totalTasks += mArr[idx]
	}

	avg := float64(totalTasks) / float64(len(mArr))

	respLow := 0
	respHigh := 0
	floorAvg := int(math.Floor(avg))
	ceilAvg := int(math.Ceil(avg))
	for i := 0; i < n; i++ {
		if float64(mArr[i]) < avg {
			respLow += floorAvg - mArr[i]
		} else {
			respHigh += mArr[i] - ceilAvg
		}
	}

	fmt.Println(math.Max(float64(respLow), float64(respHigh)))
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10,8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	totalTasks := 0
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
		totalTasks += mArr[idx]
	}

	sort.Ints(mArr)

	resp := 0
	for len(mArr) > 1 {
		mean := int(math.Round(float64(totalTasks) / float64(len(mArr))))
		idx := sort.SearchInts(mArr, mean)
		if idx == 0 || idx == len(mArr){
			break
		}
		lDiff := mean - mArr[idx-1]
		rDiff := mArr[idx] - mean

		//fmt.Printf("totalTasks: %v, mArr: %v, len: %v, idx: %v, lDiff: %v, rDiff: %v\n",
		//	totalTasks, mArr, len(mArr), idx, lDiff, rDiff)
		if lDiff < rDiff {
			mArr[idx] -= lDiff
			totalTasks -= mean
			mArr = append(mArr[0:idx-1], mArr[idx:]...)
			resp += lDiff
		} else {
			mArr[idx-1] += rDiff
			totalTasks -= mean
			mArr = append(mArr[0:idx], mArr[idx+1:]...)
			resp += rDiff
		}
		//fmt.Println(mArr)
	}

	fmt.Println(resp)
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10, 8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	totalTasks := 0
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
		totalTasks += mArr[idx]
	}

	avg := float64(totalTasks) / float64(len(mArr))

	respLow := 0
	respHigh := 0
	floorAvg := int(math.Floor(avg))
	ceilAvg := int(math.Ceil(avg))
	for i := 0; i < n; i++ {
		if float64(mArr[i]) < avg {
			respLow += floorAvg - mArr[i]
		} else {
			respHigh += mArr[i] - ceilAvg
		}
	}

	fmt.Println(math.Min(float64(respLow), float64(respHigh)))
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10,8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	totalTasks := 0
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
		totalTasks += mArr[idx]
	}

	sort.Ints(mArr)

	resp := 0
	for len(mArr) > 0 {
		mean := int(math.Round(float64(totalTasks) / float64(len(mArr))))
		idx := sort.SearchInts(mArr, mean)
		if idx == 0 || idx == len(mArr){
			break
		}
		lDiff := mean - mArr[idx-1]
		rDiff := mArr[idx] - mean

		//fmt.Printf("totalTasks: %v, mArr: %v, len: %v, idx: %v, lDiff: %v, rDiff: %v\n",
		//	totalTasks, mArr, len(mArr), idx, lDiff, rDiff)
		if lDiff < rDiff {
			mArr[idx] -= lDiff
			totalTasks -= mean
			mArr = append(mArr[0:idx-1], mArr[idx:]...)
			resp += lDiff
		} else {
			mArr[idx-1] += rDiff
			totalTasks -= mean
			mArr = append(mArr[0:idx], mArr[idx+1:]...)
			resp += rDiff
		}
		//fmt.Println(mArr)
	}

	fmt.Println(resp)
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10,8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	totalTasks := 0
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
		totalTasks += mArr[idx]
	}

	sort.Ints(mArr)

	avg := float64(totalTasks) / float64(len(mArr))
	idx := sort.SearchInts(mArr, int(math.Ceil(avg)))

	resp := 0
	floorAvg := int(math.Floor(avg))
	for i := 0; i < idx; i++ {
		resp += floorAvg - mArr[i]
	}

	fmt.Println(resp)
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10,8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	totalTasks := 0
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
		totalTasks += mArr[idx]
	}

	sort.Ints(mArr)

	resp := 0
	for len(mArr) > 0 {
		mean := int(math.Ceil(float64(totalTasks) / float64(len(mArr))))
		idx := sort.SearchInts(mArr, mean)
		if idx == 0 || idx == len(mArr){
			break
		}
		lDiff := mean - mArr[idx-1]
		rDiff := mArr[idx] - mean

		//fmt.Printf("totalTasks: %v, mArr: %v, len: %v, idx: %v, lDiff: %v, rDiff: %v\n",
		//	totalTasks, mArr, len(mArr), idx, lDiff, rDiff)
		if lDiff < rDiff {
			mArr[idx] -= lDiff
			totalTasks -= mean
			mArr = append(mArr[0:idx-1], mArr[idx:]...)
			resp += lDiff
		} else {
			mArr[idx-1] += rDiff
			totalTasks -= mean
			mArr = append(mArr[0:idx], mArr[idx+1:]...)
			resp += rDiff
		}
		//fmt.Println(mArr)
	}

	fmt.Println(resp)
}

package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Buffer([]byte{}, int(math.Pow(10,8)))

	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())

	scanner.Scan()
	mStrArr := strings.Split(scanner.Text(), " ")
	mArr := make([]int, n)
	for idx := 0; idx < n; idx++ {
		mArr[idx], _ = strconv.Atoi(mStrArr[idx])
	}

	sort.Ints(mArr)

	resp := 0
	for mArr[n-1] - mArr[0] > 1 {
		i := 0
		for mArr[0] == mArr[i] {
			i++
		}
		j := n-1
		for mArr[n-1] == mArr[j] {
			j--
		}
		var inc int
		if mArr[i] == mArr[n-1] || mArr[j] == mArr[0] {
			inc = (mArr[n-1] - mArr[0]) / 2
		} else {
			inc = int(math.Min(float64(mArr[i]-mArr[0]), float64(mArr[n-1]-mArr[j])))
		}
		lVal := mArr[0] + inc
		rVal := mArr[n-1] - inc
		for idx := 0; idx < i-1; idx++ {
			mArr[idx] = mArr[idx+1]
		}
		mArr[i-1] = lVal
		for idx := n-1; idx > j+1; idx-- {
			mArr[idx] = mArr[idx-1]
		}
		mArr[j+1] = rVal
		resp += inc
	}

	fmt.Println(resp)
}


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.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, k := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &k)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &a[i])
	}
	testS := make([]int, k)
	for i := 0; i < k; i++ {
		testS[i] = -1
	}
	testT := make([]int, k)
	work := 0
	fin := 0
	interesting := make([]bool, n)
	for true {
		dosth := false
		for i := 0; i < k; i++ {
			if testS[i] == -1 || testT[i] == a[testS[i]]+1 {
				if work < n {
					testS[i] = work
					testT[i] = 1
					work++
				}
			}
		}
		preFin := fin
		for i := 0; i < k; i++ {
			if testS[i] != -1 && testT[i] <= a[testS[i]] {
				dosth = true
				testT[i]++
				if testT[i] == a[testS[i]]+1 {
					fin++
					if fin == n {
						ans := 0
						for i := 0; i < len(interesting); i++ {
							if interesting[i] {
								ans++
							}
						}
						fmt.Fprintf(out, "%d\n", ans)
						return
					}
				}
			}
		}
		round := int(float64(preFin*100)/float64(n) + 0.5)
		//fmt.Println(round)
		for i := 0; i < k; i++ {
			if testS[i] != -1 && testT[i]-1 == round {
				//fmt.Println(testS[i], testT[i], round)
				interesting[testS[i]] = true
			}
		}
		for i := 0; i < k; i++ {
			if testS[i] != -1 && testT[i] == a[testS[i]]+1 {
				testS[i] = -1
				testT[i] = 0
			}
		}
		if !dosth {
			break
		}
		// fmt.Println("Test")
		// fmt.Println(round, fin)
		// fmt.Println(testS)
		// fmt.Println(testT)
	}
	ans := 0
	for i := 0; i < len(interesting); i++ {
		if interesting[i] {
			ans++
		}
	}
	fmt.Fprintf(out, "%d\n", ans)
	return
}


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$$$.

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

var reader io.Reader
var scanner *bufio.Scanner

func Init(io io.Reader, max_token_size int) {
	reader = bufio.NewReader(io)
	scanner = bufio.NewScanner(reader)
	// max token size
	scanner.Split(bufio.ScanWords)
	scanner.Buffer([]byte{}, max_token_size)
}

func stderr(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
}

func die(v ...interface{}) {
	fmt.Fprintln(os.Stderr, v...)
	os.Exit(1)
}

func NextInt() int {
	bytes := NextBytes()
	i, err := Atoi(bytes)
	if err != nil {
		die(err)
	}
	return i
}
func NextInt64() int64 {
	bytes := NextBytes()
	i, err := Atoi64(bytes)
	if err != nil {
		die(err)
	}
	return i
}

func NextBytes() []byte {
	if !scanner.Scan() {
		die(scanner.Err())
	}
	bytes := scanner.Bytes()
	copied := make([]byte, len(bytes))
	copy(copied, bytes)
	return copied
}

func Atoi(b []byte) (int, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func Atoi64(b []byte) (int64, error) {
	neg := false
	if b[0] == '+' {
		b = b[1:]
	} else if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	var n int64
	for _, v := range b {
		if v < '0' || v > '9' {
			return 0, strconv.ErrSyntax
		}
		n = n*10 + int64(v-'0')
	}
	if neg {
		return -n, nil
	}
	return n, nil
}

func ExtendByteArray(a []byte, size int) []byte {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]byte, size-len(a))...)
	}
}

func ExtendIntArray(a []int, size int) []int {
	if size <= len(a) {
		return a
	} else {
		return append(a, make([]int, size-len(a))...)
	}
}

func reverseInts(a []int) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

func unique(a []int) int {
	newLen := 0
	n := len(a)
	for i := 0; i < n; i++ {
		if newLen == 0 || a[i] != a[newLen-1] {
			a[newLen] = a[i]
			newLen++
		}
	}
	return newLen
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

type Graph struct {
	n     int
	m     int
	edges int
	fst   []int
	nxt   []int
	end   []int
}

func (g *Graph) Add(a, b int) {
	g.nxt[g.edges] = g.fst[a]
	g.fst[a] = g.edges
	g.end[g.edges] = b
	g.edges++
}

func (g *Graph) Adjacent(a int, fn func(b int)) {
	for u := g.fst[a]; u != -1; u = g.nxt[u] {
		fn(g.end[u])
	}
}

func NewGraph(n, m int) *Graph {
	g := &Graph{n, m, 0, make([]int, n), make([]int, m), make([]int, m)}
	for i := 0; i < n; i++ {
		g.fst[i] = -1
	}
	return g
}

type Tree struct {
	g *Graph
	// maxLogHeight int
	root   int
	parent []int
	// up           [][]int
	h        []int
	entrance []int
	exit     []int
}

func (t *Tree) GoDown(v int, par int, time int) int {
	t.parent[v] = par
	t.entrance[v] = time
	time++
	// for i := 1; i < t.maxLogHeight; i++ {
	// 	t.up[v][i] = t.up[t.up[v][i-1]][i-1]
	// }
	t.g.Adjacent(v, func(to int) {
		if to == par {
			return
		}
		t.h[to] = t.h[v] + 1
		time = t.GoDown(to, v, time)
	})
	t.exit[v] = time
	time++
	// stderr("vertex", v, "entrance", t.entrance[v], "exit", t.exit[v])
	return time
}

func (t *Tree) Prepare() {
	t.GoDown(t.root, t.root, 0)
}

func (t *Tree) IsParent(u, v int) bool {
	return t.entrance[u] <= t.entrance[v] && t.exit[u] >= t.exit[v]
}

// func (t *Tree) LCA(u, v int) int {
// 	if t.IsParent(u, v) {
// 		return u
// 	}
// 	for h := t.maxLogHeight - 1; h >= 0; {
// 		for h >= 0 && t.IsParent(t.up[u][h], v) {
// 			h--
// 		}
// 		if h >= 0 {
// 			u = t.up[u][h]
// 		}
// 	}
// 	return t.up[u][0]
// }

// func (t *Tree) Distance(u, v int) int {
// 	lca := t.LCA(u, v)
// 	// stderr("lca of", u, v, "is", lca)
// 	return t.h[u] + t.h[v] - 2*t.h[lca]
// }

func NewTree(g *Graph) *Tree {
	parent := make([]int, g.n)
	// !!!!!!!!!!!!!!!!!!!!!
	// var mh = 18
	// up := make([][]int, g.n)
	// for i := 0; i < g.n; i++ {
	// 	up[i] = make([]int, mh)
	// }
	h := make([]int, g.n)
	entrance := make([]int, g.n)
	exit := make([]int, g.n)
	return &Tree{g, 0, parent, h, entrance, exit}
}

func main() {
	inf := os.Stdin
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	// inf, err := os.Open("a.in")
	// if err != nil {
	// 	die(err)
	// }
	// out, err := os.Create("a.out")
	// if err != nil {
	// 	die(err)
	// }
	// defer out.Close()
	Init(inf, 1000010)

	n, m := NextInt(), NextInt()
	g := NewGraph(n, 2*(n-1))

	for i := 0; i < n-1; i++ {
		u, v := NextInt()-1, NextInt()-1
		g.Add(u, v)
		g.Add(v, u)
	}

	t := NewTree(g)
	t.Prepare()

	v := make([]int, 200000)
	for i := 0; i < m; i++ {
		k := NextInt()
		maxH := -1
		maxV := -1
		for j := 0; j < k; j++ {
			v[j] = NextInt() - 1
			if t.h[v[j]] > maxH {
				maxH = t.h[v[j]]
				maxV = v[j]
			}
		}
		u := t.parent[maxV]
		ok := true
		for j := 0; ok && j < k; j++ {
			if !t.IsParent(t.parent[v[j]], u) {
				ok = false
			}
		}
		if ok {
			fmt.Fprintln(out, "YES")
		} else {
			fmt.Fprintln(out, "NO")
		}
	}

}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
)

// github.com/EndlessCheng/codeforces-go
func CF1328E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	var n, q, v, w, k int
	Fscan(in, &n, &q)
	g := make([][]int, n)
	for i := 1; i < n; i++ {
		Fscan(in, &v, &w)
		v--
		w--
		g[v] = append(g[v], w)
		g[w] = append(g[w], v)
	}

	const mx = 19
	pa := make([][mx]int, n)
	dep := make([]int, n)
	var dfs func(v, p, d int)
	dfs = func(v, p, d int) {
		pa[v][0] = p
		dep[v] = d
		for _, w := range g[v] {
			if w != p {
				dfs(w, v, d+1)
			}
		}
	}
	dfs(0, -1, 0)
	for k := 0; k+1 < mx; k++ {
		for v := range pa {
			if p := pa[v][k]; p != -1 {
				pa[v][k+1] = pa[p][k]
			} else {
				pa[v][k+1] = -1
			}
		}
	}
	_lca := func(v, w int) int {
		if dep[v] > dep[w] {
			v, w = w, v
		}
		for k := 0; k < mx; k++ {
			if (dep[w]-dep[v])>>k&1 == 1 {
				w = pa[w][k]
			}
		}
		if v == w {
			return v
		}
		for k := mx - 1; k >= 0; k-- {
			if pa[v][k] != pa[w][k] {
				v, w = pa[v][k], pa[w][k]
			}
		}
		return pa[v][0]
	}

o:
	for ; q > 0; q-- {
		Fscan(in, &k)
		vs := make([]int, k)
		maxDep, maxV := 0, 0
		for i := range vs {
			Fscan(in, &v)
			v--
			if dep[v] > maxDep {
				maxDep, maxV = dep[v], v
			}
			vs[i] = v
		}
		for _, v := range vs {
			if dep[v]-dep[_lca(maxV, v)] > 1 {
				Fprintln(out, "NO")
				continue o
			}
		}
		Fprintln(out, "YES")
	}
}

func main() { CF1328E(os.Stdin, os.Stdout) }

package main

import (
	"bufio"
	"fmt"
	"os"
)

const N  = 200020
const LOG = 18

var n, m int
var a[N][] int
var dist[N] int
var dd[N] bool
var parent[N][LOG] int

func dfs(u int)  {
	dd[u] = true
	for _, v := range a[u] {
		if dd[v] == false {
			dist[v] = dist[u] + 1
			parent[v][0] = u
			dfs(v)
		}
	}
}

func makeLCA()  {
	parent[1][0] = 1
	dfs(1)
	for j := 1; j < LOG; j++ {
		for i := 1; i <= n; i++ {
			parent[i][j] = parent[parent[i][j - 1]][j - 1]
		}
	}
}

func isParentOfV(u int, v int) bool {
	if u == v {
		return true
	}

	var du = dist[u]
	var dv = dist[v]

	if du > dv {
		return false
	}

	var dx = dv - du
	for j := LOG - 1; j >= 0; j-- {
		if ((dx >> uint(j)) & 1) == 1 {
			v = parent[v][j]
		}
	}

	return u == v
}

func check(path[]int, node int) bool {
	for _, u := range path {
		var v = parent[u][0]
		if !isParentOfV(u, node) && !isParentOfV(v, node) {
			return false
		}
	}
	return true
}

func main()  {
	var reader = bufio.NewReader(os.Stdin)
	var writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	fmt.Fscanf(reader, "%d %d\n", &n, &m)

	for i := 1; i <= n; i++ {
		a[i] = make([]int, 0)
	}

	for i := 1; i < n; i++ {
		var u, v int
		fmt.Fscanf(reader, "%d %d\n", &u, &v)
		a[u] = append(a[u], v)
		a[v] = append(a[v], u)
	}

	makeLCA()

	for kk := 0; kk < m; kk++ {
		var ds = make([]int, 0)

		var could = false
		var sz int
		var pos = -1

		fmt.Fscanf(reader, "%d", &sz)
		for i := 0; i < sz; i++ {
			var u int
			fmt.Fscanf(reader, "%d", &u)
			ds = append(ds, u)
			if pos == -1 {
				pos = u
			} else if dist[u] > dist[pos] {
					pos = u
				}
		}
		fmt.Fscanf(reader, "\n")

		if check(ds, pos) {
			could = true
		}

		if check(ds, parent[pos][0]) {
			could = true
		}

		if could {
			fmt.Fprintf(writer, "YES\n")
		} else {
			fmt.Fprintf(writer, "NO\n")
		}
	}

}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

type Node struct {
	Parent int64
	In     int64
	Out    int64
}

type counter struct {
	val int64
}

func (c *counter) Next() int64 {
	c.val++
	return c.val
}

func main() {
	defer writer.Flush()
	n, m := reader.NextInt64(), reader.NextInt64()
	matrix := map[int64]map[int64]bool{}
	for ; n > 1; n-- {
		u, v := reader.NextInt64(), reader.NextInt64()
		if matrix[u] == nil {
			matrix[u] = map[int64]bool{}
		}
		if matrix[v] == nil {
			matrix[v] = map[int64]bool{}
		}
		matrix[u][v] = true
		matrix[v][u] = true
	}

	nodes := map[int64]*Node{}
	c := &counter{}
	var dfs func(int64, int64)
	dfs = func(from, to int64) {
		nodes[to] = &Node{Parent: from}
		nodes[to].In = c.Next()
		for k := range matrix[to] {
			if nodes[k] == nil {
				dfs(to, k)
			}
		}
		nodes[to].Out = c.Next()
	}
	dfs(-1, 1)

	for ; m > 0; m-- {
		writer.Printf("%s\n", sol(nodes))
	}
}

func sol(nodes map[int64]*Node) string {
    k := reader.NextInt64()
    vv := []int64{}
    for ; k > 0; k-- {
        vv = append(vv, reader.NextInt64())
    }
    minSoFar := nodes[1].In
    maxSoFar := nodes[1].Out
    for _, v := range vv {
        if nodes[v] == nil {
            // should not happen
            return "NO"
        }
        if v == 1 {
            continue
        }
        parent := nodes[nodes[v].Parent]
        if parent.In > minSoFar && parent.Out < maxSoFar {
            minSoFar = parent.In
            maxSoFar = parent.Out
            continue
        }
        if parent.In <= minSoFar && parent.Out >= maxSoFar {
            continue
        }
        return "NO"
    }
	return "YES"
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

type Node struct {
	Val    int64
	Parent *Node
}

func main() {
	defer writer.Flush()
	n, m := reader.NextInt64(), reader.NextInt64()
	matrix := map[int64]map[int64]bool{}
	for ; n > 1; n-- {
		u, v := reader.NextInt64(), reader.NextInt64()
		if matrix[u] == nil {
			matrix[u] = map[int64]bool{}
		}
		if matrix[v] == nil {
			matrix[v] = map[int64]bool{}
		}
		matrix[u][v] = true
		matrix[v][u] = true
	}
	nodes := map[int64]*Node{
		1: &Node{
			Val:    1,
			Parent: nil,
		},
	}

    toExplore := []int64{1}
    var explore func()
    explore = func() {
        tmp := []int64{}
        for _, i := range toExplore {
            for k := range matrix[i] {
                if nodes[k] != nil {
                    continue
                }
                nodes[k] = &Node{
                    Val:    k,
                    Parent: nodes[i],
                }
                tmp = append(tmp, k)
            }
        }
        if len(tmp) > 0 {
            toExplore = tmp
            explore()
        }
    }
	explore()

    for ; m > 0; m-- {
        writer.Printf("%s\n", sol(nodes))
    }
}

func sol(nodes map[int64]*Node) string {
	k := reader.NextInt64()
	tmp := map[int64]bool{1: true}
	tail := int64(1)
	for ; k > 0; k-- {
		v := reader.NextInt64()
		if tmp[v] {
			continue
		}
		curr := nodes[v].Parent // start with parent
		if tmp[curr.Val] {
			continue
		}
		newTail := curr.Val
		for !tmp[curr.Val] {
			tmp[curr.Val] = true
			curr = curr.Parent
		}
		if curr.Val != tail {
			return "NO"
		}
		tail = newTail
	}
	return "YES"
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

type Node struct {
	Val    int64
	Parent *Node
}

func main() {
	defer writer.Flush()
	n, m := reader.NextInt64(), reader.NextInt64()
	matrix := map[int64]map[int64]bool{}
	for ; n > 1; n-- {
		u, v := reader.NextInt64(), reader.NextInt64()
		if matrix[u] == nil {
			matrix[u] = map[int64]bool{}
		}
		if matrix[v] == nil {
			matrix[v] = map[int64]bool{}
		}
		matrix[u][v] = true
		matrix[v][u] = true
	}
	nodes := map[int64]*Node{
		1: &Node{
			Val:    1,
			Parent: nil,
		},
	}

    var explore func(int64)
    explore = func(i int64) {
        for k := range matrix[i] {
            if nodes[k] != nil {
                continue
            }
            nodes[k] = &Node{
                Val:    k,
                Parent: nodes[i],
            }
            explore(k)
        }
    }
	explore(1)

    for ; m > 0; m-- {
        writer.Printf("%s\n", sol(nodes))
    }
}

func sol(nodes map[int64]*Node) string {
	k := reader.NextInt64()
	tmp := map[int64]bool{1: true}
	tail := int64(1)
	for ; k > 0; k-- {
		v := reader.NextInt64()
		if tmp[v] {
			continue
		}
		curr := nodes[v].Parent // start with parent
		if tmp[curr.Val] {
			continue
		}
		newTail := curr.Val
		for !tmp[curr.Val] {
			tmp[curr.Val] = true
			curr = curr.Parent
		}
		if curr.Val != tail {
			return "NO"
		}
		tail = newTail
	}
	return "YES"
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

type BufferedWriter interface {
	Printf(format string, a ...interface{})
	Flush()
}

type writerImpl struct {
	*bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
	return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
	fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
	impl.Writer.Flush()
}

type WordScanner interface {
	NextInt() int
	NextInt64() int64
	NextString() string
}

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
	impl.Scan()
	bb := impl.Bytes()
	i := 0
	for _, b := range bb {
		i *= 10
		i += int(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
	impl.Scan()
	bb := impl.Bytes()
	i := int64(0)
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func (impl *wordScannerImpl) NextString() string {
	impl.Scan()
	return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

type Node struct {
	Val    int64
	Parent *Node
}

func main() {
	defer writer.Flush()
	n, m := reader.NextInt64(), reader.NextInt64()
	matrix := map[int64]map[int64]bool{}
	for ; n > 1; n-- {
		u, v := reader.NextInt64(), reader.NextInt64()
		if matrix[u] == nil {
			matrix[u] = map[int64]bool{}
		}
		if matrix[v] == nil {
			matrix[v] = map[int64]bool{}
		}
		matrix[u][v] = true
		matrix[v][u] = true
	}
	nodes := map[int64]*Node{
		1: &Node{
			Val:    1,
			Parent: nil,
		},
	}

    var explore func(int64)
    explore = func(i int64) {
        for k := range matrix[i] {
            if nodes[k] != nil {
                continue
            }
            fmt.Printf("%d\n", k)
            nodes[k] = &Node{
                Val:    k,
                Parent: nodes[i],
            }
            explore(k)
        }
    }
	explore(1)

    for ; m > 0; m-- {
        writer.Printf("%s\n", sol(nodes))
    }
}

func sol(nodes map[int64]*Node) string {
	k := reader.NextInt64()
	tmp := map[int64]bool{1: true}
	tail := int64(1)
	for ; k > 0; k-- {
		v := reader.NextInt64()
		if tmp[v] {
			continue
		}
		curr := nodes[v].Parent // start with parent
		if tmp[curr.Val] {
			continue
		}
		newTail := curr.Val
		for !tmp[curr.Val] {
			tmp[curr.Val] = true
			curr = curr.Parent
		}
		if curr.Val != tail {
			return "NO"
		}
		tail = newTail
	}
	return "YES"
}