Monocarp plays a computer game (yet again!). This game has a unique trading mechanics.To trade with a character, Monocarp has to choose one of the items he possesses and trade it for some item the other character possesses. Each item has an integer price. If Monocarp's chosen item has price $$$x$$$, then he can trade it for any item (exactly one item) with price not greater than $$$x+k$$$.Monocarp initially has $$$n$$$ items, the price of the $$$i$$$-th item he has is $$$a_i$$$. The character Monocarp is trading with has $$$m$$$ items, the price of the $$$i$$$-th item they have is $$$b_i$$$. Monocarp can trade with this character as many times as he wants (possibly even zero times), each time exchanging one of his items with one of the other character's items according to the aforementioned constraints. Note that if Monocarp gets some item during an exchange, he can trade it for another item (since now the item belongs to him), and vice versa: if Monocarp trades one of his items for another item, he can get his item back by trading something for it.You have to answer $$$q$$$ queries. Each query consists of one integer, which is the value of $$$k$$$, and asks you to calculate the maximum possible total cost of items Monocarp can have after some sequence of trades, assuming that he can trade an item of cost $$$x$$$ for an item of cost not greater than $$$x+k$$$ during each trade. Note that the queries are independent: the trades do not actually occur, Monocarp only wants to calculate the maximum total cost he can get.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the prices of the items Monocarp has. The third line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 10^9$$$) — the prices of the items the other character has. The fourth line contains $$$q$$$ integers, where the $$$i$$$-th integer is the value of $$$k$$$ for the $$$i$$$-th query ($$$0 \le k \le 10^9$$$).

For each query, print one integer — the maximum possible total cost of items Monocarp can have after some sequence of trades, given the value of $$$k$$$ from the query.

package main

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

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, q int
	scan(&n, &m, &q)
	goods := make([][2]int, 0, n+m)
	for x, i := 0, 0; i < n; i++ {
		scan(&x)
		goods = append(goods, [2]int{x, 1})
	}
	for x, i := 0, 0; i < m; i++ {
		scan(&x)
		goods = append(goods, [2]int{x, 0})
	}
	queries := make([][2]int, q)
	for i := range queries {
		scan(&queries[i][0])
		queries[i][1] = i
	}

	sort.Slice(goods, func(i, j int) bool {
		if goods[i][0] == goods[j][0] {
			return goods[i][1] < goods[j][1]
		}
		return goods[i][0] < goods[j][0]
	})
	sort.Slice(queries, func(i, j int) bool {
		return queries[i][0] < queries[j][0]
	})

	edges := make([][2]int, len(goods)-1)
	for i := range edges {
		edges[i][0] = i
		edges[i][1] = i + 1
	}
	sort.Slice(edges, func(i, j int) bool {
		li, ri := goods[edges[i][0]][0], goods[edges[i][1]][0]
		lj, rj := goods[edges[j][0]][0], goods[edges[j][1]][0]
		return ri-li < rj-lj
	})

	prefcnt := make([]int, len(goods))
	prefcnt[0] = goods[0][1]
	for i := 1; i < len(goods); i++ {
		prefcnt[i] = prefcnt[i-1] + goods[i][1]
	}

	prefsum := make([]int64, len(goods))
	prefsum[0] = int64(goods[0][0])
	for i := 1; i < len(goods); i++ {
		prefsum[i] = prefsum[i-1] + int64(goods[i][0])
	}

	currAns := int64(0)
	for i := range goods {
		if goods[i][1] == 1 {
			currAns += int64(goods[i][0])
		}
	}

	dsu := NewDSU(len(goods))

	ans := make([]int64, q)
	for _, query := range queries {
		k, idx := query[0], query[1]
		for len(edges) > 0 {
			l, r := edges[0][0], edges[0][1]
			if goods[r][0]-goods[l][0] > k {
				break
			}
			edges = edges[1:]
			currAns -= AnswerForSubset(l, dsu, prefcnt, prefsum)
			currAns -= AnswerForSubset(r, dsu, prefcnt, prefsum)
			dsu.Unite(l, r)
			currAns += AnswerForSubset(l, dsu, prefcnt, prefsum)
		}
		ans[idx] = currAns
	}

	for i := range ans {
		printf("%v\n", ans[i])
	}
}

func AnswerForSubset(i int, dsu *DSU, prefcnt []int, prefsum []int64) int64 {
	ri := dsu.Root(i)
	l, r := dsu.left[ri], dsu.left[ri]+dsu.size[ri]-1
	cnt := prefcnt[r]
	if l-1 >= 0 {
		cnt -= prefcnt[l-1]
	}
	ans := prefsum[r]
	if r-cnt >= 0 {
		ans -= prefsum[r-cnt]
	}
	return ans
}

type DSU struct {
	parent, size, left []int
}

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

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]
	if d.left[ri] > d.left[rj] {
		d.left[ri] = d.left[rj]
	}
}


In the year of $$$30XX$$$ participants of some world programming championship live in a single large hotel. The hotel has $$$n$$$ floors. Each floor has $$$m$$$ sections with a single corridor connecting all of them. The sections are enumerated from $$$1$$$ to $$$m$$$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $$$n$$$ and width $$$m$$$. We can denote sections with pairs of integers $$$(i, j)$$$, where $$$i$$$ is the floor, and $$$j$$$ is the section number on the floor.The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $$$(1, x)$$$, $$$(2, x)$$$, $$$\ldots$$$, $$$(n, x)$$$ for some $$$x$$$ between $$$1$$$ and $$$m$$$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $$$v$$$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.You are to process $$$q$$$ queries. Each query is a question "what is the minimum time needed to go from a room in section $$$(x_1, y_1)$$$ to a room in section $$$(x_2, y_2)$$$?"

