Suppose you are performing the following algorithm. There is an array $$$v_1, v_2, \dots, v_n$$$ filled with zeroes at start. The following operation is applied to the array several times — at $$$i$$$-th step ($$$0$$$-indexed) you can:   either choose position $$$pos$$$ ($$$1 \le pos \le n$$$) and increase $$$v_{pos}$$$ by $$$k^i$$$;  or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array $$$v$$$ equal to the given array $$$a$$$ ($$$v_j = a_j$$$ for each $$$j$$$) after some step?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 30$$$, $$$2 \le k \le 100$$$) — the size of arrays $$$v$$$ and $$$a$$$ and value $$$k$$$ used in the algorithm. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{16}$$$) — the array you'd like to achieve.

For each test case print YES (case insensitive) if you can achieve the array $$$a$$$ after some step or NO (case insensitive) otherwise.

NoteIn the first test case, you can stop the algorithm before the $$$0$$$-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add $$$k^0$$$ to $$$v_1$$$ and stop the algorithm.In the third test case, you can't make two $$$1$$$ in the array $$$v$$$.In the fifth test case, you can skip $$$9^0$$$ and $$$9^1$$$, then add $$$9^2$$$ and $$$9^3$$$ to $$$v_3$$$, skip $$$9^4$$$ and finally, add $$$9^5$$$ to $$$v_2$$$.

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := 0
	fmt.Fscanf(in, "%d\n", &t)
	for tt := 0; tt < t; tt++ {
		n, k := 0, int64(0)
		fmt.Fscanf(in, "%d %d\n", &n, &k)
		a := make([]int64, 0)
		tmp := int64(0)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &tmp)
			if tmp != 0 {
				a = append(a, tmp)
			}
		}
		fmt.Fscanf(in, "\n")
		n = len(a)
		ok := true
		arr := make([][]int, n)
		for i := 0; i < n; i++ {
			arr[i] = make([]int, 100)
			tmp = a[i]
			//fmt.Println("debug")
			for tmp > 0 {
				//fmt.Println(tmp)
				if tmp != 1 && tmp < k {
					ok = false
					break
				}
				tk := int64(1)
				id := 0
				for tk*k <= tmp {
					tk *= k
					id++
				}
				tmp -= tk
				arr[i][id]++
			}
			//fmt.Println("debug end")
		}
		for i := 0; i < 100; i++ {
			tmp := 0
			for j := 0; j < n; j++ {
				tmp += arr[j][i]
			}
			if tmp > 1 {
				ok = false
			}
		}
		if ok {
			fmt.Fprintf(out, "YES\n")
		} else {
			fmt.Fprintf(out, "NO\n")
		}
	}
	return
}

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

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

package main

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

func main() {
	defer writer.Flush()

	var tests int
	Input(&tests)

	for t := 1; t <= tests; t++ {
		var n, k int
		Input(&n, &k)

		a := make([]int, 60)
		okay := true
		for i := 0; i < n; i++ {
			var x int64
			Input(&x)

			for i := 0; x > 0; i++ {
				r := x % int64(k)
				a[i] += int(r)
				if a[i] > 1 {
					okay = false
					break;
				}

				x /= int64(k)
			}
		}

		Print(If(okay, "YES", "NO"), "\n")
	}
}

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

func Input(a ...interface{}) {
	_, _ = fmt.Fscan(reader, a...)
}

func Print(a ...interface{}) {
	_, _ = fmt.Fprint(writer, a...)
}

func If(condition bool, x interface{}, y interface{}) interface{} {
	if condition {
		return x
	}
	return y
}

package main

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

func main() {
	defer writer.Flush()

	var tests int
	Input(&tests)

	for t := 1; t <= tests; t++ {
		var n, k int
		Input(&n, &k)

		a := make([]int, 60)
		okay := true
		for i := 0; i < n; i++ {
			var x int64
			Input(&x)

			for i := 0; x > 0; i++ {
				r := x % int64(k)
				a[i] += int(r)
				if a[i] > 1 {
					okay = false
				}

				x /= int64(k)
			}
		}

		Print(If(okay, "YES", "NO"), "\n")
	}
}

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

func Input(a ...interface{}) {
	_, _ = fmt.Fscan(reader, a...)
}

func Print(a ...interface{}) {
	_, _ = fmt.Fprint(writer, a...)
}

func If(condition bool, x interface{}, y interface{}) interface{} {
	if condition {
		return x
	}
	return y
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 {
				continue
			}
			if x % int64(k) != 0 && (x-1) % int64(k) != 0 {
				flag = false
				break
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
			if !flag {
				break
			}
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current  <= x / k {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

/*
URL:
https://codeforces.com/problemset/problem/1312/C
*/

package main

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

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	t int

	n, k int64
	A    []int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k = ReadInt64_2()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	B := make([][]int64, n)

	for i := 0; i < 60; i++ {
		for j := int64(0); j < n; j++ {
			// memo[A[j]%k]++
			B[j] = append(B[j], A[j]%k)
			A[j] /= k
		}
	}

	for i := int64(0); i < n; i++ {
		B[i] = Reverse(B[i])
	}

	// for i := int64(0); i < n; i++ {
	// 	PrintfDebug("%v\n", B[i])
	// }
	// PrintfDebug("\n")

	for i := 0; i < 60; i++ {
		num := int64(0)
		for j := int64(0); j < n; j++ {
			num += B[j][i]
		}

		if num > 1 {
			fmt.Println("NO")
			return
		}
	}

	fmt.Println("YES")
}

func Reverse(A []int64) []int64 {
	res := []int64{}

	n := len(A)
	for i := n - 1; i >= 0; i-- {
		res = append(res, A[i])
	}

	return res
}

/*******************************************************************/

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

package main

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

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

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

	for t := 0; t < ts; t++ {
		var n int
		var k int64
		fmt.Fscanf(r, "%d %d\n", &n, &k)

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

		fmt.Fprintf(w, "%s\n", can(a, k))
	}
}

func can(a []int64, k int64) string {
	mp := make(map[int]int)
	for _, e := range a {
		p := 0
		for e > 0 {
			r := int(e % k)
			e /= k
			if r > 1 {
				return "NO"
			}
			if r > 0 {
				mp[p]++
				if mp[p] > 1 {
					return "NO"
				}
			}
			p++
		}
	}
	return "YES"
}

package main

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

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

	var t, n, k, v int64
o:
	for Fscan(in, &t); t > 0; t-- {
		cnts := [55]int64{}
		for Fscan(in, &n, &k); n > 0; n-- {
			i := 0
			for Fscan(in, &v); v > 0; v /= k {
				cnts[i] += v % k
				i++
			}
		}
		for _, v := range cnts {
			if v > 1 {
				Fprintln(out, "NO")
				continue o
			}
		}
		Fprintln(out, "YES")
	}
}

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

package main

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

func main() {
	for testCase := scanInt(); testCase > 0; testCase--{
		count, kValue := scanInt64(), scanInt64()
		givenArray := scanInt64Slice(int(count))
		hasFound := false
		answerArray := make([]int64, 60)
		for i := int64(0); i < count; i++{
			for j := int64(0); givenArray[i] > 0; j++{
				answerArray[j] += givenArray[i] % kValue
				givenArray[i] /= kValue
			}
		}

		for i := 0; i < 60; i++{
			if answerArray[i] > 1{
				hasFound = true
				break
			}
		}
		if !hasFound{
			printFmt("YES")
		}else{
			printFmt("NO")
		}
	}
	close(channelType)
	oWg.Wait()
}

/*********************** I/O ***********************/

var channelType chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var printFmt func(a ...interface{}) (n int, err error)

func init() {
	printFmt = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	channelType = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

		for line := range channelType {
			writer.WriteString(line + "\n")
		}
	}()
}

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

/*********************** Utils ***********************/

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if (a == 0) {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}
func min(args ...int) int { mn, _ := minMaxFinder(args...); return mn }
func max(args ...int) int { _, mx := minMaxFinder(args...); return mx }
func minMaxFinder(args ...int) (int, int) { minVal, maxVal := int(math.MaxInt32), int(math.MinInt32); for _, v := range args { if v < minVal { minVal = v }; if v > maxVal { maxVal = v } }; return minVal, maxVal }

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var t, n int
	var k int64
	fmt.Fscan(reader, &t)
	for z := 0; z < t; z++ {
		fmt.Fscan(reader, &n, &k)
		a := make([]int64, n)
		var ma int64 = 0
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
			if a[i] > ma {
				ma = a[i]
			}
 		}
		var k1 int = 0
		sum := make([]int64, 64)
		vis := make([]bool, 64)
		sum[k1] = 1
		for ; ; k1++ {
			if sum[k1] > ma {
				break
			}
			sum[k1 + 1] = sum[k1] * k
		}
		var flag bool = false
		for i := 0; i < n; i++ {
			for j := k1; j >= 0; j-- {
				if !vis[j] && a[i] >= sum[j] {
					a[i] -= sum[j]
					vis[j] = true
				}
			}
			if a[i] != 0 {
				flag = true
			}
		}
		if flag == false {
			fmt.Fprintln(writer, "YES")
		} else {
			fmt.Fprintln(writer, "NO")
		}
	}
}//2020-07-31 15:24:39.472

package main

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

const INFINITY = math.MaxInt32/2 - 1

func exec(stdin *Stdin, stdout *Stdout) {
	for t := stdin.ReadInt(); t > 0; t-- {
		n := stdin.ReadInt()
		k := stdin.ReadInt64()
		a := stdin.ReadInt64Slice(n)

		d := map[int]int64{}
		for _, v := range a {
			div := 0
			for v > 0 {
				if _, ok := d[div]; ok {
					d[div] += v % k
				} else {
					d[div] = v % k
				}
				v /= k
				div++
			}
		}

		ok := true
		for _, v := range d {
			if v > 1 {
				ok = false
				break
			}
		}

		if ok {
			stdout.Println("YES")
		} else {
			stdout.Println("NO")
		}
	}
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadInt64() int64 {
	n, _ := strconv.ParseInt(s.Read(), 10, 64)
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

func (s *Stdin) ReadIntSlice(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt()
	}
	return a
}

func (s *Stdin) ReadInt64Slice(n int) []int64 {
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt64()
	}
	return a
}

