← Home
package main

import (
	"io"
	"os"
	"sort"
	"strconv"
)

type Pair struct {
	V int
	L int
}

type Candidate struct {
	V int
	I int64
}

func main() {
	input, _ := io.ReadAll(os.Stdin)
	pos := 0

	nextInt := func() int {
		for pos < len(input) && input[pos] <= ' ' {
			pos++
		}
		if pos >= len(input) {
			return 0
		}
		res := 0
		for pos < len(input) && input[pos] > ' ' {
			res = res*10 + int(input[pos]-'0')
			pos++
		}
		return res
	}

	if pos >= len(input) {
		return
	}
	t := nextInt()
	if t == 0 {
		return
	}

	var out []byte
	var candidates []Candidate
	var sufMin []int64

	for tc := 0; tc < t; tc++ {
		n := nextInt()
		q := nextInt()

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

		candidates = candidates[:0]
		var list []Pair

		for j := 2*n - 1; j >= 0; j-- {
			nextList := make([]Pair, 0, len(list)+1)
			val := a[j%n]
			nextList = append(nextList, Pair{val, 1})

			for _, p := range list {
				newV := p.V | val
				newL := p.L + 1
				if newL > n {
					continue
				}
				if newV == nextList[len(nextList)-1].V {
					continue
				}
				nextList = append(nextList, Pair{newV, newL})
			}
			list = nextList

			if j < n {
				for _, p := range list {
					candidates = append(candidates, Candidate{
						V: p.V,
						I: int64(p.L-1)*int64(n) + int64(j) + 1,
					})
				}
			}
		}

		totalOR := list[len(list)-1].V

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

		m := len(candidates)
		if len(sufMin) < m {
			sufMin = make([]int64, m)
		}
		sufMin = sufMin[:m]

		sufMin[m-1] = candidates[m-1].I
		for i := m - 2; i >= 0; i-- {
			if candidates[i].I < sufMin[i+1] {
				sufMin[i] = candidates[i].I
			} else {
				sufMin[i] = sufMin[i+1]
			}
		}

		for i := 0; i < q; i++ {
			v := nextInt()

			if v >= totalOR {
				out = append(out, '-', '1', ' ')
			} else {
				idx := sort.Search(m, func(k int) bool {
					return candidates[k].V > v
				})
				out = strconv.AppendInt(out, sufMin[idx], 10)
				out = append(out, ' ')
			}
		}
		out = append(out, '\n')
	}
	os.Stdout.Write(out)
}