The first line contains five integers $$$n, m, c_l, c_e, v$$$ ($$$2 \leq n, m \leq 10^8$$$, $$$0 \leq c_l, c_e \leq 10^5$$$, $$$1 \leq c_l + c_e \leq m - 1$$$, $$$1 \leq v \leq n - 1$$$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains $$$c_l$$$ integers $$$l_1, \ldots, l_{c_l}$$$ in increasing order ($$$1 \leq l_i \leq m$$$), denoting the positions of the stairs. If $$$c_l = 0$$$, the second line is empty. The third line contains $$$c_e$$$ integers $$$e_1, \ldots, e_{c_e}$$$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $$$l_i$$$ and $$$e_i$$$ are distinct. The fourth line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — the number of queries. The next $$$q$$$ lines describe queries. Each of these lines contains four integers $$$x_1, y_1, x_2, y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1 \leq y_1, y_2 \leq m$$$) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. $$$y_1$$$ and $$$y_2$$$ are not among $$$l_i$$$ and $$$e_i$$$.

Print $$$q$$$ integers, one per line — the answers for the queries.

NoteIn the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.

package main

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

var in = bufio.NewScanner(os.Stdin)

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

func main() {
	in.Split(bufio.ScanWords)
	_ = readInt()
	_ = readInt()
	cl := readInt()
	ce := readInt()
	v := int64(readInt())
	l := make([]int, cl)
	for i := range l {
		l[i] = readInt()
	}
	e := make([]int, ce)
	for i := range e {
		e[i] = readInt()
	}

	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	for q := readInt(); q > 0; q-- {
		x1 := readInt()
		y1 := readInt()
		x2 := readInt()
		y2 := readInt()
		if x1 == x2 {
			fmt.Fprintln(out, abs(y1-y2))
			continue
		}
		best := int64(math.MaxInt64)
		li := sort.SearchInts(l, y1)
		if li < cl {
			ll := l[li]
			best = abs(y1-ll) + abs(y2-ll) + abs(x1-x2)
		}
		if li > 0 {
			ll := l[li-1]
			if cur := abs(y1-ll) + abs(y2-ll) + abs(x1-x2); best > cur {
				best = cur
			}
		}

		ei := sort.SearchInts(e, y1)
		if ei < ce {
			ee := e[ei]
			if cur := abs(y1-ee) + abs(y2-ee) + (abs(x1-x2)+v-1)/v; best > cur {
				best = cur
			}
		}
		if ei > 0 {
			ee := e[ei-1]
			if cur := abs(y1-ee) + abs(y2-ee) + (abs(x1-x2)+v-1)/v; best > cur {
				best = cur
			}
		}
		fmt.Fprintln(out, best)
	}
}

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


Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following:  For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) — the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.

For each test case, output one line containing two integers — the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.

NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.

package main

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

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

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var niter int
	fmt.Fscan(scanner, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		var m int64
		fmt.Fscan(scanner, &n, &m)
		mbig := big.NewInt(m)
		sums := make([]*big.Int, n)
		for i := 0; i < n; i++ {
			sums[i] = big.NewInt(0)
		}
		for i := 0; i < n; i++ {
			for j := big.NewInt(1); j.Cmp(mbig) <= 0; j.Add(j, big.NewInt(1)) {
				var curr int64
				fmt.Fscan(scanner, &curr)
				tmp := big.NewInt(0)
				tmp = tmp.Mul(big.NewInt(curr), j)
				sums[i].Add(sums[i], tmp)
			}
		}
		//fmt.Println("!!!", sums)
		diff := big.NewInt(0)
		same := big.NewInt(0)
		if sums[0].Cmp(sums[1]) == 0 {
			same = sums[0]
		}
		if sums[0].Cmp(sums[2]) == 0 {
			same = sums[0]
		}
		if sums[1].Cmp(sums[2]) == 0 {
			same = sums[1]
		}
		for i := 0; i < n; i++ {
			if sums[i].Cmp(same) != 0 {
				diff = sums[i]
			}
		}
		// if n%2 == 0 {
		// 	for i := 0; i < n-1; i++ {
		// 		diff.Xor(diff, sums[i])
		// 	}
		// 	if diff.Cmp(big.NewInt(0)) == 0 {
		// 		diff = sums[n-1]
		// 	}
		// } else {
		// 	for i := 0; i < n; i++ {
		// 		diff.Xor(diff, sums[i])
		// 	}
		// }
		inum := 0
		for i := 0; i < n; i++ {
			if sums[i].Cmp(diff) == 0 {
				inum = i + 1
			}
		}
		wres := big.NewInt(0)
		wres = wres.Sub(diff, same)
		fmt.Fprintln(writer, inum, wres)
	}
}

package main

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

var _, _, _ = main, rw, do

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, m int
		fmt.Fscan(r, &n, &m)
		a := make([][]int, n)
		for i := range a {
			a[i] = make([]int, m)
			for j := range a[i] {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1, w2 := do(n, m, a)
		fmt.Fprintln(w, w1, w2)
	}
}