func (s *Stdin) ReadStringSlice(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = s.Read()
	}
	return a
}

func (s *Stdin) ReadFloat64Slice(n int) []float64 {
	a := make([]float64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadFloat64()
	}
	return a
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max(a int, b ...int) int {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

func Abs(x int) int {
	if x > 0 {
		return x
	} else {
		return x * -1
	}
}

func Pow(x, y int) int {
	z := 1
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y -= 1
		}
	}
	return z
}

func IsPrime(x int) bool {
	if x < 2 {
		return false
	}

	for i := 2; i*i <= x; i++ {
		if x%i == 0 {
			return false
		}
	}
	return true
}

func Gcd(x, y int) int {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func Lcm(x, y int) int {
	return x * y / Gcd(x, y)
}

func CeilDiv(x, y int) int {
	if x%y == 0 {
		return x / y
	} else {
		return x/y + 1
	}
}

func LCS(s, t string) string {
	n := len(s)
	m := len(t)
	dp := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = make([]int, m+1)
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if s[i-1] == t[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				dp[i][j] = Max(dp[i-1][j], dp[i][j-1])
			}
		}
	}

	x := n
	y := m
	u := make([]byte, dp[n][m])
	i := dp[n][m] - 1
	for x > 0 && y > 0 {
		if dp[x][y] == dp[x-1][y] {
			x--
		} else if dp[x][y] == dp[x][y-1] {
			y--
		} else {
			x--
			y--
			u[i] = s[x]
			i--
		}
	}

	return string(u)
}

// [0..n) から r個選んだ組合せを生成する。
// r < 0 の場合はすべての組合せを生成する。
func Combinations(n int, r int) [][]int {
	a := [][]int{}
	for i := uint(0); i < (1 << uint(n)); i++ {
		b := []int{}
		for j := uint(0); j < uint(n); j++ {
			if i&(uint(1)<<j) != 0 {
				b = append(b, int(j))
			}
		}

		if r < 0 || len(b) == r {
			a = append(a, b)
		}
	}
	return a
}

// [0..n)の順列を生成する。
func Permutations(n int) [][]int {
	type e struct {
		bit uint
		a   []int
	}

	q := []*e{}
	for i := 0; i < n; i++ {
		q = append(q, &e{bit: 1 << uint(i), a: []int{i}})
	}

	p := [][]int{}
	for x := 0; x < len(q); x++ {
		cur := q[x]
		if cur.bit == (1<<uint(n) - 1) {
			p = append(p, cur.a)
			continue
		}

		for i := 0; i < n; i++ {
			if cur.bit&(1<<uint(i)) != 0 {
				continue
			}

			m := len(cur.a) + 1
			b := make([]int, m)
			copy(b, cur.a)
			b[m-1] = i
			q = append(q, &e{bit: cur.bit | (1 << uint(i)), a: b})
		}
	}
	return p
}

func ReverseSlice(v interface{}) {
	if reflect.TypeOf(v).Kind() == reflect.Slice {
		slice := reflect.ValueOf(v)
		for i1, n := 0, slice.Len(); i1 < n/2; i1++ {
			i2 := n - i1 - 1
			v1 := reflect.ValueOf(slice.Index(i1).Interface())
			slice.Index(i1).Set(slice.Index(i2))
			slice.Index(i2).Set(v1)
		}
	}
}

func ReverseString(s string) string {
	t := []rune(s)
	ReverseSlice(t)
	return string(t)
}

func ToStringSlice(slice interface{}) []string {
	// 本来はerrを返却すべき。 利用する側(=自分)は引数がsliceであることを知っている。
	if reflect.TypeOf(slice).Kind() != reflect.Slice {
		panic(fmt.Sprintf("%v is not slice", slice))
	}

	src := reflect.ValueOf(slice)
	n := src.Len()
	dst := make([]string, n)
	for i := 0; i < n; i++ {
		dst[i] = fmt.Sprintf("%v", src.Index(i))
	}
	return dst
}

func CreateMatrix(x, y int) [][]int {
	matrix := make([][]int, x)
	for i := 0; i < x; i++ {
		matrix[i] = make([]int, y)
	}
	return matrix
}

package main

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

func main() {
	defer writer.Flush()

	var tests int
	Input(&tests)

	for t := 1; t <= tests; t++ {
		var n, k int
		Input(&n, &k)

		a := make([]int, 60)
		okay := true
		for i := 0; i < n; i++ {
			var x int64
			Input(&x)

			for i := 1; x > 0; i++ {
				if x%int64(k) == 1 {
					a[i] += 1
					if a[i] > 1 {
						okay = false
					}
				}

				x /= int64(k)
			}
		}

		Print(If(okay, "YES", "NO"), "\n")
	}
}

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

func Input(a ...interface{}) {
	_, _ = fmt.Fscan(reader, a...)
}

func Print(a ...interface{}) {
	_, _ = fmt.Fprint(writer, a...)
}

func If(condition bool, x interface{}, y interface{}) interface{} {
	if condition {
		return x
	}
	return y
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 || k == 1{
				continue
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current * k <= x {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 || k == 1{
				continue
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current  <= x / k {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		current, flag, isOverFLow := int64(1), true, false
		ans = strings.Split(string(line), " ")
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if (!isOverFLow && x%current == 0) || (isOverFLow && x == 0) {
				if current > (max / int64(k)) {
					isOverFLow = true
				} else {
					current = current * int64(k)
				}
			} else {
				// fmt.Println(x, current, isOverFLow)
				flag = false
				break
			}
		}
		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		current, flag, isOverFLow := int64(1), true, false
		ans = strings.Split(string(line), " ")
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if (!isOverFLow && x%current == 0) || (isOverFLow && x == 0) {
				current = current * int64(k)
				if current > 10000000000000000 {
					isOverFLow = true
				}
			} else {
				// fmt.Println(x, current, isOverFLow)
				flag = false
				break
			}
		}
		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

package main

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

func main() {
	var cases int
	fmt.Scanf("%d\n", &cases)
	reader := bufio.NewReader(os.Stdin)
	// max := int64(10000000000000000)
	// fmt.Println(math.MaxInt64)
	for i := 0; i < cases; i++ {
		line := readLine(reader)
		ans := strings.Split(string(line), " ")
		n, _ := strconv.Atoi(ans[0])
		k, _ := strconv.Atoi(ans[1])
		line = readLine(reader)
		flag := true
		ans = strings.Split(string(line), " ")
		m := make(map[int]struct{})
		for i := 0; i < n; i++ {
			x, _ := strconv.ParseInt(ans[i], 10, 64)
			if x == 0 {
				continue
			}
			if x % int64(k) != 0 && (x-1) % int64(k) != 0 {
				flag = false
				break
			}
			// fmt.Println(m)
			flag = diverceX(&m, int64(k), x)
		}

		if flag {
			fmt.Println("YES")
		} else {
			fmt.Println("NO")
		}
	}
}

func diverceX(m *map[int]struct{}, k, x int64) bool {
	if x == 0 {
		return true
	}
	current := int64(1)
	i:=0
	for current  <= x / k {
		current = current * k
		i++
	}
	if _, ok := (*m)[i]; ok {
		// fmt.Println("false: ", x, current)
		return false
	}
	(*m)[i] = struct{}{}
	return diverceX(m, k, x - current)
}

func readLine(reader *bufio.Reader) []byte {
	result := make([]byte, 0)
	for {
		s, isPrefix, err := reader.ReadLine()
		if err != nil {
			fmt.Printf("error=%+v\n", err)
			break
		}
		result = append(result, s...)
		if !isPrefix {
			break
		}
	}
	return result
}

/*
URL:
https://codeforces.com/problemset/problem/1312/C
*/

package main

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

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	t int

	n, k int64
	A    []int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k = ReadInt64_2()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	B := make([][]int64, n)

	for i := 0; i < 60; i++ {
		for j := int64(0); j < n; j++ {
			// memo[A[j]%k]++
			B[j] = append(B[j], A[j]%k)
			A[j] /= k
		}
	}

	for i := int64(0); i < n; i++ {
		B[i] = Reverse(B[i])
	}

	// for i := int64(0); i < n; i++ {
	// 	PrintfDebug("%v\n", B[i])
	// }
	// PrintfDebug("\n")

	for i := 0; i < 60; i++ {
		memo := make([]int, k)
		for j := int64(0); j < n; j++ {
			memo[B[j][i]]++
		}

		for j := int64(1); j < k; j++ {
			if memo[j] > 1 {
				fmt.Println("NO")
				return
			}
		}
	}

	fmt.Println("YES")
}

func Reverse(A []int64) []int64 {
	res := []int64{}

	n := len(A)
	for i := n - 1; i >= 0; i-- {
		res = append(res, A[i])
	}

	return res
}

/*******************************************************************/

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

/*
URL:
https://codeforces.com/problemset/problem/1312/C
*/

package main

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

/********** FAU standard libraries **********/

//fmt.Sprintf("%b\n", 255) 	// binary expression

/********** I/O usage **********/

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := ZeroPaddingRuneSlice(num, 32)
//str := PrintIntsLine(X...)

/*******************************************************************/

const (
	// General purpose
	MOD          = 1000000000 + 7
	ALPHABET_NUM = 26
	INF_INT64    = math.MaxInt64
	INF_BIT60    = 1 << 60
	INF_INT32    = math.MaxInt32
	INF_BIT30    = 1 << 30
	NIL          = -1

	// for dijkstra, prim, and so on
	WHITE = 0
	GRAY  = 1
	BLACK = 2
)

func init() {
	// bufio.ScanWords <---> bufio.ScanLines
	ReadString = newReadString(os.Stdin, bufio.ScanWords)
	stdout = bufio.NewWriter(os.Stdout)
}

var (
	t int

	n, k int64
	A    []int64
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n, k = ReadInt64_2()
		A = ReadInt64Slice(int(n))

		solve()
	}
}

func solve() {
	for i := 0; i < 60; i++ {
		memo := make([]int, 150)
		for j := int64(0); j < n; j++ {
			memo[A[j]%k]++
			A[j] /= k
		}

		for j := int64(1); j < k; j++ {
			if memo[j] > 1 {
				fmt.Println("NO")
				return
			}
		}
	}

	fmt.Println("YES")
}

/*******************************************************************/

/*********** I/O ***********/

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return int(readInt64())
}
func ReadInt2() (int, int) {
	return int(readInt64()), int(readInt64())
}
func ReadInt3() (int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64())
}
func ReadInt4() (int, int, int, int) {
	return int(readInt64()), int(readInt64()), int(readInt64()), int(readInt64())
}

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

