package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	const mx int = 1e5
	primes := []int{}
	isP := [mx + 1]bool{}
	for i := range isP {
		isP[i] = true
	}
	isP[0], isP[1] = false, false
	for i := 2; i <= mx; i++ {
		if isP[i] {
			primes = append(primes, i)
			for j := 2 * i; j <= mx; j += i {
				isP[j] = false
			}
		}
	}

	solve := func(Case int) {
		var n int
		Fscan(in, &n)
		p := n
		for ;  ; p++ {
			if !isP[p] {
				continue
			}
			if !isP[p-n+1] {
				break
			}
		}
		x := p-n+1
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if i == j {
					Fprint(out, x, " ")
				} else {
					Fprint(out, 1, " ")
				}
			}
			Fprintln(out)
		}
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}
}

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

package main

import (
	"fmt"
	"math/big"
)

func main() {
	var t, n, i, x ,y, ans  int64
	var j int64
	fmt.Scan(&t)
	for i=0; i<t; i++ {
		fmt.Scan(&n)
		for j=n+1; ; j++ {
			if big.NewInt(j).ProbablyPrime(0) && !big.NewInt(j-n+1).ProbablyPrime(0) {
				ans = j-n+1
				break
			}
		}
		for x=0; x<n; x++ {
			for y=0; y<n; y++ {
				if x!=y {
					fmt.Printf("1 ")
				} else {
					fmt.Printf("%d ", ans)
				}
			}
			fmt.Printf("\n")
		}
	}
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
}

func Next() string {
	sc.Scan()
	return sc.Text()
}

func NextInt() int {
	i, err := strconv.Atoi(Next())
	if err != nil {
		panic(err)
	}
	return i
}

func main() {
	for tt := NextInt(); tt > 0; tt-- {
		n := NextInt()
		if n == 2 {
			fmt.Println("1 1")
			fmt.Println("1 1")
		} else if n == 3 {
			fmt.Println("1 1 1")
			fmt.Println("1 1 1")
			fmt.Println("1 1 1")
		} else {
			for i := 0; i < n - 1; i++ {
				for j := 0; j < n - 2 - i; j++ {
					fmt.Print("0 ")
				}
				fmt.Print("1 1 ")
				for j := n - i; j < n; j++ {
					fmt.Print("0 ")
				}
				fmt.Println()
			}
			fmt.Print("1 ")
			for i := 1; i < n - 1; i++ {
				fmt.Print("0 ")
			}
			fmt.Println("1")
		}
	}
}

package main

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

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

func print(str string) {
	writer.WriteString(str)
}

func nextInt() int {
	scanner.Scan()
	str := scanner.Text()
	val, _ := strconv.Atoi(str)
	return val
}

func nextFloat() float64 {
	scanner.Scan()
	str := scanner.Text()
	val, _ := strconv.ParseFloat(str, 64)
	return val
}

func nextString() string {
	scanner.Scan()
	str := scanner.Text()
	return str
}

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

func getPrimes(max int64) (primes []int) {
	gouged := make([]bool, max+1)
	for i := int64(2); i <= max; i++ {
		if !gouged[i] {
			primes = append(primes, int(i))
			for j := int64(i) * int64(i); j <= int64(max); j += i {
				gouged[j] = true
			}
		}
	}
	return
}

func main() {
	scanner.Split(bufio.ScanWords)
	defer writer.Flush()
	primes := getPrimes(100000)
	isPrime := map[int]bool{}
	for _, p := range primes {
		isPrime[p] = true
	}

	zvals := [101]int{}
	for i, k := 2, 0; i <= 100; i++ {
		for j := k; ; j++ {
			z := primes[j] - i + 1
			if z > 0 && !isPrime[z] {
				zvals[i] = z
				break
			}
		}
	}

	t := nextInt()
	for t != 0 {
		n := nextInt()
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				val := 1
				if j == i {
					val = zvals[n]
				}
				print(strconv.Itoa(val) + " ")
			}
			print("\n")
		}
		t--
	}
}

package main

import (
	"fmt"
)

func getPrimes(max int64) (primes []int) {
	gouged := make([]bool, max+1)
	for i := int64(2); i <= max; i++ {
		if !gouged[i] {
			primes = append(primes, int(i))
			for j := int64(i) * int64(i); j <= int64(max); j += i {
				gouged[j] = true
			}
		}
	}
	return
}