func do(n, m int, a [][]int) (k int, c int64) {
	var t int64 = -1
	for i, v := range a {
		var s int64
		for j, w := range v {
			s += int64(m - j) * int64(w)
		}
		if t < 0 {
			t = s
			k = i + 1
		} else if t < s {
			c = s - t
		} else if t > s {
			k = i + 1
			c = t - s
		}
	}
	return
}

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--
		n, m := readTwoNums(reader)
		C := make([][]int, n)
		for i := 0; i < n; i++ {
			C[i] = readNNums(reader, m)
		}
		k, res := solve(n, m, C)
		buf.WriteString(fmt.Sprintf("%d %d\n", k, 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' || s[i] == '\r' {
			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, C [][]int) (int, int64) {
	sum := make([]int64, n)

	for i := 0; i < n; i++ {
		for j := 1; j <= m; j++ {
			sum[i] += int64(C[i][j-1]) * int64(j)
		}
	}

	tmp := sum[0]
	var cnt int
	k := 0
	for i := 1; i < n; i++ {
		if tmp != sum[i] {
			cnt++
			k = i
		}
	}

	if cnt == n-1 {
		// k = 0
		return 1, sum[0] - sum[1]
	}
	// else cnt = 1
	return k + 1, sum[k] - sum[0]
}

package main

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

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

	var T, n, m int
	var v int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		for i, pre := 1, int64(0); i <= n; i++ {
			s := int64(0)
			for j := 0; j < m; j++ {
				Fscan(in, &v)
				s += int64(j) * v
			}
			if pre == -1 {
				continue
			}
			if pre == 0 {
				pre = s
			} else if pre != s {
				if s > pre {
					Fprintln(out, i, s-pre)
				} else {
					Fprintln(out, i-1, pre-s)
				}
				pre = -1
			}
		}
	}
}

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

package main

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

var in = bufio.NewReader(os.Stdin)

func read(out *int64) error {
	var ans, sign int64 = 0, 1
	var readed = false
	c, err := in.ReadByte()
	for ; err == nil && (c < '0' || '9' < c); c, err = in.ReadByte() {
		if c == '-' {
			sign = -sign
		}
	}
	for ; err == nil && '0' <= c && c <= '9'; c, err = in.ReadByte() {
		ans = ans<<3 + ans<<1 + int64(c-'0')
		readed = true
	}
	if readed {
		*out = ans * sign
		return nil
	}
	return err
}

var one int64 = 1
var zero int64 = 0
var two int64 = 2
var n, m, p, q, nq int64

func solve() {
	read(&n)
	read(&m)
	var a [][]int64
	for i := zero; i <= n; i++ {
		inline := make([]int64, m+1)
		a = append(a, inline)
	}
	num := make([]int64, n+1)
	for i := one; i <= n; i++ {
		num[i] = 0
	}
	for i := one; i <= n; i++ {
		for j := one; j <= m; j++ {
			read(&(a[i][j]))
			num[i] += a[i][j] * j
		}
	}
	p, q, nq = num[1], -1, 0
	for i := two; i <= n; i++ {
		if num[i] != p {
			q = num[i]
			nq = i
		}
	}
	if p > q {
		fmt.Println(1, p-q)
	} else {
		fmt.Println(nq, q-p)
	}
}
func main() {
	var t int64
	read(&t)
	for i := zero; i < t; i++ {
		solve()
	}
}

package main

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

func main() {
	var n, m int
	f := bufio.NewReader(os.Stdin)
	s, _ := f.ReadString('\n')
	s = strings.ReplaceAll(s, "\n", "")
	s = strings.ReplaceAll(s, "\r", "")
	t, _ := strconv.ParseInt(s, 10, 32)
	for i := 0; i < int(t); i++ {
		s, _ = f.ReadString('\n')
		s = strings.ReplaceAll(s, "\n", "")
		s = strings.ReplaceAll(s, "\r", "")
		_, _ = fmt.Sscanf(s, "%d %d", &n, &m)
		ws := make([]uint64, n)
		for j := 0; j < n; j++ {
			s, _ = f.ReadString('\n')
			s = strings.ReplaceAll(s, "\r", "")
			s = strings.ReplaceAll(s, "\n", "")
			as := strings.SplitN(s, " ", m)
			if len(as) != m {
				panic("kek")
			}
			sum := uint64(0)
			for k, a := range as {
				x, _ := strconv.ParseInt(a, 10, 64)
				sum += uint64(x) * uint64(k)
			}
			ws[j] = sum
		}
		if ws[1] > ws[0] {
			fmt.Println(2, ws[1]-ws[0])
		} else if ws[1] < ws[0] {
			fmt.Println(1, ws[0]-ws[1])
		} else {
			for j := 2; j < n; j++ {
				if ws[j] != ws[0] {
					fmt.Println(j+1, ws[j]-ws[0])
					break
				}
			}
		}
	}
}

package main

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

var rr = bufio.NewReader(os.Stdin)
var ww = bufio.NewWriter(os.Stdout)

func slove() {
	var n, m int
	fmt.Fscan(rr, &n, &m)
	nums := make([][]int64, n)
	for i := range nums {
		nums[i] = make([]int64, m)
		for j := range nums[i] {
			fmt.Fscan(rr, &nums[i][j])
		}
	}
	var ans, bei int64
	flag := false
	for i:=1;i<n;i++ {
		for j:=0;j<m-1;j++ {
			ans -= nums[0][j] - nums[i][j]
			nums[i][j+1] -= nums[0][j] - nums[i][j]
			nums[i][j] = nums[0][j]
		}
		if ans != 0 {
			if i == 1 {
				flag = true
				bei = ans
				ans = 0
			} else if flag {
				fmt.Fprintln(ww, 1, abs(bei))
				return
			} else {
				fmt.Fprintln(ww, i+1, abs(ans))
				return
			}
		} else if flag {
			fmt.Fprintln(ww, 2, abs(bei))
			return
		}
	}
}