func readInt64() int64 {
	i, err := strconv.ParseInt(ReadString(), 0, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// ReadIntSlice returns an integer slice that has n integers.
func ReadIntSlice(n int) []int {
	b := make([]int, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt()
	}
	return b
}

// ReadInt64Slice returns as int64 slice that has n integers.
func ReadInt64Slice(n int) []int64 {
	b := make([]int64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadInt64()
	}
	return b
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

func readFloat64() float64 {
	f, err := strconv.ParseFloat(ReadString(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// ReadFloatSlice returns an float64 slice that has n float64.
func ReadFloat64Slice(n int) []float64 {
	b := make([]float64, n)
	for i := 0; i < n; i++ {
		b[i] = ReadFloat64()
	}
	return b
}

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

/*********** Debugging ***********/

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

// Strtoi is a wrapper of strconv.Atoi().
// If strconv.Atoi() returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintIntsLine returns integers string delimited by a space.
func PrintInts64Line(A ...int64) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

// PrintfDebug is wrapper of fmt.Fprintf(os.Stderr, format, a...)
func PrintfDebug(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

// PrintfBufStdout is function for output strings to buffered os.Stdout.
// You may have to call stdout.Flush() finally.
func PrintfBufStdout(format string, a ...interface{}) {
	fmt.Fprintf(stdout, format, a...)
}

package main

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

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

	var t, n, k, v int
o:
	for Fscan(in, &t); t > 0; t-- {
		cnts := [55]int{}
		for Fscan(in, &n, &k); n > 0; n-- {
			i := 0
			for Fscan(in, &v); v > 0; v /= k {
				cnts[i] += v % k
				i++
			}
		}
		for _, v := range cnts {
			if v > 1 {
				Fprintln(out, "NO")
				continue o
			}
		}
		Fprintln(out, "YES")
	}
}

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

package main

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

func main() {
	for testCase := scanInt(); testCase > 0; testCase--{
		count, kValue := scanInt(), scanInt()
		givenArray := scanIntSlice(count)
		hasFound := false
		answerArray := make([]int, 60)
		for i := 0; i < count; i++{
			for j := 0; givenArray[i] > 0; j++{
				answerArray[j] += givenArray[i] % kValue
				givenArray[i] /= kValue
			}
		}

		for i := 0; i < 60; i++{
			if answerArray[i] > 1{
				hasFound = true
				break
			}
		}
		if !hasFound{
			printFmt("YES")
		}else{
			printFmt("NO")
		}
	}
	close(channelType)
	oWg.Wait()
}

/*********************** I/O ***********************/

var channelType chan string
var in *bufio.Scanner
var oWg *sync.WaitGroup
var printFmt func(a ...interface{}) (n int, err error)

func init() {
	printFmt = fmt.Println

	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)

	channelType = make(chan string, 16)
	oWg = &sync.WaitGroup{}
	oWg.Add(1)

	writer := bufio.NewWriter(os.Stdout)
	go func() {
		defer oWg.Done()
		defer writer.Flush()

		for line := range channelType {
			writer.WriteString(line + "\n")
		}
	}()
}

func scanString() string {in.Scan(); return in.Text() }
func scanInt() int {i, _ := strconv.Atoi(scanString()); return i}
func scanInt64() int64 {i, _ := strconv.ParseInt(scanString(), 10, 64); return i}
func scanStringSlice(n int) []string {s := make([]string, n); for i := 0; i < n; i++ {s[i] = scanString()}; return s}
func scanIntSlice(n int) []int {arr := make([]int, n); for i := 0; i < n; i++ {arr[i] = scanInt()}; return arr}
func scanInt64Slice(n int) []int64 {arr := make([]int64, n); for i := 0; i < n; i++ {arr[i] = scanInt64()}; return arr}

/*********************** Utils ***********************/

func stringEquivalent(v interface{}) string {return fmt.Sprintf("%v", v)}
func spaceSeperatedStringFromArray(a []int) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.Itoa(a[i]) + " ")}; return sb.String()}
func spaceSeperatedStringFromArray64(a []int64) string {sb := strings.Builder{}; sb.Grow(len(a) * 9); for i := range a {sb.WriteString(strconv.FormatInt(a[i], 10) + " ")}; return sb.String()}
func minMaxFromArray(args ...int64) (int64, int64) {minVal, maxVal := int64(math.MaxInt64), int64(math.MinInt64); for _, v := range args {if v < minVal {minVal = v}; if v > maxVal {maxVal = v}}; return minVal, maxVal}
func minElementFromArray(args ...int64) int64 { mn, _ := minMaxFromArray(args...); return mn }
func maxElementFromArray(args ...int64) int64 { _, mx := minMaxFromArray(args...); return mx }
func lcmCalculation(a, b int64) int64 {return a / gcdCalculation(a, b) * b}
func gcdCalculation(a, b int64) int64 {if (a == 0) {return b}; return gcdCalculation(b%a, a)}
func sortInt64Slice(a []int64) {sort.Slice(a, func(i, j int) bool { return a[i] < a[j] })}
func absoluteValue(x int64) int64 {if x < 0 {return -x}; return x}
func min(args ...int) int { mn, _ := minMaxFinder(args...); return mn }
func max(args ...int) int { _, mx := minMaxFinder(args...); return mx }
func minMaxFinder(args ...int) (int, int) { minVal, maxVal := int(math.MaxInt32), int(math.MinInt32); for _, v := range args { if v < minVal { minVal = v }; if v > maxVal { maxVal = v } }; return minVal, maxVal }

package main

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

const INFINITY = math.MaxInt32/2 - 1

func exec(stdin *Stdin, stdout *Stdout) {
	t := stdin.ReadInt()
	for i := 0; i < t; i++ {
		n := stdin.ReadInt()
		k := stdin.ReadInt()
		a := stdin.ReadIntSlice(n)

		d := map[int]int{}
		for _, v := range a {
			div := 0
			for v > 0 {
				if _, ok := d[div]; ok {
					d[div] += v % k
				} else {
					d[div] = v % k
				}
				v /= k
				div++
			}
		}

		ok := true
		for _, v := range d {
			if v > 1 {
				ok = false
				break
			}
		}

		if ok {
			stdout.Println("YES")
		} else {
			stdout.Println("NO")
		}
	}
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

func (s *Stdin) ReadIntSlice(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt()
	}
	return a
}

func (s *Stdin) ReadStringSlice(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = s.Read()
	}
	return a
}

func (s *Stdin) ReadFloat64Slice(n int) []float64 {
	a := make([]float64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadFloat64()
	}
	return a
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max(a int, b ...int) int {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

func Abs(x int) int {
	if x > 0 {
		return x
	} else {
		return x * -1
	}
}

func Pow(x, y int) int {
	z := 1
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y -= 1
		}
	}
	return z
}

func IsPrime(x int) bool {
	if x < 2 {
		return false
	}

	for i := 2; i*i <= x; i++ {
		if x%i == 0 {
			return false
		}
	}
	return true
}

func Gcd(x, y int) int {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func Lcm(x, y int) int {
	return x * y / Gcd(x, y)
}

func CeilDiv(x, y int) int {
	if x%y == 0 {
		return x / y
	} else {
		return x/y + 1
	}
}

func LCS(s, t string) string {
	n := len(s)
	m := len(t)
	dp := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = make([]int, m+1)
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if s[i-1] == t[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				dp[i][j] = Max(dp[i-1][j], dp[i][j-1])
			}
		}
	}

	x := n
	y := m
	u := make([]byte, dp[n][m])
	i := dp[n][m] - 1
	for x > 0 && y > 0 {
		if dp[x][y] == dp[x-1][y] {
			x--
		} else if dp[x][y] == dp[x][y-1] {
			y--
		} else {
			x--
			y--
			u[i] = s[x]
			i--
		}
	}

	return string(u)
}

// [0..n) から r個選んだ組合せを生成する。
// r < 0 の場合はすべての組合せを生成する。
func Combinations(n int, r int) [][]int {
	a := [][]int{}
	for i := uint(0); i < (1 << uint(n)); i++ {
		b := []int{}
		for j := uint(0); j < uint(n); j++ {
			if i&(uint(1)<<j) != 0 {
				b = append(b, int(j))
			}
		}

		if r < 0 || len(b) == r {
			a = append(a, b)
		}
	}
	return a
}