func main() {
	primes := getPrimes(100000)
	isPrime := map[int]bool{}
	for _, p := range primes {
		isPrime[p] = true
	}

	zvals := [101]int{}
	for i, k := 2, 0; i <= 100; i++ {
		for j := k; ; j++ {
			z := primes[j] - i + 1
			if z > 0 && !isPrime[z] {
				zvals[i] = z
				break
			}
		}
	}

	var t int
	fmt.Scan(&t)
	for t != 0 {
		var n int
		fmt.Scan(&n)
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				val := 1
				if j == i {
					val = zvals[n]
				}
				fmt.Print(val, " ")
			}
			fmt.Println()
		}
		t--
	}
}

package main

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

var rw = NewFastIO(os.Stdin, os.Stdout)

func main() {
	defer rw.Flush()
	nt := rw.NextInt()
	for i := 0; i < nt; i++ {
		tCase()
	}
}

func tCase() {
	n := rw.NextInt()
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == j || i == j+1 || (i == 0 && j == 1) || (i == n-2 && j == n-1) {
				rw.Print("1 ")
			} else {
				rw.Print("0 ")
			}
		}
		rw.Println()
	}
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}
func (f *FastIO) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}
func (f *FastIO) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}

package main

import "fmt"

func main() {
	var t, n int
	_, _ = fmt.Scanf("%d\n", &t)
	for i := 0; i < t; i++ {
		_, _ = fmt.Scanf("%d\n", &n)
		for i:=0;i<n;i++{
			for j:=0;j<n;j++{
				if ( i == j || i == j + 1 || i == j -1 ){
					fmt.Println("1 ")
				}else{
					fmt.Println("0 ")
				}
				fmt.Println()
			}
		}
	}
}

package main

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

var rw = NewFastIO(os.Stdin, os.Stdout)

func main() {
	defer rw.Flush()
	nt := rw.NextInt()
	for i := 0; i < nt; i++ {
		tCase()
	}
}

func tCase() {
	n := rw.NextInt()
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if i == j {
				rw.Print("2 ")
			} else {
				rw.Print("0 ")
			}
		}
		rw.Println()
	}
}

type FastIO struct {
	*bufio.Writer
	r    io.Reader
	buf  [8192]byte
	i, n int
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{r: r, Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	if f.i == f.n {
		f.n, _ = f.r.Read(f.buf[:])
		if f.n == 0 {
			panic("EOF")
		}
		f.i = 0
	}
	f.i++
	return f.buf[f.i-1]
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, c)
	}
	return string(s)
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}
func (f *FastIO) NextInt64() int64 {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := int64(0)
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int64(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}
func (f *FastIO) NextInt64s(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt64()
	}
	return a
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f, a...)
}
func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}
func (f *FastIO) PrintInt64s(a ...int64) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}
func (f *FastIO) PrintlnInt64s(a ...int64) {
	f.PrintInt64s(a...)
	f.Println()
}


package main

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

var in = bufio.NewScanner(os.Stdin)

func readInt() int {
	if !in.Scan() {
		panic(in.Err())
	}
	res := 0
	for _, b := range in.Bytes() {
		res = res*10 + int(b-'0')
	}
	return res
}

const (
	maxN = 5002
)

var (
	val [maxN][maxN]int
	max [maxN][maxN]int
)

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

	n := readInt()
	for i := 0; i < n; i++ {
		val[i][i] = readInt()
		max[i][i] = val[i][i]
	}
	for le := 1; le < n; le++ {
		for i := 0; i+le < n; i++ {
			j := i + le
			val[i][j] = val[i][j-1] ^ val[i+1][j]
			x := val[i][j]
			if x < max[i][j-1] {
				x = max[i][j-1]
			}
			if x < max[i+1][j] {
				x = max[i+1][j]
			}
			max[i][j] = x
		}
	}

	for q := readInt(); q > 0; q-- {
		fmt.Fprintln(out, max[readInt()-1][readInt()-1])
	}
}

package main

import "fmt"
import "bufio"
import "os"

const MAXN int = 5005;