func abs(a int64) int64 {if a < 0 {return -a} else {return a}}

func main() {
	defer ww.Flush()
	var n int
	fmt.Fscan(rr, &n)
	for i:=1;i<=n;i++ {
		slove()
	}
}

package main

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

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

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var niter int
	fmt.Fscan(scanner, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		var m int64
		fmt.Fscan(scanner, &n, &m)
		mbig := big.NewInt(m)
		sums := make([]*big.Int, n)
		for i := 0; i < n; i++ {
			sums[i] = big.NewInt(0)
		}
		for i := 0; i < n; i++ {
			for j := big.NewInt(1); j.Cmp(mbig) <= 0; j.Add(j, big.NewInt(1)) {
				var curr int64
				fmt.Fscan(scanner, &curr)
				tmp := big.NewInt(0)
				tmp = tmp.Mul(big.NewInt(curr), j)
				sums[i].Add(sums[i], tmp)
			}
		}
		//fmt.Println("!!!", sums)
		diff := big.NewInt(0)
		if n%2 == 0 {
			for i := 0; i < n-1; i++ {
				diff.Xor(diff, sums[i])
			}
			if diff.Cmp(big.NewInt(0)) == 0 {
				diff = sums[n-1]
			}
		} else {
			for i := 0; i < n; i++ {
				diff.Xor(diff, sums[i])
			}
		}
		same := sums[0]
		if same.Cmp(diff) == 0 {
			same = sums[1]
		}
		inum := 0
		for i := 0; i < n; i++ {
			if sums[i].Cmp(diff) == 0 {
				inum = i + 1
			}
		}
		wres := big.NewInt(0)
		wres = wres.Sub(diff, same)
		fmt.Fprintln(writer, inum, wres)
	}
}

package main

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

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

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

func main() {
	scanner := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()
	var niter int
	fmt.Fscan(scanner, &niter)
	for iiter := 0; iiter < niter; iiter++ {
		var n int
		var m int64
		fmt.Fscan(scanner, &n, &m)
		sums := make([]int64, n)
		for i := 0; i < n; i++ {
			for j := int64(1); j <= m; j++ {
				var curr int64
				fmt.Fscan(scanner, &curr)
				sums[i] += curr * j
			}
		}
		diff := int64(0)
		if n%2 == 0 {
			for i := 0; i < n-1; i++ {
				diff ^= sums[i]
			}
			if diff == 0 {
				diff = sums[n-1]
			}
		} else {
			for i := 0; i < n; i++ {
				diff ^= sums[i]
			}
		}
		var same int64
		same = sums[0]
		if same == diff {
			same = sums[1]
		}
		inum := 0
		for i := 0; i < n; i++ {
			if sums[i] == diff {
				inum = i + 1
			}
		}
		fmt.Fprintln(writer, inum, diff-same)
	}
}

package main

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

var _, _, _ = main, rw, do

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

func rw(r io.Reader, w io.Writer) {
	var t int
	fmt.Fscan(r, &t)
	for ti := 0; ti < t; ti++ {
		var n, m int
		fmt.Fscan(r, &n, &m)
		a := make([][]int, n)
		for i := range a {
			a[i] = make([]int, m)
			for j := range a[i] {
				fmt.Fscan(r, &a[i][j])
			}
		}
		w1, w2 := do(n, m, a)
		fmt.Fprintln(w, w1, w2)
	}
}

func do(n, m int, a [][]int) (k int, c int) {
	t := -1
	for i, v := range a {
		s := 0
		for j, w := range v {
			s += (m - j) * w
		}
		if t < 0 {
			t = s
			k = i + 1
		} else if t < s {
			c = s - t
		} else if t > s {
			k = i + 1
			c = t - s
		}
	}
	return
}


There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n + 1) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?   The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses.

The first line contains integer t (1 ≤ t ≤ 104) — the number of test cases.  The second line contains t space-separated integers ni (1 ≤ ni ≤ 109) — the sides of the square for each test sample.

For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

package main

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

func scanInt(scanner *bufio.Scanner) int {
  scanner.Scan()
  x, _ := strconv.Atoi(scanner.Text())
  return x
}

func gcd(a, b int64) int64 {
  for b != 0 {
    a, b = b, a%b
  }
  return a
}

func main() {
  scanner := bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  t := scanInt(scanner)
  for i := 0; i < t; i++ {
    n := int64(scanInt(scanner))
    result := 4*n / gcd(n+1, 4*n) + 1
    writer.WriteString(fmt.Sprintf("%d\n", result))
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n uint64
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    switch (n+1)%4 {
      case 0: fmt.Println(n+1)
      case 2: fmt.Println(2*n+1)
      default: fmt.Println(4*n+1)
    }
  }
}

package main
import "fmt"

func main(){
	var n,in,i int64
	fmt.Scan(&n)
	for i=0; i<n; i++ {
		fmt.Scan(&in)
		if in%2==0{
			fmt.Println(in*4+1)
		}else if in%4==1{
			fmt.Println(in*2+1)
		}else{
			fmt.Println(in+1)
		}
	}
}

// 194B
package main

import (
	"fmt"
)