// [0..n)の順列を生成する。
func Permutations(n int) [][]int {
	type e struct {
		bit uint
		a   []int
	}

	q := []*e{}
	for i := 0; i < n; i++ {
		q = append(q, &e{bit: 1 << uint(i), a: []int{i}})
	}

	p := [][]int{}
	for x := 0; x < len(q); x++ {
		cur := q[x]
		if cur.bit == (1<<uint(n) - 1) {
			p = append(p, cur.a)
			continue
		}

		for i := 0; i < n; i++ {
			if cur.bit&(1<<uint(i)) != 0 {
				continue
			}

			m := len(cur.a) + 1
			b := make([]int, m)
			copy(b, cur.a)
			b[m-1] = i
			q = append(q, &e{bit: cur.bit | (1 << uint(i)), a: b})
		}
	}
	return p
}

func ReverseSlice(v interface{}) {
	if reflect.TypeOf(v).Kind() == reflect.Slice {
		slice := reflect.ValueOf(v)
		for i1, n := 0, slice.Len(); i1 < n/2; i1++ {
			i2 := n - i1 - 1
			v1 := reflect.ValueOf(slice.Index(i1).Interface())
			slice.Index(i1).Set(slice.Index(i2))
			slice.Index(i2).Set(v1)
		}
	}
}

func ReverseString(s string) string {
	t := []rune(s)
	ReverseSlice(t)
	return string(t)
}

func ToStringSlice(slice interface{}) []string {
	// 本来はerrを返却すべき。 利用する側(=自分)は引数がsliceであることを知っている。
	if reflect.TypeOf(slice).Kind() != reflect.Slice {
		panic(fmt.Sprintf("%v is not slice", slice))
	}

	src := reflect.ValueOf(slice)
	n := src.Len()
	dst := make([]string, n)
	for i := 0; i < n; i++ {
		dst[i] = fmt.Sprintf("%v", src.Index(i))
	}
	return dst
}

func CreateMatrix(x, y int) [][]int {
	matrix := make([][]int, x)
	for i := 0; i < x; i++ {
		matrix[i] = make([]int, y)
	}
	return matrix
}


There are $$$n$$$ points on a coordinate axis $$$OX$$$. The $$$i$$$-th point is located at the integer point $$$x_i$$$ and has a speed $$$v_i$$$. It is guaranteed that no two points occupy the same coordinate. All $$$n$$$ points move with the constant speed, the coordinate of the $$$i$$$-th point at the moment $$$t$$$ ($$$t$$$ can be non-integer) is calculated as $$$x_i + t \cdot v_i$$$.Consider two points $$$i$$$ and $$$j$$$. Let $$$d(i, j)$$$ be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points $$$i$$$ and $$$j$$$ coincide at some moment, the value $$$d(i, j)$$$ will be $$$0$$$.Your task is to calculate the value $$$\sum\limits_{1 \le i < j \le n}$$$ $$$d(i, j)$$$ (the sum of minimum distances over all pairs of points).

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^8$$$), where $$$x_i$$$ is the initial coordinate of the $$$i$$$-th point. It is guaranteed that all $$$x_i$$$ are distinct. The third line of the input contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-10^8 \le v_i \le 10^8$$$), where $$$v_i$$$ is the speed of the $$$i$$$-th point.

Print one integer — the value $$$\sum\limits_{1 \le i < j \le n}$$$ $$$d(i, j)$$$ (the sum of minimum distances over all pairs of points).

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1311F(_r io.Reader, out io.Writer) {
	in := bufio.NewReader(_r)
	type pair struct{ v, x int }

	var n int
	Fscan(in, &n)
	x := make([]int, n)
	ps := make([]pair, n)
	for i := range x {
		Fscan(in, &x[i])
	}
	for i := range ps {
		Fscan(in, &ps[i].v)
		ps[i].x = x[i]
	}
	sort.Ints(x)
	sort.Slice(ps, func(i, j int) bool { a, b := ps[i], ps[j]; return a.v < b.v || a.v == b.v && a.x < b.x })

	ans := int64(0)
	rank := map[int]int{}
	for i, v := range x {
		ans += int64(v) * int64(2*i+1-n)
		rank[v] = i
	}
	for i, p := range ps {
		ans -= int64(p.x) * int64(rank[p.x]-i)
	}
	Fprint(out, ans)
}

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

package main

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

var ans int64
var c [200005][2]int64
var n int

type node struct {
	x int
	v int
}

func lowbit(x int) int {
	return x & (-x)
}
func update(i, val int) {
	for i <= n {
		c[i][0] ++
		c[i][1] += int64(val)
		i += lowbit(i)
	}
}
func query(i, k int) int64 {
	var res int64 = 0
	for i > 0 {
		res += c[i][k]
		i -= lowbit(i)
	}
	return res
}
func unique_sort(slice []int) []int {
	res := make([]int, 0)
	mp := make(map[int]bool, len(slice))
	for _, e := range slice {
		if mp[e] == false {
			mp[e] = true
			res = append(res, e)
		}
	}
	sort.Slice(res, func(i, j int) bool {
		return res[i] < res[j]
	})
	return res
}
func lower_bound(st int, ed int, key int, num []int) int {
	left, right := 1, ed-1
	for ; left < right; {
		mid := (right + left) / 2
		if num[mid] >= key {
			right = mid
		} else {
			left = mid + 1
		}
	}
	if right == ed {
		return ed
	} else {
		return right
	}
}
func main() {
	n = ReadInt()
	a := make([]node, n+1)
	var b []int
	a[0].x = -1e9
	a[0].v = -1e9
	for i := 1; i <= n; i++ {
		a[i].x = ReadInt()
	}
	b = append(b, -1e9)
	for i := 1; i <= n; i++ {
		a[i].v = ReadInt()
		b = append(b, a[i].v)
	}
	sort.Slice(a, func(i, j int) bool {
		return a[i].x < a[j].x;
	})
	b = unique_sort(b)
	for i := 1; i <= n; i++ {
		tmp := lower_bound(1, len(b), a[i].v, b)
		ans += int64(a[i].x) * query(tmp, 0) - query(tmp, 1)
		update(tmp, a[i].x)
	}
	fmt.Println(ans)
}

////////////////////////////////////

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

var out chan string
var in *bufio.Scanner
var outWg *sync.WaitGroup

func ReadString() string {
	in.Scan()
	return in.Text()
}
func ReadStringSlice(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ReadString()
	}
	return s
}
func ReadInt() int {
	intStr := ReadString()
	i, _ := strconv.ParseInt(intStr, 10, 32)
	return int(i)
}
func ReadIntSlice(n int) []int {
	arr := make([]int, n)
	for i := 0; i < n; i++ {
		arr[i] = ReadInt()
	}
	return arr
}
func init() {
	//set input
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(2e+5))
	in.Split(bufio.ScanWords)

	//set output
	out = make(chan string, 16)
	outWg = &sync.WaitGroup{}
	outWg.Add(1)

	writer := bufio.NewWriterSize(os.Stdout, int(2e+5))
	go func(write *bufio.Writer) {
		defer outWg.Done()
		defer write.Flush()

		for line := range out {
			write.WriteString(line + "\n")
		}
	}(writer)
}


You are given a colored permutation $$$p_1, p_2, \dots, p_n$$$. The $$$i$$$-th element of the permutation has color $$$c_i$$$.Let's define an infinite path as infinite sequence $$$i, p[i], p[p[i]], p[p[p[i]]] \dots$$$ where all elements have same color ($$$c[i] = c[p[i]] = c[p[p[i]]] = \dots$$$).We can also define a multiplication of permutations $$$a$$$ and $$$b$$$ as permutation $$$c = a \times b$$$ where $$$c[i] = b[a[i]]$$$. Moreover, we can define a power $$$k$$$ of permutation $$$p$$$ as $$$p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$$$.Find the minimum $$$k > 0$$$ such that $$$p^k$$$ has at least one infinite path (i.e. there is a position $$$i$$$ in $$$p^k$$$ such that the sequence starting from $$$i$$$ is an infinite path).It can be proved that the answer always exists.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Next $$$3T$$$ lines contain test cases — one per three lines. The first line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of the permutation. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, $$$p_i \neq p_j$$$ for $$$i \neq j$$$) — the permutation $$$p$$$. The third line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le n$$$) — the colors of elements of the permutation. It is guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print minimum $$$k > 0$$$ such that $$$p^k$$$ has at least one infinite path.

NoteIn the first test case, $$$p^1 = p = [1, 3, 4, 2]$$$ and the sequence starting from $$$1$$$: $$$1, p[1] = 1, \dots$$$ is an infinite path.In the second test case, $$$p^5 = [1, 2, 3, 4, 5]$$$ and it obviously contains several infinite paths.In the third test case, $$$p^2 = [3, 6, 1, 8, 7, 2, 5, 4]$$$ and the sequence starting from $$$4$$$: $$$4, p^2[4]=8, p^2[8]=4, \dots$$$ is an infinite path since $$$c_4 = c_8 = 4$$$.

package main

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

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

	const mx int = 2e5
	factors := [mx + 1][]int{}
	for i := 1; i <= mx; i++ {
		for j := i; j <= mx; j += i {
			factors[j] = append(factors[j], i)
		}
	}

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		p := make([]int, n)
		for i := range p {
			Fscan(in, &p[i])
			p[i]--
		}
		colors := make([]int, n)
		for i := range colors {
			Fscan(in, &colors[i])
		}

		ans := n
		vis := make([]bool, n)
		for _, v := range p {
			if vis[v] {
				continue
			}
			cs := []int{}
			for ; !vis[v]; v = p[v] {
				vis[v] = true
				cs = append(cs, colors[v])
			}
		o:
			for _, f := range factors[len(cs)] {
				for i, c := range cs[:f] {
					same := true
					for j := i; j < len(cs); j += f {
						if cs[j] != c {
							same = false
							break
						}
					}
					if same {
						if f < ans {
							ans = f
						}
						break o
					}
				}
			}
		}
		Fprintln(out, ans)
	}
}

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

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