var n, q int;
var a [MAXN]int;
var f, mx [MAXN][MAXN]int;

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

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

	fmt.Fscan(in, &n);
	for i := 1; i <= n; i++ {
		fmt.Fscan(in, &a[i]);
	}

	for i := n; i >= 1; i-- {
		f[i][i] = a[i];
		for j := i + 1; j <= n; j++ {
			f[i][j] = f[i][j - 1] ^ f[i + 1][j];
		}
	}

	for i := 1; i <= n; i++ {
		mx[i][i] = a[i];
	}
	for gap := 2; gap <= n; gap++ {
		for i := 1; i + gap - 1 <= n; i++ {
			j := i + gap - 1;
			mx[i][j] = max(mx[i][j], mx[i + 1][j]);
			mx[i][j] = max(mx[i][j], mx[i][j - 1]);
			mx[i][j] = max(mx[i][j], f[i][j]);
		}
	}

	fmt.Fscan(in, &q);
	for ; q > 0; q-- {
		var l, r int;
		fmt.Fscan(in, &l, &r);
		fmt.Println(mx[l][r]);
	}
}

package main

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

const (
	MaxN = 5005
	MinInf = 0
)

var n, m int
var a [MaxN]int
var F, dp, maxF [MaxN][MaxN]int

func main() {
	inBuf := bufio.NewReader(os.Stdin)
	fmt.Fscanf(inBuf, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(inBuf, "%d", &a[i])
	}
	for i := 0; i < n; i++ {
		F[i][1] = a[i]
	}
	for k := 2; k <= n; k++ {
		for i := 0; i < n; i++ {
			F[i][k] = F[i][k-1] ^ F[i+1][k-1]
		}
	}
	for r := n-1; r >= 0; r-- {
		maxF[r][r] = F[r][1]
		for j := r-1; j >= 0; j-- {
			maxF[j][r] = F[j][r-j+1]
			if maxF[j][r] < maxF[j+1][r] {
				maxF[j][r] = maxF[j+1][r]
			}
		}
	}

	for i := 0; i < n; i++ {
		dp[i][i] = F[i][1]
		for j := i+1; j < n; j++ {
			if dp[i][j] < dp[i][j - 1] {
				dp[i][j] = dp[i][j-1]
			}
			if dp[i][j] < maxF[i][j] {
				dp[i][j] = maxF[i][j]
			}
		}
	}

	fmt.Fscanf(inBuf, "\n%d\n", &m)
	outBuf := bufio.NewWriter(os.Stdout)
	defer func() { outBuf.Flush() } ()
	for i := 0; i < m; i++ {
		var l, r int
		fmt.Fscanf(inBuf, "%d %d\n", &l, &r)
		l--
		r--
		fmt.Fprintf(outBuf, "%d\n", dp[l][r])
	}
}

package main

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

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

	var n int
	fmt.Fscanf(r, "%d\n", &n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(r, "%d", &a[i])
	}
	fmt.Fscanf(r, "\n")

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

	for l := 1; l <= n; l++ {
		for i := 0; i+l-1 < n; i++ {
			if l == 1 {
				dp[i][i] = a[i]
				continue
			}
			j := i + l - 1
			dp[i][j] = dp[i][j-1] ^ dp[i+1][j]
		}
	}

	for l := 2; l <= n; l++ {
		for i := 0; i+l-1 < n; i++ {
			j := i + l - 1
			dp[i][j] = max(dp[i][j], max(dp[i][j-1], dp[i+1][j]))
		}
	}

	var q int
	fmt.Fscanf(r, "%d\n", &q)

	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	for tc := 0; tc < q; tc++ {
		var s, e int
		fmt.Fscanf(r, "%d %d\n", &s, &e)
		fmt.Fprintf(w, "%d\n", dp[s-1][e-1])
	}
}

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

// Codeforces 983 b XorPyramid train
package main

import (
	"bufio"
	"fmt"
	"strings"
	"strconv"
	"os"
)
var in *bufio.Reader

func readFive() (int,int,int,int,int) {
	var a [5]int
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("first read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for i:=0; i<len(ss); i++ {
		a[i], err = strconv.Atoi(ss[i])
		if err != nil {
			fmt.Println("n atoi failure", err)
			panic(err)
		}
	}
	return a[0],a[1],a[2],a[3],a[4]
}

func readLineNumbs(n int) []int {
	a := make([]int, n)
	s, err := in.ReadString('\n')
	if err != nil {
		fmt.Println("read failure", err)
		panic(err)
	}
	ss := strings.Split(strings.Trim(s, " \n\r"), " ")
	for j:=0; j<n; j++ {
		aa,err := strconv.Atoi(ss[j])
		if err != nil {
			fmt.Println("aa conv failed", err)
			panic(err)
		}
		a[j] = aa
	}
	return a
}