func gcd(u, v int64) int64 {
	for v != 0 {
		r := u % v
		u = v
		v = r
	}
	return u
}

func main() {
	var t, i int64
	fmt.Scan(&t)
	for ; t > 0; t-- {
		fmt.Scan(&i)
		fmt.Println(1 + (4*i)/gcd(4*i, i+1))
	}
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n int
  fmt.Scanf("%d", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    fmt.Println(4*n+1)
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n int
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    fmt.Println(4*n+1)
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n uint64
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    fmt.Println(4*n+1)
  }
}

package main

import (
  "fmt"
)

func main() {
  var t int
  var n uint64
  fmt.Scanf("%d\n", &t)
  for i:=0; i<t; i++ {
    fmt.Scanf("%d", &n)
    switch n%4 {
      case 0: fmt.Println(n+1)
      case 2: fmt.Println(2*n+1)
      default: fmt.Println(4*n+1)
    }
  }
}

package main
import "fmt"

func main(){
	var n,in int
	fmt.Scan(&n)
	for i:=0; i<n; i++ {
		fmt.Scan(&in)
		fmt.Println(in*4+1)
	}
}

package main
import "fmt"

func main(){
	var n,in,i int64
	fmt.Scan(&n)
	for i=0; i<n; i++ {
		fmt.Scan(&in)
		if in%2 == 0{
			fmt.Println(in*4+1)
		}else{
			fmt.Println(in*2+1)
		}
	}
}

package main
import "fmt"

func main(){
	var n,in,i int64
	fmt.Scan(&n)
	for i=0; i<n; i++ {
		fmt.Scan(&in)
		fmt.Println(in*4+1)
	}
}


Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.There is a set $$$S$$$ containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a positive integer $$$k$$$ and replace each element $$$s$$$ of the set $$$S$$$ with $$$s \oplus k$$$ ($$$\oplus$$$ denotes the exclusive or operation). Help him choose such $$$k$$$ that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set $$$\{1, 2, 3\}$$$ equals to set $$$\{2, 1, 3\}$$$.Formally, find the smallest positive integer $$$k$$$ such that $$$\{s \oplus k | s \in S\} = S$$$ or report that there is no such number.For example, if $$$S = \{1, 3, 4\}$$$ and $$$k = 2$$$, new set will be equal to $$$\{3, 1, 6\}$$$. If $$$S = \{0, 1, 2, 3\}$$$ and $$$k = 1$$$, after playing set will stay the same.

In the first line of input, there is a single integer $$$t$$$ ($$$1 \leq t \leq 1024$$$), the number of test cases. In the next lines, $$$t$$$ test cases follow. Each of them consists of two lines.  In the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1024$$$) denoting the number of elements in set $$$S$$$. Second line consists of $$$n$$$ distinct integers $$$s_i$$$ ($$$0 \leq s_i < 1024$$$), elements of $$$S$$$. It is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$1024$$$.

Print $$$t$$$ lines; $$$i$$$-th line should contain the answer to the $$$i$$$-th test case, the minimal positive integer $$$k$$$ satisfying the conditions or $$$-1$$$ if no such $$$k$$$ exists.

NoteIn the first test case, the answer is $$$1$$$ because it is a minimum positive integer and it satisfies all the conditions.

package main

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

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 main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)

		A := readNNums(reader, n)

		fmt.Println(solve(n, A))
	}
}

func solve(n int, A []int) int {
	if n%2 == 1 {
		return -1
	}
	cnt := make([]int, 1025)
	for k := 1; k < 1025; k++ {
		var can = true
		for j := 0; j < n; j++ {
			if A[j]^k >= 1024 {
				can = false
				break
			}
			cnt[A[j]]++
			cnt[A[j]^k]--
		}
		if !can {
			continue
		}
		for j := 0; j < 1025; j++ {
			if cnt[j] != 0 {
				can = false
				break
			}
		}
		if can {
			return k
		}
		for j := 0; j < 1025; j++ {
			cnt[j] = 0
		}
	}
	return -1
}

package main

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

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
var input io.Reader

func main() {
	var (
		T int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &T)
	for i := 0; i < T; i++ {
		solver()
	}
}

func solver() {
	var n int
	table := make(map[int]bool)
	fmt.Fscan(input, &n)
	s := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(input, &s[i])
		table[s[i]] = true
	}

	worker:
	for k := 1; k <= 1024; k++ {
		for _, v := range s {
			vn := v ^ k
			if !(v != vn && table[vn]) {continue worker}
		}
		fmt.Println(k)
		return
	}
	fmt.Println(-1)
}

package main

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

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

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n:= reader.NextInt()
		aa := make([]int, n)
		// hm:=make(map[int]bool)
		max:=0
		for i := 0; i < n; i++ {
			aa[i]=reader.NextInt()
			if(aa[i]>max){
				max=aa[i]
			}
		}
		sort.Ints(aa)
		sol(aa, n,max)
	}
}