func Reader() func() int {
	var input []byte
	var idx int = 0
	scanner := bufio.NewReader(os.Stdin)
	return func() int {
		var ret, sign int = 0, 1
		for flag := true; flag; {
			for ; idx < len(input); idx++ {
				if (input[idx] >= '0' && input[idx] <= '9') || input[idx] == '-' {
					if input[idx] == '-' {
						sign = -1
						idx += 1
					}
					flag = false
					break
				}
			}
			if !flag {
				break
			}

			var err error
			input, _, err = scanner.ReadLine()
			idx = 0
			if err == io.EOF {
				return -1
			}
		}
		for ; idx < len(input) && input[idx]>='0' && input[idx]<='9'; idx++ {
			ret = ret * 10 + int(input[idx] -'0');
		}
		return ret * sign
	}
}

func GetPrimeList(n int) []int {
	var plist []int
	chk := make([]bool, n+1)
	for i := 2; i <= n; i++ { chk[i] = false }
	for i := 2; i <= n; i++ {
		if !chk[i] {
			plist = append(plist, i)
			for j := int64(i) * int64(i); j <= int64(n); j += int64(i) {
				chk[j] = true
			}
		}
	}
	return plist
}

type Factor struct {
	val int
	size int
}

func GetPrimeFactors(n int, primes *[]int) []Factor {
	var factors []Factor
	for i := 0; i < len(*primes) && int64((*primes)[i]) * int64((*primes)[i]) <= int64(n); i++ {
		if n % (*primes)[i] == 0 {
			size := 0
			for ; n % (*primes)[i] == 0; {
				n /= (*primes)[i]
				size++
			}
			factors = append(factors, Factor{(*primes)[i], size})
		}
	}
	if n != 1 {
		factors = append(factors, Factor{n, 1})
	}
	return factors
}

func GenDivisor(idx, val int, factors *[]Factor, divisor *[]int) {
	if idx == len(*factors) {
		*divisor = append(*divisor, val)
		return
	}

	for j := 0; j <= (*factors)[idx].size; j++ {
		GenDivisor(idx+1, val, factors, divisor)
		val *= (*factors)[idx].val
	}
}

func GetLeast(n int, primes *[]int, colors *[]int) int {
	ret := n
	factors := GetPrimeFactors(n, primes)
	var divisors []int
	GenDivisor(0, 1, &factors, &divisors)
	for _, div := range divisors {
		cs := make([]int, div)
		for i := range cs {
			cs[i] = 0
		}
		for i := 0; i < n; i++ {
			if cs[i%div] == 0 {
				cs[i%div] = (*colors)[i]
			} else if cs[i%div] != (*colors)[i] {
				cs[i%div] = -1
			}
		}
		for _, state := range cs {
			if state != -1 && ret > div {
				ret = div
			}
		}
	}
	return ret
}

func dfs(cur int, adj *[]int, vis *[]bool, colors, arr_col *[]int) int {
	if (*vis)[cur] {
		return 0
	}
	*arr_col = append(*arr_col, (*colors)[cur])
	(*vis)[cur] = true
	return dfs((*adj)[cur], adj, vis, colors, arr_col) + 1
}

func main() {
	//reader := Reader()
	var t, n int
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	Fscan(in, &t)
	primes := GetPrimeList(200000)
	for ; t > 0; t-- {
		Fscan(in, &n)
		adj := make([]int, n+1)
		colors := make([]int, n+1)
		vis := make([]bool, n+1)
		for i := range vis {
			vis[i] = false
		}
		for i := 1; i <= n; i++ {
			Fscan(in, &adj[i])
		}
		for i := 1; i <= n; i++ {
			Fscan(in, &colors[i])
		}

		ans := n
		for i := 1; i <= n; i++ {
			if !vis[i] {
				var cycle_colors []int
				l := dfs(i, &adj, &vis, &colors, &cycle_colors)
				tmp := GetLeast(l, &primes, &cycle_colors)
				if ans > tmp {
					ans = tmp
				}
			}
		}
		Fprintln(out, ans)
	}
}

package main

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

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

	const mx int = 2e5
	factors := [mx + 1][]int{}
	for i := 1; i <= mx; i++ {
		for j := i; j <= mx; j += i {
			factors[j] = append(factors[j], i)
		}
	}

	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		p := make([]int, n)
		for i := range p {
			Fscan(in, &p[i])
			p[i]--
		}
		colors := make([]int, n)
		for i := range colors {
			Fscan(in, &colors[i])
		}

		ans := n
		vis := make([]bool, n)
		for _, v := range p {
			if vis[v] {
				continue
			}
			cs := []int{}
			for ; !vis[v]; v = p[v] {
				vis[v] = true
				cs = append(cs, colors[v])
			}
			for _, f := range factors[len(cs)] {
				same := true
				for i := f; i < len(cs); i += f {
					if cs[i] != cs[0] {
						same = false
						break
					}
				}
				if same && f < ans {
					ans = f
				}
			}
		}
		Fprintln(out, ans)
	}
}

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

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

func Reader() func() int {
	var input []byte
	var idx int = 0
	scanner := bufio.NewReader(os.Stdin)
	return func() int {
		var ret, sign int = 0, 1
		for flag := true; flag; {
			for ; idx < len(input); idx++ {
				if (input[idx] >= '0' && input[idx] <= '9') || input[idx] == '-' {
					if input[idx] == '-' {
						sign = -1
						idx += 1
					}
					flag = false
					break
				}
			}
			if !flag {
				break
			}

			var err error
			input, _, err = scanner.ReadLine()
			idx = 0
			if err == io.EOF {
				return -1
			}
		}
		for ; idx < len(input) && input[idx]>='0' && input[idx]<='9'; idx++ {
			ret = ret * 10 + int(input[idx] -'0');
		}
		return ret * sign
	}
}

func GetPrimeList(n int) []int {
	var plist []int
	chk := make([]bool, n+1)
	for i := 2; i <= n; i++ { chk[i] = false }
	for i := 2; i <= n; i++ {
		if !chk[i] {
			plist = append(plist, i)
			for j := int64(i) * int64(i); j <= int64(n); j += int64(i) {
				chk[j] = true
			}
		}
	}
	return plist
}

type Factor struct {
	val int
	size int
}

func GetPrimeFactors(n int, primes *[]int) []Factor {
	var factors []Factor
	for i := 0; i < len(*primes) && int64((*primes)[i]) * int64((*primes)[i]) <= int64(n); i++ {
		if n % (*primes)[i] == 0 {
			size := 0
			for ; n % (*primes)[i] == 0; {
				n /= (*primes)[i]
				size++
			}
			factors = append(factors, Factor{(*primes)[i], size})
		}
	}
	if n != 1 {
		factors = append(factors, Factor{n, 1})
	}
	return factors
}

func GenDivisor(idx, val int, factors *[]Factor, divisor *[]int) {
	if idx == len(*factors) {
		*divisor = append(*divisor, val)
		return
	}

	for j := 0; j <= (*factors)[idx].size; j++ {
		GenDivisor(idx+1, val, factors, divisor)
		val *= (*factors)[idx].val
	}
}

func GetLeast(n int, primes *[]int, colors *[]int) int {
	ret := n
	factors := GetPrimeFactors(n, primes)
	var divisors []int
	GenDivisor(0, 1, &factors, &divisors)
	for _, div := range divisors {
		cs := make([]int, div)
		for i := range cs {
			cs[i] = 0
		}
		for i := 0; i < n; i++ {
			if cs[i%div] == 0 {
				cs[i%div] = (*colors)[i]
			} else if cs[i%div] != (*colors)[i] {
				cs[i%div] = -1
			}
		}
		for _, state := range cs {
			if state != -1 && ret > div {
				ret = div
			}
		}
	}
	return ret
}

func dfs(cur int, adj *[]int, vis *[]bool, colors, arr_col *[]int) int {
	if (*vis)[cur] {
		return 0
	}
	*arr_col = append(*arr_col, (*colors)[cur])
	(*vis)[cur] = true
	return dfs((*adj)[cur], adj, vis, colors, arr_col) + 1
}

func main() {
	//reader := Reader()
	var t, n int
	fmt.Scan(&t)
	primes := GetPrimeList(200000)
	for ; t > 0; t-- {
		fmt.Scan(&n)
		adj := make([]int, n+1)
		colors := make([]int, n+1)
		vis := make([]bool, n+1)
		for i := range vis {
			vis[i] = false
		}
		for i := 1; i <= n; i++ {
			fmt.Scan(&adj[i])
		}
		for i := 1; i <= n; i++ {
			fmt.Scan(&colors[i])
		}
		fmt.Println(n)
		fmt.Println(adj)
		fmt.Println(colors)

		ans := n
		for i := 1; i <= n; i++ {
			if !vis[i] {
				var cycle_colors []int
				l := dfs(i, &adj, &vis, &colors, &cycle_colors)
				fmt.Println(cycle_colors)
				tmp := GetLeast(l, &primes, &cycle_colors)
				if ans > tmp {
					ans = tmp
				}
			}
		}
		fmt.Println(ans)
	}
}

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

func Reader() func() int {
	var input []byte
	var idx int = 0
	scanner := bufio.NewReader(os.Stdin)
	return func() int {
		var ret, sign int = 0, 1
		for flag := true; flag; {
			for ; idx < len(input); idx++ {
				if (input[idx] >= '0' && input[idx] <= '9') || input[idx] == '-' {
					if input[idx] == '-' {
						sign = -1
						idx += 1
					}
					flag = false
					break
				}
			}
			if !flag {
				break
			}

			var err error
			input, _, err = scanner.ReadLine()
			idx = 0
			if err == io.EOF {
				return -1
			}
		}
		for ; idx < len(input) && input[idx]>='0' && input[idx]<='9'; idx++ {
			ret = ret * 10 + int(input[idx] -'0');
		}
		return ret * sign
	}
}