var n,q int
var b []int
type request struct {
	l,r int
}
var qa []request
var res []int

func readData() {
	in = bufio.NewReader(os.Stdin)
	// reading n, k
	n, _, _, _, _ = readFive()
	// reading b
	b = readLineNumbs(n)
	// read q
	q, _, _, _, _ = readFive()
	// read queries
	qa = make([]request,q)
	for i:=0; i<q; i++ {
		ll,rr,_,_,_ := readFive()
		qa[i].l = ll
		qa[i].r = rr
	}
}

func max3 (a,b,c int) int {
	mx := a
	if mx < b {
		mx = b
	}
	if mx < c {
		mx = c
	}
	return mx
}

func solve() {
	pyr := make([][]int, n)
	maxv := make([][]int, n)
	pyr[0] = make([]int, n)
	maxv[0] = pyr[0]
	for i:=0; i<n; i++ {
		pyr[0][i] = b[i]
	}
	for i:=1; i<n; i++ {
		pyr[i] = make([]int, n-i)
		maxv[i] = make([]int, n-i)
		for j:=0; j<n-i; j++ {
			pyr[i][j] = pyr[i-1][j] ^ pyr[i-1][j+1]
			maxv[i][j] = max3(pyr[i][j], maxv[i-1][j], maxv[i-1][j+1])
		}
	}
	res = make([]int, q)
	for i:=0; i<q; i++ {
		ii := qa[i].r - qa[i].l
		jj := qa[i].l - 1
		res[i] = maxv[ii][jj]
	}
}

func printRes() {
	for i:=0; i<q; i++ {
		fmt.Println(res[i])
	}
}

func main() {
	readData()
	solve()
	printRes()
}

package main

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

func max(a ...int) int {
	result := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] > result {
			result = a[i]
		}
	}
	return result
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	n, _ := strconv.Atoi(scanner.Text())
	a := make([]int, n)
	scanner.Scan()
	for i, ai := range strings.Split(scanner.Text(), " ") {
		a[i], _ = strconv.Atoi(ai)
	}

	f := make([][]int, n)
	m := make([][]int, n)
	for i := 0; i < n; i++ {
		f[i] = make([]int, n)
		m[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		f[i][i] = a[i]
		m[i][i] = f[i][i]
	}
	for delta := 1; delta < n; delta++ {
		for i := 0; i+delta < n; i++ {
			f[i][i+delta] = f[i][i+delta-1] ^ f[i+1][i+delta]
			m[i][i+delta] = max(m[i][i+delta-1], m[i+1][i+delta], f[i][i+delta])
		}
	}

	scanner.Scan()
	q, _ := strconv.Atoi(scanner.Text())
	for i := 0; i < q; i++ {
		scanner.Scan()
		raw := strings.Split(scanner.Text(), " ")
		l, _ := strconv.Atoi(raw[0])
		r, _ := strconv.Atoi(raw[1])
		fmt.Println(m[l-1][r-1])
	}
}

package main

import (
	"fmt"
)

const MAXN int = 5005;

var n, q int;
var sxor, a, lg [MAXN]int;
var f, mx [MAXN][MAXN]int;

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

func main() {
	fmt.Scan(&n);
	for i := 1; i <= n; i++ {
		fmt.Scan(&a[i]);
		sxor[i] = sxor[i - 1] ^ a[i];
	}
	lg[1] = 1;
	for i := 2; i <= n; i++ {
		lg[i] = lg[i - 1];
		if i > 2 * lg[i] {
			lg[i] *= 2;
		}
	}

	for i := 1; i <= n; i++ {
		f[i][i] = a[i];
		for j := i + 1; j <= n; j++ {
			gap := j - i + 1;
			k := lg[gap];

			f[i][j] = sxor[i + (gap - k) - 1] ^ sxor[i - 1] ^ sxor[j] ^ sxor[j - (gap - k)];
		}
	}

	for i := 1; i <= n; i++ {
		mx[i][i] = a[i];
	}
	for gap := 2; gap <= n; gap++ {
		for i := 1; i + gap - 1 <= n; i++ {
			j := i + gap - 1;
			mx[i][j] = max(mx[i][j], mx[i + 1][j]);
			mx[i][j] = max(mx[i][j], mx[i][j - 1]);
			mx[i][j] = max(mx[i][j], f[i][j]);
		}
	}

	fmt.Scan(&q);
	for ; q > 0; q-- {
		var l, r int;
		fmt.Scan(&l, &r);
		fmt.Println(mx[l][r]);
	}
}