func sol(aa []int, n int, max int)  {
	slc:=make([]int,n)
	copy(slc,aa)
	for i:=1;i<=1024;i++ {
		for j:=0;j<n;j++{
			slc[j]=slc[j]^i
		}
		sort.Ints(slc)
		if(reflect.DeepEqual(slc, aa)){
			writer.Printf("%d\n",i)
			return;
		}else{
			copy(slc,aa)
			// fmt.Println(slc)
		}
	}
  writer.Printf("-1\n")
}

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

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

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

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

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(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 SArr64(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 MnMx(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 Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func main() {
	t := nextInt()
	for i := 0; i < t; i++ {
		n := nextInt()
		s := nextInts(n)
		fmt.Println(solve(n, s))
	}
}

func solve(n int, s []int) int {
	if n == 1 {
		return -1
	}

	sort.Ints(s)

	sumXor := 0
	sumOr := 0
	for i := 0; i < len(s); i++ {
		sumXor ^= s[i]
		sumOr |= s[i]
	}
	for t := 1; t <= sumOr; t++ {
		if t&sumOr != t {
			continue
		}
		if check(sumXor, t, s) {
			return t
		}
	}
	return -1
}

func check(sumXor, t int, s []int) bool {
	sum := 0
	products := make([]int, len(s))
	for i := 0; i < len(s); i++ {
		p := (s[i] ^ t)
		sum ^= p
		products[i] = p
	}
	if sum != sumXor {
		return false
	}

	sort.Ints(products)
	for i := 0; i < len(s); i++ {
		if products[i] != s[i] {
			return false
		}
	}
	return true
}

var sc = bufio.NewScanner(os.Stdin)

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

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

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

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

/*
URL:
https://codeforces.com/contest/1362/problem/B
*/

package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math"
	"os"
	"sort"
	"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 int
	S []int
)

func main() {
	t = ReadInt()
	for i := 0; i < t; i++ {
		n = ReadInt()
		S = ReadIntSlice(n)

		solve()
	}
}

func solve() {
	// for i := 0; i < n; i++ {
	// 	PrintfDebug("%2d: %s\n", S[i], string(ZeroPaddingRuneSlice(S[i], 10)))
	// }
	// PrintfDebug("\n")
	sort.Sort(sort.IntSlice(S))

	for k := 1; k < 1024; k++ {
		T := []int{}
		for i := 0; i < n; i++ {
			c := k ^ S[i]
			T = append(T, c)
		}

		sort.Sort(sort.IntSlice(T))
		if isSame(S, T) {
			fmt.Println(k)
			return
		}
	}
	fmt.Println(-1)
}

func isSame(A, B []int) bool {
	for i := 0; i < n; i++ {
		if A[i] != B[i] {
			return false
		}
	}
	return true
}

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

/*********** 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 "fmt"

func main() {
	var nTest int
	fmt.Scan(&nTest)

	for t := 0; t < nTest; t++ {
		var n int
		fmt.Scan(&n)
		var a [1025]int

		for i := 0; i < n; i++ {
			fmt.Scan(&a[i])
		}

		var cnt [1025]int
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				cnt[a[i]^a[j]]++
			}
		}

		hasSolution := false
		for i := 1; i < 1025; i++ {
			if cnt[i] == n {
				fmt.Println(i)
				hasSolution = true
				break
			}
		}

		if !hasSolution {
			fmt.Println(-1)
		}
	}
}

package main

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

func main() {
	defer out.Flush()
	for t := ScanInt(); t > 0; t-- {
		P(solve())
	}

}

var m map[int]bool

func solve() int {
	n := ScanInt()
	a := ScanInts(n)

	//max := Mx(a...)

	for i := 1; i <= 1024; i++ {
		m := make(map[int]bool)
		for j := 0; j < n; j++ {
			m[a[j]^i] = true
		}

		allFound := true
		for j := 0; j < n; j++ {
			if _, found := m[a[j]]; !found {
				allFound = false
				break
			}
		}
		if allFound {
			return i
		}
	}
	return -1
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case []int:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.Itoa(v[i]) + " ")
			}
			str = sb.String()
		case int64:
			str = strconv.FormatInt(v, 10)
		case []int64:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.FormatInt(v[i], 10) + " ")
			}
			str = sb.String()
		case string:
			str = v
		default:
			panic("invalid print arg: " + fmt.Sprintf("%v", arg))

		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
	}
	return a
}

func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func main() {
	defer out.Flush()
	for t := ScanInt(); t > 0; t-- {
		P(solve())
	}

}

var m map[int]bool

func solve() int {
	m = make(map[int]bool)
	n := ScanInt()
	a := ScanInts(n)

	for i := 1; i <= 1024; i++ {
		allFound := true
		for j := 0; j < n; j++ {
			if _, found := m[i^a[j]]; !found {
				allFound = false
				break
			}
		}

		if allFound {
			return i
		}
	}
	return -1
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case []int:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.Itoa(v[i]) + " ")
			}
			str = sb.String()
		case int64:
			str = strconv.FormatInt(v, 10)
		case []int64:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.FormatInt(v[i], 10) + " ")
			}
			str = sb.String()
		case string:
			str = v
		default:
			panic("invalid print arg: " + fmt.Sprintf("%v", arg))

		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
		m[a[i]] = true
	}
	return a
}

func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

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

func main() {
	defer out.Flush()
	inn.Buffer([]byte{}, 10000000)
	inn.Split(bufio.ScanWords)

	for tt := rd(); tt > 0; tt-- {
		n := rd()
		a := make([]int, n)
		cnt := [1024]int{}
		for i := range a {
			a[i] = rd()
			cnt[a[i]]++
		}
		for i := 1; i < 1024; i++ {
			tcnt := [1024]int{}
			for _, it := range a {
				tcnt[it^i]++
			}
			for j := range cnt {
				if cnt[j] != tcnt[j] {
					goto next
				}
			}
			Fprintln(out, i)
			goto nnext
		next:
		}
		Fprintln(out, -1)
	nnext:
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func min64(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}
func rd() (x int) {
	inn.Scan()
	data := inn.Bytes()
	x, _ = strconv.Atoi(string(data))
	return x
}
func rdll() (x int64) {
	inn.Scan()
	data := inn.Bytes()
	x, _ = strconv.ParseInt(string(data), 10, 64)
	return x
}
func rds() string {
	inn.Scan()
	return string(inn.Bytes())
}

package main

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

func fastGetInt(b []byte) int {
	neg := false
	if b[0] == '-' {
		neg = true
		b = b[1:]
	}
	n := 0
	for _, v := range b {
		n = n*10 + int(v-'0')
	}
	if neg {
		return -n
	}
	return n
}

func equalSlice(s1 []int, s2 []int) bool {
	if len(s1) != len(s2) {
		return false
	}
	for x := 0; x < len(s1); x++ {
		if s1[x] != s2[x] {
			return false
		}
	}
	return true
}

//========== Implement Algorithm =======================
func solution(sl []int) {
	sort.Ints(sl)
	check := false
	for i := 1; i < 1040; i++ {
		newSl := make([]int, len(sl))
		for x := 0; x < len(sl); x++ {
			newSl[x] = sl[x] ^ i
		}
		sort.Ints(newSl)
		if equalSlice(newSl, sl) {
			fmt.Println(i)
			check = true
			break
		}
	}
	if !check {
		fmt.Println(-1)
	}
}

func main() {

	scanner := bufio.NewScanner(os.Stdin)

	//================== Variables used ====================
	var num int
	//======================================================

	//============== Get return value from File ============
	if len(os.Args) >= 2 {

		file, err := os.Open(os.Args[1])
		if err != nil {
			log.Fatalf("failed opening file: %s", err)
		}
		scanner = bufio.NewScanner(file)
		defer file.Close()

	}
	scanner.Split(bufio.ScanWords)
	//======================= I/O ==========================
	scanner.Scan()
	num = fastGetInt(scanner.Bytes())
	//======================================================
	for x := 0; x < num; x++ {
		scanner.Scan()
		a := fastGetInt(scanner.Bytes())
		sl := make([]int, a)
		for i := 0; i < a; i++ {
			scanner.Scan()
			sl[i] = fastGetInt(scanner.Bytes())
		}
		solution(sl)
	}
	//==================== OUTPUT ==========================

}

package main

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

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 main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)

		A := readNNums(reader, n)

		fmt.Println(solve(n, A))
	}
}

func solve(n int, A []int) int {
	if n%2 == 1 {
		return -1
	}

	var res int
	var res2 int = -1
	for i := 0; i < 11; i++ {
		var cnt int
		for j := 0; j < n; j++ {
			cnt += (A[j] >> i) & 1
		}
		cnt2 := n - cnt
		//如果put 1, 0 ^ 1 => 1, 1 ^ 1 => 0
		//如果put 0，0 ^ 0 => 0, 1 ^ 0 => 1
		if cnt == cnt2 && res2 < 0 {
			res2 = 1 << i
		}
		if cnt&1 == 0 && cnt2&1 == 0 {
			// can put 0 here
		} else {
			// have to put 1 here
			if cnt != cnt2 {
				return -1
			}
			res |= 1 << i
		}
	}

	if res == 0 {
		res = res2
	}

	if res < 0 {
		return -1
	}

	cnt := make([]int, 1025)

	for i := 0; i < n; i++ {
		cnt[A[i]]++
		cnt[res^A[i]]--
	}

	for i := 0; i < 1025; i++ {
		if cnt[i] != 0 {
			return -1
		}
	}

	return res
}

package main

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

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 main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	for tc > 0 {
		tc--
		n := readNum(reader)

		A := readNNums(reader, n)

		fmt.Println(solve(n, A))
	}
}

func solve(n int, A []int) int {
	if n%2 == 1 {
		return -1
	}
	cnt := make([]int, 1025)
	for i := 1; i < n; i++ {
		k := A[i] ^ A[0]
		if k >= 1024 {
			continue
		}
		var can = true
		for j := 0; j < n; j++ {
			if A[j]^k >= 1024 {
				can = false
				break
			}
			cnt[A[j]]++
			cnt[A[j]^k]--
		}
		if !can {
			continue
		}
		for j := 0; j < 1025; j++ {
			if cnt[j] != 0 {
				can = false
				break
			}
		}
		if can {
			return k
		}
		for j := 0; j < 1025; j++ {
			cnt[j] = 0
		}
	}
	return -1
}

package main

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

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

func main() {
	defer writer.Flush()
	t := reader.NextInt64()
	for ; t > 0; t-- {
		n:= reader.NextInt()
		aa := make([]int, n)
		// hm:=make(map[int]bool)
		max:=0
		for i := 0; i < n; i++ {
			aa[i]=reader.NextInt()
			if(aa[i]>max){
				max=aa[i]
			}
		}
		sort.Ints(aa)
		sol(aa, n,max)
	}
}

func sol(aa []int, n int, max int)  {
	slc:=make([]int,n)
	copy(slc,aa)
	for i:=1;i<=max;i++ {
		for j:=0;j<n;j++{
			slc[j]=slc[j]^i
		}
		sort.Ints(slc)
		if(reflect.DeepEqual(slc, aa)){
			writer.Printf("%d\n",i)
			return;
		}else{
			copy(slc,aa)
		}
	}
  writer.Printf("-1\n")
}

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

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

type writerImpl struct {
	*bufio.Writer
}

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

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

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

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

type wordScannerImpl struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
	s := bufio.NewScanner(reader)
	s.Split(bufio.ScanWords)
	// adjust the following size as needed
	// 2 << 17 is good enough to scan strings of len 2*10^5
	// it could go as high as 2 << 26 before cf judge breaks
	size := 2 << 20
	buf := make([]byte, size)
	s.Buffer(buf, size)
	return &wordScannerImpl{Scanner: s}
}

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

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

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

func S(v interface{}) string { return fmt.Sprintf("%v", v) }
func SArr(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 SArr64(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 MnMx(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 Mn(args ...int64) int64 { mn, _ := MnMx(args...); return mn }
func Mx(args ...int64) int64 { _, mx := MnMx(args...); return mx }
func LCM(a, b int64) int64   { return a / GCD(a, b) * b }
func GCD(a, b int64) int64 {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func sortInt64Slice(a []int64) { sort.Slice(a, func(i, j int) bool { return a[i] < a[j] }) }
func abs(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

package main

import "fmt"

func main() {
	var nTest int
	fmt.Scanf("%d\n", &nTest)

	for t := 0; t < nTest; t++ {
		var n int
		fmt.Scanf("%d\n", &n)
		var a [1025]int

		for i := 0; i < n; i++ {
			fmt.Scanf("%d", &a[i])
		}

		var cnt [1025]int
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				cnt[a[i]^a[j]]++
			}
		}

		hasSolution := false
		for i := 1; i < 1025; i++ {
			if cnt[i] == n {
				fmt.Println(i)
				hasSolution = true
				break
			}
		}

		if !hasSolution {
			fmt.Println(-1)
		}
	}
}

package main

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

func main() {
	defer out.Flush()
	for t := ScanInt(); t > 0; t-- {
		P(solve())
	}

}

var m map[int]bool

func solve() int {
	n := ScanInt()
	a := ScanInts(n)

	max := Mx(a...)

	for i := 1; i <= max; i++ {
		m := make(map[int]bool)
		for j := 0; j < n; j++ {
			m[a[j]^i] = true
		}

		allFound := true
		for j := 0; j < n; j++ {
			if _, found := m[a[j]]; !found {
				allFound = false
				break
			}
		}
		if allFound {
			return i
		}
	}
	return -1
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case []int:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.Itoa(v[i]) + " ")
			}
			str = sb.String()
		case int64:
			str = strconv.FormatInt(v, 10)
		case []int64:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.FormatInt(v[i], 10) + " ")
			}
			str = sb.String()
		case string:
			str = v
		default:
			panic("invalid print arg: " + fmt.Sprintf("%v", arg))

		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
	}
	return a
}

func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

package main

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

func main() {
	defer out.Flush()
	for t := ScanInt(); t > 0; t-- {
		P(solve())
	}

}

var m map[int]bool

func solve() int {
	m = make(map[int]bool)
	n := ScanInt()
	a := ScanInts(n)

	for i := 1; i <= 1024; i++ {
		allFound := true
		for j := 0; j < n; j++ {
			if _, found := m[a[j]]; !found {
				allFound = false
				break
			}
		}

		if allFound {
			return i
		}
	}
	return -1
}

/*********************** I/O ***********************/
var in *bufio.Scanner
var out *bufio.Writer

func init() {
	in = bufio.NewScanner(os.Stdin)
	in.Buffer(make([]byte, 1024), int(1e+9))
	in.Split(bufio.ScanWords)
	out = bufio.NewWriter(os.Stdout)
}

func P(args ...interface{}) {
	print("\n", args...)
}

func PS(args ...interface{}) {
	print(" ", args...)
	print("\n", nil)
}

func print(seperator string, args ...interface{}) {
	for _, arg := range args {
		str := ""
		switch v := arg.(type) {
		case byte:
			str = string(v)
		case rune:
			str = string(v)
		case int:
			str = strconv.Itoa(v)
		case []int:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.Itoa(v[i]) + " ")
			}
			str = sb.String()
		case int64:
			str = strconv.FormatInt(v, 10)
		case []int64:
			sb := strings.Builder{}
			for i := 0; i < len(v); i++ {
				sb.WriteString(strconv.FormatInt(v[i], 10) + " ")
			}
			str = sb.String()
		case string:
			str = v
		default:
			panic("invalid print arg: " + fmt.Sprintf("%v", arg))

		}
		out.WriteString(str + seperator)
	}
}

func ScanWord() string { in.Scan(); return in.Text() }
func ScanWords(n int) []string {
	s := make([]string, n)
	for i := 0; i < n; i++ {
		s[i] = ScanWord()
	}
	return s
}
func ScanInt() int { i, _ := strconv.Atoi(ScanWord()); return i }
func ScanInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ScanInt()
		m[a[i]] = true
	}
	return a
}

func MnMx(args ...int) (int, int) {
	minVal, maxVal := math.MaxInt32, math.MinInt32
	for _, v := range args {
		if v < minVal {
			minVal = v
		}
		if v > maxVal {
			maxVal = v
		}
	}
	return minVal, maxVal
}
func Mn(args ...int) int { mn, _ := MnMx(args...); return mn }
func Mx(args ...int) int { _, mx := MnMx(args...); return mx }
func LCM(a, b int) int   { return a / GCD(a, b) * b }
func GCD(a, b int) int {
	if a == 0 {
		return b
	}
	return GCD(b%a, a)
}
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}