func GetPrimeList(n int) []int {
	var plist []int
	chk := make([]bool, n+1)
	for i := 2; i <= n; i++ { chk[i] = false }
	for i := 2; i <= n; i++ {
		if !chk[i] {
			plist = append(plist, i)
			for j := int64(i) * int64(i); j <= int64(n); j += int64(i) {
				chk[j] = true
			}
		}
	}
	return plist
}

type Factor struct {
	val int
	size int
}

func GetPrimeFactors(n int, primes *[]int) []Factor {
	var factors []Factor
	for i := 0; i < len(*primes) && int64((*primes)[i]) * int64((*primes)[i]) <= int64(n); i++ {
		if n % (*primes)[i] == 0 {
			size := 0
			for ; n % (*primes)[i] == 0; {
				n /= (*primes)[i]
				size++
			}
			factors = append(factors, Factor{(*primes)[i], size})
		}
	}
	return factors
}

func GenDivisor(idx, val int, factors *[]Factor, divisor *[]int) {
	if idx == len(*factors) {
		*divisor = append(*divisor, val)
		return
	}

	for j := 0; j <= (*factors)[idx].size; j++ {
		GenDivisor(idx+1, val, factors, divisor)
		val *= (*factors)[idx].val
	}
}

func GetLeast(n int, primes *[]int, colors *[]int) int {
	ret := n
	factors := GetPrimeFactors(n, primes)
	var divisors []int
	GenDivisor(0, 1, &factors, &divisors)
	for _, div := range divisors {
		cs := make([]int, div)
		for i := range cs {
			cs[i] = 0
		}
		for i := 0; i < n; i++ {
			if cs[i%div] == 0 {
				cs[i%div] = (*colors)[i]
			} else if cs[i%div] != (*colors)[i] {
				cs[i%div] = -1
			}
		}
		for _, state := range cs {
			if state != -1 && ret > div {
				ret = div
			}
		}
	}
	return ret
}

func dfs(cur int, adj *[]int, vis *[]bool, colors, arr_col *[]int) int {
	if (*vis)[cur] {
		return 0
	}
	*arr_col = append(*arr_col, (*colors)[cur])
	(*vis)[cur] = true
	return dfs((*adj)[cur], adj, vis, colors, arr_col) + 1
}

func main() {
	reader := Reader()
	t := reader()
	primes := GetPrimeList(200000)
	for ; t > 0; t-- {
		n := reader()
		adj := make([]int, n+1)
		colors := make([]int, n+1)
		vis := make([]bool, n+1)
		for i := range vis {
			vis[i] = false
		}
		for i := 1; i <= n; i++ {
			adj[i] = reader()
		}
		for i := 1; i <= n; i++ {
			colors[i] = reader()
		}

		ans := n
		for i := 1; i <= n; i++ {
			if !vis[i] {
				var cycle_colors []int
				l := dfs(i, &adj, &vis, &colors, &cycle_colors)
				tmp := GetLeast(l, &primes, &cycle_colors)
				if ans > tmp {
					ans = tmp
				}
			}
		}
		fmt.Println(ans)
	}
}


Vasya has a string $$$s$$$ of length $$$n$$$ consisting only of digits 0 and 1. Also he has an array $$$a$$$ of length $$$n$$$. Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty). For example, if he erases substring 111 from string 111110 he will get the string 110. Vasya gets $$$a_x$$$ points for erasing substring of length $$$x$$$.Vasya wants to maximize his total points, so help him with this!

The first line contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of string $$$s$$$. The second line contains string $$$s$$$, consisting only of digits 0 and 1. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the number of points for erasing the substring of length $$$i$$$.

Print one integer — the maximum total points Vasya can get.

NoteIn the first example the optimal sequence of erasings is: 1101001 $$$\rightarrow$$$ 111001 $$$\rightarrow$$$ 11101 $$$\rightarrow$$$ 1111 $$$\rightarrow$$$ $$$\varnothing$$$.In the second example the optimal sequence of erasings is: 10101 $$$\rightarrow$$$ 1001 $$$\rightarrow$$$ 11 $$$\rightarrow$$$ $$$\varnothing$$$.

package main

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

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

type dpcall struct {
	c   byte
	l   int
	r   int
	cnt int
}

var dp map[dpcall]*int64

type anscall struct {
	l int
	r int
}

var ans map[anscall]*int64

var s []byte
var costs []int

func main() {
	//STDOUT MUST BE FLUSHED MANUALLY
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	s = make([]byte, n)
	var tmp string
	scanf("%s\n", &tmp)
	for i, c := range tmp {
		s[i] = byte(c) - byte('0')
	}

	costs = make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &costs[i])
	}
	// printf("scanned: %v\n", costs)

	// SOLUTION
	// init memoization
	ans = make(map[anscall]*int64)
	dp = make(map[dpcall]*int64)
	printf("%v\n", calcAns(0, n))
}

func calcAns(l, r int) int64 {
	if l >= r {
		return 0
	}
	cal, ok := ans[anscall{l, r}]
	if ok {
		return *cal
	}
	res := int64(0)
	ans[anscall{l, r}] = &res

	for cnt := 1; cnt <= r - l; cnt++ {
		res = max(res, calcDp(0, l, r, cnt) + int64(costs[cnt - 1]))
		res = max(res, calcDp(1, l, r, cnt) + int64(costs[cnt - 1]))
		// printf("res for l(%d), r(%d): %d\n", l, r, res)
	}
	// printf("calcAns(%+v) : %d (cached: %d)\n", anscall{l, r}, res, *ans[anscall{l, r}])
	return res
}

func calcDp(c byte, l, r, cnt int) int64 {
	if cnt == 0 {
		return calcAns(l, r)
	}
	val, ok := dp[dpcall{c, l, r, cnt}]
	if ok {
		return *val
	}
	res := -int64(math.MaxInt64)
	dp[dpcall{c, l, r, cnt}] = &res

	for i := l; i < r; i++ {
		if (c == s[i]) {
			res = max(res, calcAns(l, i) + calcDp(c, i + 1, r, cnt - 1))
		}
	}
	// printf("calcDp(%+v) : %d (cached: %d)\n", dpcall{c, l, r, cnt}, res, *dp[dpcall{c, l, r, cnt}])
	return res
}

func max(i, f int64) int64 {
	if i > f {
		return i
	}
	return f
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"math"
	"runtime/debug"
)

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

type dpcall struct {
	c   byte
	l   int
	r   int
	cnt int
}

var dp map[dpcall]*int64

type anscall struct {
	l int
	r int
}

var ans map[anscall]*int64

var s []byte
var costs []int

func main() {
	//STDOUT MUST BE FLUSHED MANUALLY
	debug.SetGCPercent(-1)
	defer writer.Flush()

	var n int
	scanf("%d\n", &n)
	s = make([]byte, n)
	var tmp string
	scanf("%s\n", &tmp)
	for i, c := range tmp {
		s[i] = byte(c) - byte('0')
	}

	costs = make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &costs[i])
	}
	// printf("scanned: %v\n", costs)

	// SOLUTION
	// init memoization
	ans = make(map[anscall]*int64)
	dp = make(map[dpcall]*int64)
	printf("%v\n", calcAns(0, n))
}

func calcAns(l, r int) int64 {
	if l >= r {
		return 0
	}
	cal, ok := ans[anscall{l, r}]
	if ok {
		return *cal
	}
	res := int64(0)
	ans[anscall{l, r}] = &res

	for cnt := 1; cnt <= r - l; cnt++ {
		res = max(res, calcDp(0, l, r, cnt) + int64(costs[cnt - 1]))
		res = max(res, calcDp(1, l, r, cnt) + int64(costs[cnt - 1]))
		// printf("res for l(%d), r(%d): %d\n", l, r, res)
	}
	// printf("calcAns(%+v) : %d (cached: %d)\n", anscall{l, r}, res, *ans[anscall{l, r}])
	return res
}

func calcDp(c byte, l, r, cnt int) int64 {
	if cnt == 0 {
		return calcAns(l, r)
	}
	val, ok := dp[dpcall{c, l, r, cnt}]
	if ok {
		return *val
	}
	res := -int64(math.MaxInt64)
	dp[dpcall{c, l, r, cnt}] = &res

	for i := l; i < r; i++ {
		if (c == s[i]) {
			res = max(res, calcAns(l, i) + calcDp(c, i + 1, r, cnt - 1))
		}
	}
	// printf("calcDp(%+v) : %d (cached: %d)\n", dpcall{c, l, r, cnt}, res, *dp[dpcall{c, l, r, cnt}])
	return res
}

func max(i, f int64) int64 {
	if i > f {
		return i
	}
	return f
}


Recently, Vlad has been carried away by spanning trees, so his friends, without hesitation, gave him a connected weighted undirected graph of $$$n$$$ vertices and $$$m$$$ edges for his birthday.Vlad defined the ority of a spanning tree as the bitwise OR of all its weights, and now he is interested in what is the minimum possible ority that can be achieved by choosing a certain spanning tree. A spanning tree is a connected subgraph of a given graph that does not contain cycles.In other words, you want to keep $$$n-1$$$ edges so that the graph remains connected and the bitwise OR weights of the edges are as small as possible. You have to find the minimum bitwise OR itself.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. An empty line is written in front of each test case. This is followed by two numbers $$$n$$$ and $$$m$$$ ($$$3 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and edges of the graph, respectively. The next $$$m$$$ lines contain the description of the edges. Line $$$i$$$ contains three numbers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$1 \le w_i \le 10^9$$$, $$$v_i \neq u_i$$$) — the vertices that the edge connects and its weight. It is guaranteed that the sum $$$m$$$ and the sum $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ and each test case contains a connected graph.