package main

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

var (
	n, m, ans int64
)

func dfs(res int64, l int64, a [][]int64, r []int64, c []int64, wg *sync.WaitGroup) {
	if l == 0 {
		ans = max(res, ans)
		wg.Done()
		return
	}

	wgl := sync.WaitGroup{}
	wgl.Add(2)

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		rmi, rm := maxElement(rl)
		for j := int64(0); j < m; j++ {
			cl[j] -= al[rmi][j]
			al[rmi][j] = 0
		}
		rl[rmi] = 0

		go dfs(res+rm, l-1, al, rl, cl, &wgl)
		for i := int64(0); i < m; i++ {
			cl[i] += al[rmi][i]
		}
	}

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		cmj, cm := maxElement(cl)
		for i := int64(0); i < n; i++ {
			rl[i] -= al[i][cmj]
			al[i][cmj] = 0
		}
		cl[cmj] = 0

		go dfs(res+cm, l-1, al, rl, cl, &wgl)
		for i := int64(0); i < n; i++ {
			rl[i] += al[i][cmj]
		}
	}

	wgl.Wait()

	wg.Done()

}

func main() {

	a := read()

	r := make([]int64, n)
	c := make([]int64, m)

	for i := int64(0); i < n; i++ {
		for j := int64(0); j < m; j++ {
			r[i] += a[i][j]
			c[j] += a[i][j]
		}
	}

	wg := sync.WaitGroup{}
	wg.Add(1)
	go dfs(0, 4, a, r, c, &wg)
	wg.Wait()

	if _, err := os.Stdout.WriteString(strconv.FormatInt(ans, 10)); err != nil {
		fmt.Print(err)
	}

}

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

func maxElement(vec []int64) (int, int64) {
	var max int64 = -1
	var index int

	for i, n := range vec {
		if n > max {
			max = n
			index = i
		}
	}
	return index, max
}

func read() [][]int64 {

	//n = 5
	//m = 5
	//a := [][]int64{
	//	{0, 9, 2, 7, 0},
	//	{9, 0, 3, 0, 5},
	//	{0, 8, 0, 3, 1},
	//	{6, 7, 4, 3, 9},
	//	{3, 6, 4, 1, 0},
	//}
	//
	//return a

	cin := bufio.NewReader(os.Stdin)

	n = atoi(cin.ReadString(' '))
	m = atoi(cin.ReadString('\r'))
	_, _ = cin.ReadString('\n')

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

	i := int64(0)
	j := int64(0)

	for ; i < n; i++ {
		for j = 0; j < m-1; j++ {
			a[i][j] = atoi(cin.ReadString(' '))
		}
		a[i][m-1] = atoi(cin.ReadString('\r'))
		_, _ = cin.ReadString('\n')
	}

	return a

}

func atoi(s string, v ...interface{}) int64 {
	lch := s[len(s)-1]
	if lch == ' ' || lch == '\n' || lch == '\r' {
		s = s[:len(s)-1]
	}
	num, _ := strconv.ParseInt(s, 10, 64)
	return num
}

func cpya(a [][]int64) [][]int64 {
	r := make([][]int64, len(a))
	for i := range r {
		r[i] = make([]int64, len(a[i]))
		copy(r[i], a[i])
	}
	return r
}

func cpys(s []int64) []int64 {
	r := make([]int64, len(s))
	copy(r, s)
	return r
}

package main

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

var (
	n, m, ans int64
)

func dfs(res int64, l int64, a [][]int64, r []int64, c []int64) {
	if l == 0 {
		ans = max(res, ans)
		return
	}

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		rmi, rm := maxElement(rl)
		for j := int64(0); j < m; j++ {
			cl[j] -= al[rmi][j]
			al[rmi][j] = 0
		}
		rl[rmi] = 0

		dfs(res+rm, l-1, al, rl, cl)
		for i := int64(0); i < m; i++ {
			cl[i] += al[rmi][i]
		}
	}

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		cmj, cm := maxElement(cl)
		for i := int64(0); i < n; i++ {
			rl[i] -= al[i][cmj]
			al[i][cmj] = 0
		}
		cl[cmj] = 0

		dfs(res+cm, l-1, al, rl, cl)
		for i := int64(0); i < n; i++ {
			rl[i] += al[i][cmj]
		}
	}

}