Print $$$t$$$ lines, each of which contains the answer to the corresponding set of input data — the minimum possible spanning tree ority.

Note  Graph from the first test case.   Ority of this tree equals to 2 or 2 = 2 and it's minimal.   Without excluding edge with weight $$$1$$$ ority is 1 or 2 = 3.

package main

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

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 print(a ...interface{}) { fmt.Println(a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f + "\n", a...) }

func main() {
	defer writer.Flush()

	var testcases int
	scanf("%d", &testcases)
	for i := 0; i < testcases; i++ {
		scanf("%s")
		var vertices, edges int
		scanf("%d %d", &vertices, &edges)
		graph := make([][][]int, vertices + 1)
		for i := range(graph) {
			graph[i] = make([][]int, 0)
		}
		for j := 0; j < edges; j++ {
			var u, v, w int
			scanf("%d %d %d", &u, &v, &w)
			graph[u] = append(graph[u], []int{v, w})
			graph[v] = append(graph[v], []int{u, w})
		}
		print(solve(graph, vertices))
	}
}

func solve(graph [][][]int, vertices int) int {
	result := (1<<30) - 1
	notInAns := 0
	for i := 30; i >= 0; i-- {
		stack := []int{1}
		seen := make([]int, vertices + 1)
		seenVertices := 0
		notInAns |= (1<<i)
		for len(stack) > 0 {
			current := stack[len(stack) - 1]
			stack = stack[:len(stack) - 1]
			for _, data := range graph[current] {
				next, weight := data[0], data[1]
				if seen[next] == 1 || (weight & notInAns != 0) {
					continue
				}
				stack = append(stack, next)
				seen[next] = 1
				seenVertices += 1
			}
		}
		notInAns &= ^(1<<i)
		if seenVertices == vertices {
			notInAns |= (1<<i)
			result &= ^(1<<i)
		}
	}
	return result
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		readString(reader)
		n, m := readTwoNums(reader)
		E := make([][]int, m)
		for i := 0; i < m; i++ {
			E[i] = readNNums(reader, 3)
		}
		res := solve(n, m, E)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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(n int, m int, E [][]int) int {
	g := NewGraph(n, 2*m)

	for _, e := range E {
		u, v, w := e[0], e[1], e[2]
		u--
		v--
		g.AddEdge(u, v, w)
		g.AddEdge(v, u, w)
	}

	vis := make([]int, n)

	var dfs func(u int, mask int)

	dfs = func(u int, mask int) {
		vis[u] = mask
		for i := g.nodes[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			w := g.val[i]
			if (mask&w) != w || vis[v] == mask {
				continue
			}
			dfs(v, mask)
		}
	}

	mask := (1 << 30) - 1

	for d := 29; d >= 0; d-- {
		// if we turn off d, whether connect of not
		tmp := mask ^ (1 << d)

		dfs(0, tmp)

		ok := true

		for i := 0; i < n; i++ {
			if vis[i] != tmp {
				ok = false
				break
			}
		}

		if ok {
			mask = tmp
		}
	}

	return mask
}

func solve1(n int, m int, E [][]int) int {
	g := NewGraph(n, 2*m)

	for _, e := range E {
		u, v, w := e[0], e[1], e[2]
		u--
		v--
		g.AddEdge(u, v, w)
		g.AddEdge(v, u, w)
	}

	uf := NewUF(n)

	var dfs func(p int, u int, mask int)

	dfs = func(p int, u int, mask int) {

		for i := g.nodes[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			w := g.val[i]
			if p == v || (mask&w) != w || uf.Find(v) == uf.Find(u) {
				continue
			}
			uf.Union(u, v)
			dfs(u, v, mask)
		}
	}

	mask := (1 << 30) - 1

	for d := 29; d >= 0; d-- {
		// if we turn off d, whether connect of not
		tmp := mask ^ (1 << d)

		uf.Reset()
		dfs(-1, 0, tmp)

		if uf.Size() == 1 {
			// good
			mask = tmp
		}
	}

	return mask
}

type UF struct {
	arr  []int
	cnt  []int
	size int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	cnt := make([]int, n)

	for i := 0; i < n; i++ {
		arr[i] = i
		cnt[i]++
	}
	return &UF{arr, cnt, n}
}

func (this *UF) Reset() {
	for i := 0; i < len(this.arr); i++ {
		this.arr[i] = i
		this.cnt[i] = 1
	}
	this.size = len(this.arr)
}

func (this *UF) Find(x int) int {
	if this.arr[x] != x {
		this.arr[x] = this.Find(this.arr[x])
	}
	return this.arr[x]
}

func (this *UF) Union(a, b int) bool {
	pa := this.Find(a)
	pb := this.Find(b)

	if pa == pb {
		return false
	}
	if this.cnt[pa] < this.cnt[pb] {
		pa, pb = pb, pa
	}
	this.cnt[pa] += this.cnt[pb]
	this.arr[pb] = pa
	this.size--
	return true
}

func (this *UF) Size() int {
	return this.size
}

type Graph struct {
	nodes []int
	next  []int
	to    []int
	val   []int
	cur   int
}

func NewGraph(n int, e int) *Graph {
	nodes := make([]int, n)
	next := make([]int, e+3)
	to := make([]int, e+3)
	val := make([]int, e+3)
	var cur int
	return &Graph{nodes, next, to, val, cur}
}

func (g *Graph) AddEdge(u, v, w int) {
	g.cur++
	g.next[g.cur] = g.nodes[u]
	g.nodes[u] = g.cur
	g.to[g.cur] = v
	g.val[g.cur] = w
}

package main

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

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

	var buf bytes.Buffer

	tc := readNum(reader)

	for tc > 0 {
		tc--
		readString(reader)
		n, m := readTwoNums(reader)
		E := make([][]int, m)
		for i := 0; i < m; i++ {
			E[i] = readNNums(reader, 3)
		}
		res := solve(n, m, E)
		buf.WriteString(fmt.Sprintf("%d\n", res))
	}

	fmt.Print(buf.String())
}

func readString(reader *bufio.Reader) string {
	s, _ := reader.ReadString('\n')
	for i := 0; i < len(s); i++ {
		if s[i] == '\n' {
			return s[:i]
		}
	}
	return s
}

func normalize(s string) string {

	for i := len(s); i > 0; i-- {
		if s[i-1] >= 'a' && s[i-1] <= 'z' {
			return s[:i]
		}
	}
	return ""
}

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(n int, m int, E [][]int) int {
	g := NewGraph(n, 2*m)

	for _, e := range E {
		u, v, w := e[0], e[1], e[2]
		u--
		v--
		g.AddEdge(u, v, w)
		g.AddEdge(v, u, w)
	}

	uf := NewUF(n)

	var dfs func(p int, u int, mask int)

	dfs = func(p int, u int, mask int) {

		for i := g.nodes[u]; i > 0; i = g.next[i] {
			v := g.to[i]
			w := g.val[i]
			if p == v || (mask&w) != w || uf.Find(v) == uf.Find(u) {
				continue
			}
			uf.Union(u, v)
			dfs(u, v, mask)
		}
	}

	mask := (1 << 30) - 1

	for d := 29; d >= 0; d-- {
		// if we turn off d, whether connect of not
		tmp := mask ^ (1 << d)

		uf.Reset()
		dfs(-1, 0, tmp)

		if uf.Size() == 1 {
			// good
			mask = tmp
		}
	}

	return mask
}

type UF struct {
	arr  []int
	cnt  []int
	size int
}

func NewUF(n int) *UF {
	arr := make([]int, n)
	cnt := make([]int, n)

	for i := 0; i < n; i++ {
		arr[i] = i
		cnt[i]++
	}
	return &UF{arr, cnt, n}
}

func (this *UF) Reset() {
	for i := 0; i < len(this.arr); i++ {
		this.arr[i] = i
		this.cnt[i] = 1
	}
	this.size = len(this.arr)
}

func (this *UF) Find(x int) int {
	if this.arr[x] != x {
		this.arr[x] = this.Find(this.arr[x])
	}
	return this.arr[x]
}

func (this *UF) Union(a, b int) bool {
	pa := this.Find(a)
	pb := this.Find(b)

	if pa == pb {
		return false
	}
	if this.cnt[pa] < this.cnt[pb] {
		pa, pb = pb, pa
	}
	this.cnt[pa] += this.cnt[pb]
	this.arr[pb] = pa
	this.size--
	return true
}

func (this *UF) Size() int {
	return this.size
}

type Graph struct {
	nodes []int
	next  []int
	to    []int
	val   []int
	cur   int
}

func NewGraph(n int, e int) *Graph {
	nodes := make([]int, n)
	next := make([]int, e+3)
	to := make([]int, e+3)
	val := make([]int, e+3)
	var cur int
	return &Graph{nodes, next, to, val, cur}
}

func (g *Graph) AddEdge(u, v, w int) {
	g.cur++
	g.next[g.cur] = g.nodes[u]
	g.nodes[u] = g.cur
	g.to[g.cur] = v
	g.val[g.cur] = w
}

package main

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

type bufReader struct {
	r   *bufio.Reader
	buf []byte
	i   int
}

var reader = &bufReader{
	bufio.NewReader(os.Stdin),
	make([]byte, 0),
	0,
}

func (r *bufReader) readLine() {
	if r.i < len(r.buf) {
		return
	}
	r.buf = make([]byte, 0)
	r.i = 0
	for {
		line, isPrefix, err := r.r.ReadLine()
		if err != nil {
			panic(err)
		}
		r.buf = append(r.buf, line...)
		if !isPrefix {
			break
		}
	}
}

func (r *bufReader) next() string {
	r.readLine()
	from := r.i
	for ; r.i < len(r.buf); r.i++ {
		if r.buf[r.i] == ' ' {
			break
		}
	}
	s := string(r.buf[from:r.i])
	r.i++
	return s
}