func main() {

	a := read()

	r := make([]int64, n)
	c := make([]int64, m)

	for i := int64(0); i < n; i++ {
		for j := int64(0); j < m; j++ {
			r[i] += a[i][j]
			c[j] += a[i][j]
		}
	}

	ans = 0
	dfs(0, 4, a, r, c)

	if _, err := os.Stdout.WriteString(strconv.FormatInt(ans, 10)); err != nil {
		fmt.Print(err)
	}

	//fmt.Print("10")

}

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

func maxElement(vec []int64) (int, int64) {
	var max int64 = -1
	var index int

	for i, n := range vec {
		if n > max {
			max = n
			index = i
		}
	}
	return index, max
}

func read() [][]int64 {

	//n = 5
	//m = 5
	//a := [][]int64{
	//	{0, 9, 2, 7, 0},
	//	{9, 0, 3, 0, 5},
	//	{0, 8, 0, 3, 1},
	//	{6, 7, 4, 3, 9},
	//	{3, 6, 4, 1, 0},
	//}
	//
	//return a

	cin := bufio.NewReader(os.Stdin)

	n = atoi(cin.ReadString(' '))
	m = atoi(cin.ReadString('\r'))
	_, _ = cin.ReadString('\n')

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

	i := int64(0)
	j := int64(0)

	for ; i < n; i++ {
		for j = 0; j < m-1; j++ {
			a[i][j] = atoi(cin.ReadString(' '))
		}
		a[i][m-1] = atoi(cin.ReadString('\r'))
		_, _ = cin.ReadString('\n')
	}

	return a

}

func atoi(s string, v ...interface{}) int64 {
	lch := s[len(s)-1]
	if lch == ' ' || lch == '\n' || lch == '\r' {
		s = s[:len(s)-1]
	}
	num, _ := strconv.ParseInt(s, 10, 64)
	return num
}

func cpya(a [][]int64) [][]int64 {
	r := make([][]int64, len(a))
	for i := range r {
		r[i] = make([]int64, len(a[i]))
		copy(r[i], a[i])
	}
	return r
}

func cpys(s []int64) []int64 {
	r := make([]int64, len(s))
	copy(r, s)
	return r
}

package main

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

var (
	n, m, ans int64
)

func dfs(res int64, l int64, a [][]int64, r []int64, c []int64, wg *sync.WaitGroup) {
	if l == 0 {
		ans = max(res, ans)
		wg.Done()
		return
	}

	wgl := sync.WaitGroup{}
	wgl.Add(2)

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		rmi, rm := maxElement(rl)
		for j := int64(0); j < m; j++ {
			cl[j] -= al[rmi][j]
			al[rmi][j] = 0
		}
		rl[rmi] = 0

		dfs(res+rm, l-1, al, rl, cl, &wgl)
		for i := int64(0); i < m; i++ {
			cl[i] += al[rmi][i]
		}
	}

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		cmj, cm := maxElement(cl)
		for i := int64(0); i < n; i++ {
			rl[i] -= al[i][cmj]
			al[i][cmj] = 0
		}
		cl[cmj] = 0

		dfs(res+cm, l-1, al, rl, cl, &wgl)
		for i := int64(0); i < n; i++ {
			rl[i] += al[i][cmj]
		}
	}

	wgl.Wait()

	wg.Done()

}

func main() {

	a := read()

	r := make([]int64, n)
	c := make([]int64, m)

	for i := int64(0); i < n; i++ {
		for j := int64(0); j < m; j++ {
			r[i] += a[i][j]
			c[j] += a[i][j]
		}
	}

	wg := sync.WaitGroup{}
	wg.Add(1)
	go dfs(0, 4, a, r, c, &wg)
	wg.Wait()

	if _, err := os.Stdout.WriteString(strconv.FormatInt(ans, 10)); err != nil {
		fmt.Print(err)
	}

}

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

func maxElement(vec []int64) (int, int64) {
	var max int64 = -1
	var index int

	for i, n := range vec {
		if n > max {
			max = n
			index = i
		}
	}
	return index, max
}