func (r *bufReader) nextLine() string {
	r.readLine()
	s := string(r.buf[r.i:])
	r.i = len(r.buf)
	return s
}

var writer = bufio.NewWriter(os.Stdout)

func next() string {
	return reader.next()
}

func nextInt64() int64 {
	i, err := strconv.ParseInt(reader.next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func nextInt() int {
	return int(nextInt64())
}

func nextLine() string {
	return reader.nextLine()
}

func out(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func max64(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

func max(x, y int) int {
	return int(max64(int64(x), int64(y)))
}

func min64(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func min(x, y int) int {
	return int(min64(int64(x), int64(y)))
}

func abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func abs(x int) int {
	return int(abs64(int64(x)))
}

func joinInt64s(a []int64, sep string) string {
	b := make([]string, len(a))
	for i, v := range a {
		b[i] = strconv.FormatInt(v, 10)
	}
	return strings.Join(b, sep)
}

func joinInts(a []int, sep string) string {
	b := make([]string, len(a))
	for i, v := range a {
		b[i] = strconv.Itoa(v)
	}
	return strings.Join(b, sep)
}

func divUp64(x, y int64) int64 {
	return (x + y - 1) / y
}

func divUp(x, y int) int {
	return int(divUp64(int64(x), int64(y)))
}

func gcd64(x, y int64) int64 {
	if x < y {
		x, y = y, x
	}
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func gcd(x, y int) int {
	return int(gcd64(int64(x), int64(y)))
}

func lcm64(x, y int64) int64 {
	return x * y / gcd64(x, y)
}

func lcm(x, y int) int {
	return int(lcm64(int64(x), int64(y)))
}

func pow64(x, y int64) int64 {
	return int64(math.Pow(float64(x), float64(y)))
}

func pow(x, y int) int {
	return int(pow64(int64(x), int64(y)))
}

type UnionFind struct {
	root []int
	size []int
}

// New returns an initialized list of size
func New(size int) *UnionFind {
	return new(UnionFind).init(size)
}

// Constructor initializes root and size arrays
func (uf *UnionFind) init(size int) *UnionFind {
	uf = new(UnionFind)
	uf.root = make([]int, size)
	uf.size = make([]int, size)

	for i := 0; i < size; i++ {
		uf.root[i] = i
		uf.size[i] = 1
	}

	return uf
}

// Union connects p and q by finding their roots and comparing their respective
// size arrays to keep the tree flat
func (uf *UnionFind) Union(p int, q int) {
	qRoot := uf.Root(q)
	pRoot := uf.Root(p)

	if uf.size[qRoot] < uf.size[pRoot] {
		uf.root[qRoot] = uf.root[pRoot]
		uf.size[pRoot] += uf.size[qRoot]
	} else {
		uf.root[pRoot] = uf.root[qRoot]
		uf.size[qRoot] += uf.size[pRoot]
	}
}

// Root or Find traverses each parent element while compressing the
// levels to find the root element of p
// If we attempt to access an element outside the array it returns -1
func (uf *UnionFind) Root(p int) int {
	if p > len(uf.root)-1 {
		return -1
	}

	for uf.root[p] != p {
		uf.root[p] = uf.root[uf.root[p]]
		p = uf.root[p]
	}

	return p
}

// Root or Find
func (uf *UnionFind) Find(p int) int {
	return uf.Root(p)
}

// Check if items p,q are connected
func (uf *UnionFind) Connected(p int, q int) bool {
	return uf.Root(p) == uf.Root(q)
}

func main() {
	solveTC()
	writer.Flush()
}

func solveTC() {
	t := nextInt()
	for tc := 0; tc < t; tc++ {
		solve()
	}
}

func hasSolution(edges [][]int, allowed []bool, n int) bool {
	unionFind := New(n)
	for i := 0; i < len(allowed); i++ {
		if allowed[i] {
			unionFind.Union(edges[i][0], edges[i][1])
		}
	}
	c := unionFind.Find(0)
	for i := 1; i < n; i++ {
		if unionFind.Find(i) != c {
			return false
		}
	}
	return true
}

func hasSolutionWith(currentOr int64, currentIndex int, edges [][]int, n int, m int) bool {
	allowed := []bool{}
	for i := 0; i < m; i++ {
		currentWeight := int64(edges[i][2])
		toRemove := int64(1)
		if currentIndex > 0 {
			toRemove <<= currentIndex
		}
		toRemove -= 1
		currentWeight = currentWeight & (^toRemove)
		isOk := ((currentOr ^ currentWeight) | currentOr) == currentOr
		if !isOk {
			allowed = append(allowed, false)
		} else {
			allowed = append(allowed, true)
		}
	}
	return hasSolution(edges, allowed, n)
}

func solve() {
	nextLine()
	n := nextInt()
	m := nextInt()
	edges := [][]int{}
	for i := 0; i < m; i++ {
		edges = append(edges, []int{})
		edges[i] = []int{nextInt() - 1, nextInt() - 1, nextInt()}
	}
	currentOr := int64(0)
	for currentIndex := 31; currentIndex >= 0; currentIndex-- {
		if !hasSolutionWith(currentOr, currentIndex, edges, n, m) {
			currentOr |= int64(1) << currentIndex
		}
	}
	out(currentOr)
}

package main

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

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

	var T, n, m, v, w, wt int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		type nb struct{ to, wt int }
		g := make([][]nb, n)
		for ; m > 0; m-- {
			Fscan(in, &v, &w, &wt)
			v--
			w--
			g[v] = append(g[v], nb{w, wt})
			g[w] = append(g[w], nb{v, wt})
		}
		vis := make([]int8, n)
		ans := 0
		for i, m := int8(29), 0; i >= 0; i-- {
			c := n
			m |= 1 << i
			var f func(v int)
			f = func(v int) {
				vis[v] = i + 1
				c--
				for _, e := range g[v] {
					if e.wt&m == 0 && vis[e.to] != i+1 {
						f(e.to)
					}
				}
			}
			f(0)
			if c > 0 {
				ans |= 1 << i
				m &^= 1 << i
			}
		}
		Fprintln(out, ans)
	}
}

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

package main

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

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

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

func redirectInputToFile(r *bufio.Reader, fp string) {
	f, err := os.Open(fp)
	if err != nil {
		panic(err)
	}
	r.Reset(f)
}

func main() {
	defer writer.Flush()
// 	redirectInputToFile(reader, "input.txt")

	T := 1
	scan(&T)
	for t := 0; t < T; t++ {
		solve()
	}
}

func solve() {
	var n, m int
	scan(&n, &m)
	var edges = make([]struct{ v1, v2, w int }, m)
	for i := range edges {
		scan(&edges[i].v1, &edges[i].v2, &edges[i].w)
		edges[i].v1--
		edges[i].v2--
	}
	var (
		dsu           = NewDSU(n)
		edgesIdxs, ok = make([]int, m), false
		ans           = 0
	)
	for i := range edgesIdxs {
		edgesIdxs[i] = i
	}
	for bit := 29; bit >= 0; bit-- {
		dsu.Clear()
		if edgesIdxs, ok = check(edges, edgesIdxs, dsu, bit); !ok {
			ans |= 1 << bit
		}
	}
	printf("%v\n", ans)
}

func check(edges []struct{ v1, v2, w int }, edgesIdxs []int, dsu *DSU, bit int) ([]int, bool) {
	edgesIdxsWithZeroedBit := make([]int, 0)
	for _, i := range edgesIdxs {
		if (edges[i].w>>bit)&1 == 1 {
			continue
		}
		edgesIdxsWithZeroedBit = append(edgesIdxsWithZeroedBit, i)
	}
	for _, i := range edgesIdxsWithZeroedBit {
		dsu.Unite(edges[i].v1, edges[i].v2)
	}
	prev := -1
	for i := 0; i < len(dsu.parent); i++ {
		if root := dsu.Root(i); prev != -1 && root != prev {
			return edgesIdxs, false
		} else {
			prev = root
		}
	}
	return edgesIdxsWithZeroedBit, true
}

type DSU struct {
	parent, size []int
}

func NewDSU(n int) *DSU {
	d := &DSU{
		parent: make([]int, n),
		size:   make([]int, n),
	}
	for i := 0; i < n; i++ {
		d.parent[i] = i
		d.size[i] = 1
	}
	return d
}

func (d *DSU) AddSet() {
	n := len(d.parent)
	d.parent = append(d.parent, n)
	d.size = append(d.size, 1)
}

func (d *DSU) Root(i int) int {
	if d.parent[i] == i {
		return i
	}
	d.parent[i] = d.Root(d.parent[i])
	return d.parent[i]
}

func (d *DSU) Unite(i, j int) {
	ri, rj := d.Root(i), d.Root(j)
	if ri == rj {
		return
	}
	if d.size[ri] < d.size[rj] {
		ri, rj = rj, ri
	}
	d.parent[rj] = ri
	d.size[ri] += d.size[rj]
}

func (d *DSU) Clear() {
	for i := range d.parent {
		d.parent[i] = i
	}
	for i := range d.size {
		d.size[i] = 1
	}
}


Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day — exactly $$$2$$$ problems, during the third day — exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of contests. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) — the number of problems in the $$$i$$$-th contest.

Print one integer — the maximum number of days Polycarp can train if he chooses the contests optimally.

package main

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

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

func main() {
	defer writer.Flush()
	var d int
	scanf("%d\n", &d)
	n := make([]int, d)
	for i := range n {
		scanf("%d", &n[i])
	}
	sort.Ints(n)
	sum, cur := 0, 1
	for i := range n {
		if n[i] >= cur {
			sum++
			cur++
		}
	}
	printf("%d", sum)
}