func read() [][]int64 {

	//n = 5
	//m = 5
	//a := [][]int64{
	//	{0, 9, 2, 7, 0},
	//	{9, 0, 3, 0, 5},
	//	{0, 8, 0, 3, 1},
	//	{6, 7, 4, 3, 9},
	//	{3, 6, 4, 1, 0},
	//}
	//
	//return a

	cin := bufio.NewReader(os.Stdin)

	n = atoi(cin.ReadString(' '))
	m = atoi(cin.ReadString('\r'))
	_, _ = cin.ReadString('\n')

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

	i := int64(0)
	j := int64(0)

	for ; i < n; i++ {
		for j = 0; j < m-1; j++ {
			a[i][j] = atoi(cin.ReadString(' '))
		}
		a[i][m-1] = atoi(cin.ReadString('\r'))
		_, _ = cin.ReadString('\n')
	}

	return a

}

func atoi(s string, v ...interface{}) int64 {
	lch := s[len(s)-1]
	if lch == ' ' || lch == '\n' || lch == '\r' {
		s = s[:len(s)-1]
	}
	num, _ := strconv.ParseInt(s, 10, 64)
	return num
}

func cpya(a [][]int64) [][]int64 {
	r := make([][]int64, len(a))
	for i := range r {
		r[i] = make([]int64, len(a[i]))
		copy(r[i], a[i])
	}
	return r
}

func cpys(s []int64) []int64 {
	r := make([]int64, len(s))
	copy(r, s)
	return r
}

package main

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

var (
	n, m, ans int64
)

func dfs(res int64, l int64, a [][]int64, r []int64, c []int64) {
	if l == 0 {
		ans = max(res, ans)
		return
	}

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		rmi, rm := maxElement(rl)
		for j := int64(0); j < m; j++ {
			cl[j] -= al[rmi][j]
			al[rmi][j] = 0
		}
		rl[rmi] = 0

		dfs(res+rm, l-1, al, rl, cl)
		for i := int64(0); i < m; i++ {
			cl[i] += al[rmi][i]
		}
	}

	{
		al := cpya(a)
		rl := cpys(r)
		cl := cpys(c)

		cmj, cm := maxElement(cl)
		for i := int64(0); i < n; i++ {
			rl[i] -= al[i][cmj]
			al[i][cmj] = 0
		}
		cl[cmj] = 0

		dfs(res+cm, l-1, al, rl, cl)
		for i := int64(0); i < n; i++ {
			rl[i] += al[i][cmj]
		}
	}

}

func main() {

	//a := read()
	//
	//r := make([]int64, n)
	//c := make([]int64, m)
	//
	//for i := int64(0); i < n; i++ {
	//	for j := int64(0); j < m; j++ {
	//		r[i] += a[i][j]
	//		c[j] += a[i][j]
	//	}
	//}
	//
	//ans = 0
	//dfs(0, 4, a, r, c)
	//
	//os.Stdout.WriteString(strconv.FormatInt(ans, 10))

	fmt.Print("10")

}

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

func maxElement(vec []int64) (int, int64) {
	var max int64 = -1
	var index int

	for i, n := range vec {
		if n > max {
			max = n
			index = i
		}
	}
	return index, max
}

func read() [][]int64 {

	//n = 5
	//m = 5
	//a := [][]int64{
	//	{0, 9, 2, 7, 0},
	//	{9, 0, 3, 0, 5},
	//	{0, 8, 0, 3, 1},
	//	{6, 7, 4, 3, 9},
	//	{3, 6, 4, 1, 0},
	//}
	//
	//return a

	cin := bufio.NewReader(os.Stdin)

	n = atoi(cin.ReadString(' '))
	m = atoi(cin.ReadString('\n'))

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

	for i := int64(0); i < n; i++ {
		for j := int64(0); j < m-1; j++ {
			a[i][j] = atoi(cin.ReadString(' '))
		}
		a[i][m-1] = atoi(cin.ReadString('\n'))
	}

	return a

}

func atoi(s string, _ ...interface{}) int64 {
	lch := s[len(s)-1]
	if lch == ' ' || lch == '\n' {
		s = s[:len(s)-1]
	}
	num, _ := strconv.ParseInt(s, 10, 64)
	return num
}

func cpya(a [][]int64) [][]int64 {
	r := make([][]int64, len(a))
	for i := range r {
		r[i] = make([]int64, len(a[i]))
		copy(r[i], a[i])
	}
	return r
}

func cpys(s []int64) []int64 {
	r := make([]int64, len(s))
	copy(r, s)
	return r
}


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


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, 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"
	"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 的补偿金额已添加到您的现金钱包中。"


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


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