A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $$$l$$$ nanoseconds, where $$$l$$$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $$$2$$$ nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of Dima's sequence. The second line contains string of length $$$n$$$, consisting of characters "(" and ")" only.

Print a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.

NoteIn the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is $$$4 + 2 = 6$$$ nanoseconds.

/*
URL:
https://codeforces.com/problemset/problem/1322/A
*/

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 (
	n int
	S []rune
)

func main() {
	n = ReadInt()
	S = ReadRuneSlice()

	pref := make([]int, n+1)
	for i := 0; i < n; i++ {
		if S[i] == '(' {
			pref[i+1] = pref[i] + 1
		} else {
			pref[i+1] = pref[i] - 1
		}
	}
	PrintfDebug("%v\n", pref)

	if pref[len(pref)-1] != 0 {
		fmt.Println(-1)
		return
	}

	ans := 0
	var start int
	var flag bool
	for i := 1; i <= n; i++ {
		if pref[i] < 0 && !flag {
			start = i
			flag = true
			continue
		}

		if pref[i] == 0 && flag {
			ans += i - start + 1
			flag = false
		}
	}

	fmt.Println(ans)
}

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

/*********** 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"
	"strconv"
)

var reader io.Reader
var scanner *bufio.Scanner

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

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

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

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

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

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

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

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

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

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

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

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

	lastPos := -1
	var result int
	var bal int
	for i := 0; i < n; i++ {
		if s[i] == '(' {
			bal++
		} else if s[i] == ')' {
			bal--
		}

		if bal == 0 && lastPos != -1 {
			result += i - lastPos + 1
			lastPos = -1
		}
		if bal < 0 && lastPos == -1 {
			lastPos = i
		}
	}
	if bal != 0 {
		fmt.Fprintln(out, -1)
		return
	}
	fmt.Fprintln(out, result)
}

package main

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

func main() {
	var n int64
	fmt.Scanf("%d\n", &n)
	reader := bufio.NewReader(os.Stdin)
	str := readLine(reader)
	if n%2 != 0 {
		fmt.Println(-1)
		return
	}
	left := 0
	wstart := int64(0)
	flag := true
	result := int64(0)
	for i := int64(0); i < n; i++ {
		if str[i] == ')' {
			left--
			if left == 0 && !flag {
				flag = true
				result += i - wstart + 1
				wstart = 0
			} else if left < 0 && flag {
				flag = false
				wstart = i
			}
		}
		if str[i] == '(' {
			left++
			if left == 0 && !flag {
				flag = true
				result += i-wstart+1
				wstart = 0
			}
		}
	}
	if left != 0 {
		fmt.Println(-1)
		return
	}
	fmt.Println(result)
}

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 {
			// fmt.Println(string(result))
			break
		}
	}
	return result
}

package main

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    capacity := 5000 * 1024
    scanner.Buffer(make([]byte, capacity), capacity)

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

    scanner.Scan()
    line = scanner.Text()
    a := make([]int8, n)
    for i := 0; i < n; i++ {
        if line[i] == '(' {
            a[i] = 1
        } else if line[i] == ')' {
            a[i] = -1
        } else {
            panic("invalid char")
        }
    }
    //~ fmt.Println(a)

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

    //~ fmt.Println(sum)

    if sum[n - 1] != 0 {
        fmt.Println(-1)
        return
    }

    zeroes := find_zeroes(sum)
    //~ fmt.Println(zeroes)

    last_zero := -1
    count := 0
    for _, zero := range zeroes {
        if sum[zero - 1] < 0 {
            count += zero - last_zero
        }
        last_zero = zero
    }

    fmt.Println(count)
}

func find_zeroes(a []int) []int {
    z := make([]int, 0)
    for i, v := range a {
        if v == 0 {
            z = append(z, i)
        }
    }
    return z
}

package main

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

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

	var n, cntL, ans int
	var s []byte
	Fscan(in, &n, &s)
	for _, b := range s {
		if b == '(' {
			cntL++
		}
	}
	if 2*cntL != n {
		Fprint(out, -1)
		return
	}

	cntL = 0
	for i := 0; i < n; i++ {
		if s[i] == '(' {
			cntL++
			continue
		}
		cntL--
		if cntL >= 0 {
			continue
		}
		st := i
		for i++; i < n; i++ {
			if s[i] == '(' {
				cntL++
				if cntL == 0 {
					break
				}
			} else {
				cntL--
			}
		}
		ans += i - st + 1
	}
	Fprint(out, ans)
}

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

package main

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

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

	var n int
	var s []byte
	Fscan(in, &n, &s)
	if n%2 == 1 {
		Fprintln(out, -1)
		return
	}
	cntl, cntr := 0, 0
	for _, b := range s {
		if b == '(' {
			cntl++
		} else {
			cntr++
		}
	}
	if cntl != n/2 {
		Fprintln(out, -1)
		return
	}

	ans := 0
	cntl, cntr = 0, 0
	okl := 0
	for i := 0; i < n; i++ {
		b := s[i]

		if b == '(' {
			//cntl++
			okl++
		} else {
			//cntr++
			okl--
			if okl < 0 {
				j := i+1
				for ; j < n; j++ {
					b := s[j]
					if b == '(' {
						okl++
						if okl == 0 {
							break
						}
					} else {
						okl--
					}
				}
				ans += j-i+1
				i=j
			}
		}

	}
	Fprintln(out, ans)
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1323C(_r io.Reader, _w io.Writer) {
	var n, c, ans int
	var s []byte
	Fscan(bufio.NewReader(_r), &n, &s)
	for _, b := range s {
		if b == '(' {
			c++
		}
	}
	if 2*c != n {
		Fprint(_w, -1)
		return
	}

	c = 0
	for i := 0; i < n; i++ {
		if s[i] == '(' {
			c++
			continue
		}
		c--
		if c >= 0 {
			continue
		}
		st := i
		for i++; i < n; i++ {
			if s[i] == '(' {
				c++
				if c == 0 {
					break
				}
			} else {
				c--
			}
		}
		ans += i - st + 1
	}
	Fprint(_w, ans)
}

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

package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	buf, _ := ioutil.ReadAll(os.Stdin)
	buf = bytes.TrimSpace(buf)

	parts := bytes.Split(buf, []byte("\n"))
	if len(parts) != 2 {
		panic("!!!")
	}

	str := bytes.TrimSpace(parts[1])

	curr := 0

	ans := 0

	for _, c := range str {
		if c == '(' {
			curr++
			if curr <= 0 {
				ans++
			}
		} else if c == ')' {
			curr--
			if curr < 0 {
				ans++
			}
		} else {
			panic(string([]byte{c}))
		}
	}

	if curr != 0 {
		fmt.Println(-1)
	} else {
		fmt.Println(ans)
	}
}


You are given two arrays $$$a_1, a_2, \dots , a_n$$$ and $$$b_1, b_2, \dots , b_m$$$. Array $$$b$$$ is sorted in ascending order ($$$b_i < b_{i + 1}$$$ for each $$$i$$$ from $$$1$$$ to $$$m - 1$$$).You have to divide the array $$$a$$$ into $$$m$$$ consecutive subarrays so that, for each $$$i$$$ from $$$1$$$ to $$$m$$$, the minimum on the $$$i$$$-th subarray is equal to $$$b_i$$$. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of $$$a$$$ compose the first subarray, the next several elements of $$$a$$$ compose the second subarray, and so on.For example, if $$$a = [12, 10, 20, 20, 25, 30]$$$ and $$$b = [10, 20, 30]$$$ then there are two good partitions of array $$$a$$$:   $$$[12, 10, 20], [20, 25], [30]$$$;  $$$[12, 10], [20, 20, 25], [30]$$$. You have to calculate the number of ways to divide the array $$$a$$$. Since the number can be pretty large print it modulo 998244353.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of arrays $$$a$$$ and $$$b$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. The third line contains $$$m$$$ integers $$$b_1, b_2, \dots , b_m$$$ ($$$1 \le b_i \le 10^9; b_i < b_{i+1}$$$) — the array $$$b$$$.

In only line print one integer — the number of ways to divide the array $$$a$$$ modulo 998244353.

package main

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

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

	n, m := readTwoNums(reader)
	A := readNNums(reader, n)
	B := readNNums(reader, m)

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

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
}

const MOD = 998244353

func solve(n int, A []int, m int, B []int) int {
	//if n < m {
	//	return 0
	//}
	reverse(A)
	reverse(B)

	cur := A[0]
	var pos int

	for pos < n && cur > B[0] {
		pos++
		if pos < n {
			cur = min(cur, A[pos])
		} else {
			cur = -1
		}
	}

	if pos == n || cur < B[0] {
		return 0
	}

	var res int64 = 1
	var ii = 0

	for {
		if ii == m-1 {
			if minElement(A[pos:]) != B[ii] {
				return 0
			}
			break
		}
		var f = true
		npos := pos

		for npos < n && cur != B[ii+1] {
			npos++
			if npos < n {
				cur = min(cur, A[npos])
			} else {
				cur = -1
			}
			if f && cur < B[ii] {
				f = false
				res *= int64(npos - pos)
				res %= MOD
			}
		}

		if npos == n || cur != B[ii+1] {
			return 0
		}
		ii++
		pos = npos
	}

	return int(res)
}

func reverse(arr []int) {
	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
		arr[i], arr[j] = arr[j], arr[i]
	}
}

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

func minElement(arr []int) int {
	res := arr[0]
	for i := 1; i < len(arr); i++ {
		res = min(res, arr[i])
	}
	return res
}


Note: The XOR-sum of set $$$\{s_1,s_2,\ldots,s_m\}$$$ is defined as $$$s_1 \oplus s_2 \oplus \ldots \oplus s_m$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.After almost winning IOI, Victor bought himself an $$$n\times n$$$ grid containing integers in each cell. $$$n$$$ is an even integer. The integer in the cell in the $$$i$$$-th row and $$$j$$$-th column is $$$a_{i,j}$$$.Sadly, Mihai stole the grid from Victor and told him he would return it with only one condition: Victor has to tell Mihai the XOR-sum of all the integers in the whole grid.Victor doesn't remember all the elements of the grid, but he remembers some information about it: For each cell, Victor remembers the XOR-sum of all its neighboring cells.Two cells are considered neighbors if they share an edge — in other words, for some integers $$$1 \le i, j, k, l \le n$$$, the cell in the $$$i$$$-th row and $$$j$$$-th column is a neighbor of the cell in the $$$k$$$-th row and $$$l$$$-th column if $$$|i - k| = 1$$$ and $$$j = l$$$, or if $$$i = k$$$ and $$$|j - l| = 1$$$.To get his grid back, Victor is asking you for your help. Can you use the information Victor remembers to find the XOR-sum of the whole grid?It can be proven that the answer is unique.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \leq n \leq 1000$$$) — the size of the grid. Then follows $$$n$$$ lines, each containing $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th of these lines represents the XOR-sum of the integers in all the neighbors of the cell in the $$$i$$$-th row and $$$j$$$-th column. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$1000$$$ and in the original grid $$$0 \leq a_{i, j} \leq 2^{30} - 1$$$. Hack Format To hack a solution, use the following format: The first line should contain a single integer t ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case should contain a single even integer $$$n$$$ ($$$2 \leq n \leq 1000$$$) — the size of the grid. Then $$$n$$$ lines should follow, each containing $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th of these lines is $$$a_{i,j}$$$ in Victor's original grid. The values in the grid should be integers in the range $$$[0, 2^{30}-1]$$$ The sum of $$$n$$$ over all test cases must not exceed $$$1000$$$.

For each test case, output a single integer — the XOR-sum of the whole grid.

package main

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

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

	t := readInt(in)
	b := strings.Builder{}
	for i := 0; i < t; i++ {
		str := solve(in)
		b.WriteString(str + "\n")
	}
	fmt.Println(b.String())
}

func solve(in *bufio.Reader) string {
	n := readInt(in)
	grid := make([][]int, n)
	visited := make([][]int, n)

	for i := 0; i < n; i++ {
		row := readArrInt(in)
		visitedRow := make([]int, n)
		grid[i] = row
		visited[i] = visitedRow
	}

	res := 0
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			xor := grid[i][j]
			if checkAdj(visited, i, j, n) {
				res = res ^ xor
			}
		}
	}

	return strconv.Itoa(res)
}

func printArr(visited [][]int, n int) {
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Printf("%d ", visited[i][j])
		}
		fmt.Println()
	}
}

type coord struct {
	i int
	j int
}

func changeVisited(arr [][]int, coords []coord) {
	for _, c := range coords {
		arr[c.i][c.j] = 1
	}
}

func checkAdj(arr [][]int, i, j, n int) bool {
	toChange := []coord{}
	left := coord{i, j - 1}
	right := coord{i, j + 1}
	up := coord{i - 1, j}
	down := coord{i + 1, j}
	if left.inBorder(n) {
		if arr[left.i][left.j] != 0 {
			return false
		}
		toChange = append(toChange, left)
	}
	if right.inBorder(n) {
		if arr[right.i][right.j] != 0 {
			return false
		}
		toChange = append(toChange, right)
	}
	if up.inBorder(n) {
		if arr[up.i][up.j] != 0 {
			return false
		}
		toChange = append(toChange, up)
	}
	if down.inBorder(n) {
		if arr[down.i][down.j] != 0 {
			return false
		}
		toChange = append(toChange, down)
	}
	changeVisited(arr, toChange)
	return true
}

func (c *coord) inBorder(n int) bool {
	return c.j < n && c.j >= 0 && c.i < n && c.i >= 0
}

func readInt(in *bufio.Reader) int {
nStr, _ := in.ReadString('\n')
nStr = strings.ReplaceAll(nStr, "\r", "")
nStr = strings.ReplaceAll(nStr, "\n", "")
n, _ := strconv.Atoi(nStr)
return n
}

func readLineNumbs(in *bufio.Reader) []string {
line, _ := in.ReadString('\n')
line = strings.ReplaceAll(line, "\r", "")
line = strings.ReplaceAll(line, "\n", "")
numbs := strings.Split(line, " ")
return numbs
}

func readArrInt(in *bufio.Reader) []int {
	numbs := readLineNumbs(in)
	arr := make([]int, len(numbs))
	for i, n := range numbs {
		val, _ := strconv.Atoi(n)
		arr[i] = val
	}
	return arr
}

package main

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

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

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

var n int
var m [][]int
var values [][]int
var ans = 0

func pick(i, j int) {
	// printf("pick %d,%d\n", i, j)
	ans ^= values[i][j]
	if i+1 < n {
		m[i+1][j] ^= 1
	}
	if i > 0 {
		m[i-1][j] ^= 1
	}
	if j+1 < n {
		m[i][j+1] ^= 1
	}
	if j > 0 {
		m[i][j-1] ^= 1
	}
	// printf("ans = %d\n", ans)
}

func printMatrix() {
	printf("Matrix: \n")
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			printf("%d", m[i][j])
		}
		printf("\n")
	}
	printf("-------------------\n")
}

func solveCase() {
	scan(&n)
	m = make([][]int, n)
	values = make([][]int, n)
	ans = 0
	for i := 0; i < n; i++ {
		m[i] = make([]int, n)
		values[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			scan(&values[i][j])
		}
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if m[i][j] == 0 {
				if j+1 < n {
					if i > 0 && m[i-1][j+1] == 1 {
						pick(i+1, j)
					} else {
						pick(i, j+1)
					}
					// printMatrix()
				} else if i+1 < n {
					pick(i+1, j)
					// printMatrix()
				}
			}
		}
	}
	printf("%d\n", ans)
}

func main() {
	defer out.Flush()

	var ntc int
	scan(&ntc)
	for t := 0; t < ntc; t++ {
		solveCase()
	}
}


Roland loves growing flowers. He has recently grown a beautiful rose at point (0, 0) of the Cartesian coordinate system. The rose is so beautiful that Roland is afraid that the evil forces can try and steal it. To protect the rose, Roland wants to build n watch towers. Let's assume that a tower is a point on the plane at the distance of at most r from the rose. Besides, Roland assumes that the towers should be built at points with integer coordinates and the sum of squares of distances between all pairs of towers must be as large as possible. Note, that Roland may build several towers at the same point, also he may build some of them at point (0, 0).Help Roland build the towers at the integer points so that the sum of squares of distances between all towers is maximum possible. Note that the distance in this problem is defined as the Euclidian distance between points.

The first line contains two integers, n and r (2 ≤ n ≤ 8; 1 ≤ r ≤ 30).

In the first line print an integer — the maximum possible sum of squared distances. In the i-th of the following n lines print two integers, xi, yi — the coordinates of the i-th tower. Each tower must be inside or on the border of the circle with radius r. Note that there may be several towers located at the same point of the plane, also some towers can be located at point (0, 0). If there are multiple valid optimal arrangements, choose any of them.

package main

import (
	"fmt"
	"sort"
)

const top = 33

func main() {
	var n, r int
	fmt.Scan(&n, &r)
	points := eligiblePoints(r)
	ans := make([]int, n)
	ansScore := -1
	cur := make([]int, n)
	var bf func(int)
	bf = func(i int) {
		if i == n {
			score := 0
			for j, a := range cur {
				for _, b := range cur[j+1:] {
					dx := points[b][0] - points[a][0]
					dy := points[b][1] - points[a][1]
					score += dx*dx + dy*dy
				}
			}
			if score > ansScore {
				copy(ans, cur)
				ansScore = score
			}
			return
		}
		for cur[i] = cur[i-1]; cur[i] < len(points); cur[i]++ {
			bf(i + 1)
		}
	}
	bf(1)
	fmt.Println(ansScore)
	for _, a := range ans {
		fmt.Println(points[a][0], points[a][1])
	}
}

type byDist [][2]int

func (s byDist) Len() int { return len(s) }
func (s byDist) Less(i, j int) bool {
	return s[i][0]*s[i][0]+s[i][1]*s[i][1] > s[j][0]*s[j][0]+s[j][1]*s[j][1]
}
func (s byDist) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func eligiblePoints(r int) [][2]int {
	var res [][2]int
	r2 := r * r
	forY := func(x int) {
		for y := -r; y <= r; y++ {
			d2 := x*x + y*y
			if d2 > r2 {
				continue
			}
			res = append(res, [2]int{x, y})
		}
	}
	for x := 0; x <= r; x++ {
		forY(x)
	}
	for x := -r; x < 0; x++ {
		forY(x)
	}
	if len(res) > top {
		sort.Sort(byDist(res))
		return res[:top]
	}
	return res
}

package main

import (
	"fmt"
	"sort"
)

const (
	allow = 12
	top   = 33
)

func main() {
	var n, r int
	fmt.Scan(&n, &r)
	points := eligiblePoints(r)
	ans := make([]int, n)
	ansScore := -1
	cur := make([]int, n)
	var bf func(int)
	bf = func(i int) {
		if i == n {
			score := 0
			for j, a := range cur {
				for _, b := range cur[j+1:] {
					dx := points[b][0] - points[a][0]
					dy := points[b][1] - points[a][1]
					score += dx*dx + dy*dy
				}
			}
			if score > ansScore {
				copy(ans, cur)
				ansScore = score
			}
			return
		}
		for cur[i] = cur[i-1]; cur[i] < len(points); cur[i]++ {
			bf(i + 1)
		}
	}
	bf(1)
	fmt.Println(ansScore)
	for _, a := range ans {
		fmt.Println(points[a][0], points[a][1])
	}
}

type byDist [][2]int

func (s byDist) Len() int { return len(s) }
func (s byDist) Less(i, j int) bool {
	return s[i][0]*s[i][0]+s[i][1]*s[i][1] > s[j][0]*s[j][0]+s[j][1]*s[j][1]
}
func (s byDist) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func eligiblePoints(r int) [][2]int {
	var res [][2]int
	r2 := r * r
	forY := func(x int) {
		for y := -r; y <= r; y++ {
			d2 := x*x + y*y
			if d2 > r2 || d2 < r2-allow {
				continue
			}
			res = append(res, [2]int{x, y})
		}
	}
	for x := 0; x <= r; x++ {
		forY(x)
	}
	for x := -r; x < 0; x++ {
		forY(x)
	}
	if len(res) > top {
		sort.Sort(byDist(res))
		return res[:top]
	}
	return res
}

package main

import (
	"fmt"
	"sort"
)

const top = 12

func main() {
	var n, r int
	fmt.Scan(&n, &r)
	points := eligiblePoints(r)
	ans := make([]int, n)
	ansScore := -1
	cur := make([]int, n)
	var bf func(int)
	bf = func(i int) {
		if i == n {
			score := 0
			for j, a := range cur {
				for _, b := range cur[j+1:] {
					dx := points[b][0] - points[a][0]
					dy := points[b][1] - points[a][1]
					score += dx*dx + dy*dy
				}
			}
			if score > ansScore {
				copy(ans, cur)
				ansScore = score
			}
			return
		}
		for cur[i] = cur[i-1]; cur[i] < len(points); cur[i]++ {
			bf(i + 1)
		}
	}
	bf(1)
	fmt.Println(ansScore)
	for _, a := range ans {
		fmt.Println(points[a][0], points[a][1])
	}
}

type byDist [][2]int

func (s byDist) Len() int { return len(s) }
func (s byDist) Less(i, j int) bool {
	return s[i][0]*s[i][0]+s[i][1]*s[i][1] > s[j][0]*s[j][0]+s[j][1]*s[j][1]
}
func (s byDist) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func eligiblePoints(r int) [][2]int {
	var res [][2]int
	r2 := r * r
	forY := func(x int) {
		for y := -r; y <= r; y++ {
			d2 := x*x + y*y
			if d2 > r2 {
				continue
			}
			res = append(res, [2]int{x, y})
		}
	}
	for x := 0; x <= r; x++ {
		forY(x)
	}
	for x := -r; x < 0; x++ {
		forY(x)
	}
	if len(res) > top {
		sort.Sort(byDist(res))
		return res[:top]
	}
	return res
}


Morning desert sun horizonRise above the sands of time...Fates Warning, "Exodus"After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open!Ori was taken aback, but the Voice of the Forest explained to him that the cunning Gorleks had decided to add protection to the repository.The Gorleks were very fond of the "string expansion" operation. They were also very fond of increasing subsequences.Suppose a string $$$s_1s_2s_3 \ldots s_n$$$ is given. Then its "expansion" is defined as the sequence of strings $$$s_1$$$, $$$s_1 s_2$$$, ..., $$$s_1 s_2 \ldots s_n$$$, $$$s_2$$$, $$$s_2 s_3$$$, ..., $$$s_2 s_3 \ldots s_n$$$, $$$s_3$$$, $$$s_3 s_4$$$, ..., $$$s_{n-1} s_n$$$, $$$s_n$$$. For example, the "expansion" the string 'abcd' will be the following sequence of strings: 'a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'. To open the ancient repository, Ori must find the size of the largest increasing subsequence of the "expansion" of the string $$$s$$$. Here, strings are compared lexicographically.Help Ori with this task!A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 5000$$$) — length of the string. The second line of each test case contains a non-empty string of length $$$n$$$, which consists of lowercase latin letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For every test case print one non-negative integer — the answer to the problem.

7
5
acbac
8
acabacba
12
aaaaaaaaaaaa
10
abacabadac
8
dcbaabcd
3
cba
6
sparky

NoteIn first test case the "expansion" of the string is: 'a', 'ac', 'acb', 'acba', 'acbac', 'c', 'cb', 'cba', 'cbac', 'b', 'ba', 'bac', 'a', 'ac', 'c'. The answer can be, for example, 'a', 'ac', 'acb', 'acba', 'acbac', 'b', 'ba', 'bac', 'c'.

package main

import (
	"fmt"
	"unsafe"
)

const N int = 5000

var t int

func memset(s unsafe.Pointer, mdata byte, n uintptr) {
	start := uintptr(s)
	end := start + n
	for i := start; i < end; i++ {
		*((*byte)(unsafe.Pointer(i))) = mdata
	}
}

var n int
var ss string
var charsize int
var sa, rk, sorta, sort1, sort2, lcps [N + 5]int
var ff [N + 5]int
var lg2 [N + 5]int
var sts [21][N + 5]int

type pair struct {
	l int16
	r int16
}

type Seq []pair

var lis [(N * (N + 1) >> 1) + 5]pair

type Comparable interface {
	Less(b interface{}) bool
}

type ComparableList interface {
	Len() int32
	ILoc(a int32) Comparable
}

func LowerBound(seq ComparableList, v Comparable) int32 {
	L := int32(0)
	R := seq.Len() - 1
	if R < 0 || seq.ILoc(R).Less(v) {
		return R + 1
	}
	for L < R {
		mid := L + (R-L)>>1
		if seq.ILoc(mid).Less(v) {
			L = mid + 1
		} else {
			R = mid
		}
	}
	return R
}

func UpperBound(seq ComparableList, v Comparable) int32 {
	L := int32(0)
	R := seq.Len() - 1
	if R < 0 || seq.ILoc(R).Less(v) || !v.Less(seq.ILoc(R)) {
		return R + 1
	}
	for L < R {
		mid := L + (R-L)>>1
		if seq.ILoc(mid).Less(v) || !v.Less(seq.ILoc(mid)) {
			L = mid + 1
		} else {
			R = mid
		}
	}
	return R
}

func (s Seq) ILoc(index int32) Comparable {
	return s[index]
}

func (s Seq) Len() int32 {
	return int32(len(s))
}

func (a pair) Less(B interface{}) bool {
	fl := true
	rev := true
	b := B.(pair)
	if rk[a.l] > rk[b.l] {
		a, b = b, a
		fl = !fl
		rev = false
	}
	Lcp := GetLcp(int16(rk[a.l]), int16(rk[b.l]))
	if a.l > b.l {
		a, b = b, a
		fl = !fl
	}
	if a.r-a.l < Lcp || b.r-b.l < Lcp {
		rev = a.r-a.l < b.r-b.l
		return (fl && rev) || (!fl && !rev)
	} else {
		return rev
	}
}

func num_sort() {
	memset(unsafe.Pointer(&sorta), 0, uintptr(8*charsize+8))
	for i := 0; i < n; i++ {
		sorta[sort1[i]]++
	}
	for i := 1; i < charsize; i++ {
		sorta[i] += sorta[i-1]
	}
	for i := 0; i < n; i++ {
		sorta[sort1[i]]--
		sa[sorta[sort1[i]]] = i
	}
}

func SA() {
	for k := 1; k < n; k <<= 1 {
		rks := -1
		for i := n - 1; i >= n-k; i-- {
			rks++
			sort2[rks] = i
		}
		for i := 0; i < n; i++ {
			if sa[i] >= k {
				rks++
				sort2[rks] = sa[i] - k
			}
		}
		memset(unsafe.Pointer(&sorta), 0, uintptr(8*charsize+8))
		for i := 0; i < n; i++ {
			sorta[sort1[i]]++
		}
		for i := 1; i < charsize; i++ {
			sorta[i] += sorta[i-1]
		}
		for i := n - 1; i >= 0; i-- {
			sorta[sort1[sort2[i]]]--
			if sorta[sort1[sort2[i]]] < 0 {
				n = len(ss)
			}
			sa[sorta[sort1[sort2[i]]]] = sort2[i]
		}
		for i := 0; i < n; i++ {
			sort2[i] = sort1[i]
		}
		sort1[sa[0]] = 0
		rks = 1
		for i := 1; i < n; i++ {
			sort1[sa[i]] = sort1[sa[i-1]]
			if !(sort2[sa[i]] == sort2[sa[i-1]] && sa[i]+k < n && sa[i-1]+k < n && sort2[sa[i]+k] == sort2[sa[i-1]+k]) {
				sort1[sa[i]]++
				rks++
			}
		}
		if rks == n {
			break
		}
	}
}

func lcp() {
	k := 0
	for i := 0; i < n; i++ {
		if k != 0 {
			k--
		}
		j := 0
		if rk[i] > 0 {
			j = sa[rk[i]-1]
		} else {
			lcps[0] = 0
			continue
		}
		for i+k < n && j+k < n && ss[i+k] == ss[j+k] {
			k++
		}
		lcps[rk[i]] = k
	}
}

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

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

func ST() {
	for i := 0; i < n; i++ {
		sts[0][i] = lcps[i]
	}
	for i := 1; (1 << i) <= n; i++ {
		for j := 0; j <= n-(1<<i); j++ {
			sts[i][j] = min(sts[i-1][j], sts[i-1][j+(1<<(i-1))])
		}
	}
}

func QuMin(L, R interface{}) int16 {
	l := L.(int16)
	r := R.(int16)
	lg := lg2[r-l+1]
	return int16(min(sts[lg][l], sts[lg][r-(1<<lg)+1]))
}

func GetLcp(l, r int16) int16 {
	if l == r {
		return int16(n - sa[l])
	} else {
		if l > r {
			l, r = r, l
		}
		return QuMin(l+1, r)
	}
}

func main() {
	fmt.Scan(&t)
	for i := 2; i < N; i++ {
		lg2[i] = lg2[i>>1] + 1
	}
	for t != 0 {
		t--
		fmt.Scan(&n, &ss)
		//ss = "a"
		//for i := 0; i < 12; i++ {
		//	ss = ss + ss
		//}
		//n = len(ss)
		if n > 257 {
			charsize = n
		} else {
			charsize = 257
		}
		for i := 0; i < n; i++ {
			sort1[i] = int(ss[i])
		}
		num_sort()
		SA()
		for i := 0; i < n; i++ {
			rk[sa[i]] = i
		}
		lcp()
		ST()
		co := n
		ff[0] = n
		for i := 1; i < n; i++ {
			ff[i] = n - i
			for j := 0; j < i; j++ {
				Lcp := int(GetLcp(int16(rk[i]), int16(rk[j])))
				if rk[i] > rk[j] {
					ff[i] = max(ff[i], ff[j]+n-i-Lcp)
				}
			}
			co = max(co, ff[i])
		}
		fmt.Println(co)
	}
}


Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.Each test case consists of an integer $$$n$$$ and two arrays $$$a$$$ and $$$b$$$, of size $$$n$$$. If after some (possibly zero) operations described below, array $$$a$$$ can be transformed into array $$$b$$$, the input is said to be valid. Otherwise, it is invalid.An operation on array $$$a$$$ is:   select an integer $$$k$$$ $$$(1 \le k \le \lfloor\frac{n}{2}\rfloor)$$$  swap the prefix of length $$$k$$$ with the suffix of length $$$k$$$ For example, if array $$$a$$$ initially is $$$\{1, 2, 3, 4, 5, 6\}$$$, after performing an operation with $$$k = 2$$$, it is transformed into $$$\{5, 6, 3, 4, 1, 2\}$$$.Given the set of test cases, help them determine if each one is valid or invalid.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 500)$$$ — the number of test cases. The description of each test case is as follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — elements of array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le 10^9)$$$ — elements of array $$$b$$$.

For each test case, print "Yes" if the given input is valid. Otherwise print "No". You may print the answer in any case.

NoteFor the first test case, we can swap prefix $$$a[1:1]$$$ with suffix $$$a[2:2]$$$ to get $$$a=[2, 1]$$$.For the second test case, $$$a$$$ is already equal to $$$b$$$.For the third test case, it is impossible since we cannot obtain $$$3$$$ in $$$a$$$.For the fourth test case, we can first swap prefix $$$a[1:1]$$$ with suffix $$$a[4:4]$$$ to obtain $$$a=[2, 2, 3, 1]$$$. Now we can swap prefix $$$a[1:2]$$$ with suffix $$$a[3:4]$$$ to obtain $$$a=[3, 1, 2, 2]$$$.For the fifth test case, it is impossible to convert $$$a$$$ to $$$b$$$.

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)
		B := readNNums(reader, n)

		res := solve(n, A, B)

		if res {
			fmt.Println("Yes")
		} else {
			fmt.Println("No")
		}
	}
}

func solve(n int, A []int, B []int) bool {
	if n%2 == 1 {
		if A[n/2] != B[n/2] {
			return false
		}
	}

	cnt := make(map[Pair]int)

	for i := 0; i < n; i++ {
		a := Pair{min(A[i], A[n-1-i]), max(A[i], A[n-1-i])}
		cnt[a]++
		b := Pair{min(B[i], B[n-1-i]), max(B[i], B[n-1-i])}
		cnt[b]--
	}

	for _, v := range cnt {
		if v != 0 {
			return false
		}
	}

	return true
}

type Pair struct {
	first, second int
}

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

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

package main

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

type node struct {
	diff int
	time int
}

type ByTime []node

func (a ByTime) Len() int           { return len(a) }
func (a ByTime) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByTime) Less(i, j int) bool { return a[i].time < a[j].time }

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	t := int64(1)
	fmt.Fscanf(in, "%d\n", &t)
	for tt := int64(0); tt < t; tt++ {
		n := 0
		fmt.Fscanf(in, "%d\n", &n)
		a, b := make([]int, n), make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &a[i])
		}
		fmt.Fscanf(in, "\n")
		for i := 0; i < n; i++ {
			fmt.Fscanf(in, "%d", &b[i])
		}
		fmt.Fscanf(in, "\n")
		if n%2 == 1 {
			if a[n/2] != b[n/2] {
				fmt.Fprintf(out, "No\n")
				continue
			}
		}
		left := 0
		right := 0
		used := make([]bool, n)
		if n%2 == 0 {
			left = n/2 - 1
			right = left + 1
		} else {
			left = n/2 - 1
			right = left + 2
		}
		ok := true
		for left >= 0 {
			found := false
			for i := 0; i < n/2; i++ {
				x := i
				y := n - 1 - x
				if !used[i] {
					if a[x] == b[left] && a[y] == b[right] || a[x] == b[right] && a[y] == b[left] {
						used[i] = true
						found = true
						break
					}
				}
			}
			if !found {
				ok = false
				break
			}
			left--
			right++
		}
		if ok {
			fmt.Fprintf(out, "Yes\n")
		} else {
			fmt.Fprintf(out, "No\n")
		}
	}
	return
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)

	buff := make([]byte, 2 * 1024 * 1024)

	scanner.Buffer(buff, 1024 * 1024)

	scanner.Scan()

	t := scanner.Text()

	testCases, err := strconv.Atoi(t)

	if err != nil {
		panic(err)
	}

	for j := 0; j < int(testCases); j ++ {

		scanner.Scan()

		N := scanner.Text()

		n, _  := strconv.Atoi(N)

		var a []int
		var b []int

		scanner.Scan()

		aas := scanner.Text()

		ps := strings.Fields(aas)

		scanner.Scan()

		bbs := scanner.Text()

		bps := strings.Fields(bbs)

		for i:= 0; i < n; i++ {
			v1, _ := strconv.Atoi(ps[i])

			a = append(a, v1)

			v2, _ := strconv.Atoi(bps[i])

			b = append(b, v2)
		}

		fmt.Println(solve3(a, b))
	}
}

func solve3(a,b []int) string {
	if len(a) != len(b) {
		return "No"
	}
	if len(a) % 2 == 0 {
		if checkEven(a, b) {
			return "Yes"
		} else {
			return "No"
		}
	} else {
		if checkEven(a, b) && checkMiddle(a, b) {
			return "Yes"
		} else {
			return "No"
		}
	}
}

func checkEven(a, b []int) bool {
	//1 2 3 4 5 6
	//2 6 3 4 1 5

	mp := make(map[[2]int]int)
	n := len(a)

	for i:=0; i < n/2; i++ {
		opposite := a[n - i - 1]
		current := a[i]

		var max int
		var min int
		if current > opposite {
			max = current
			min = opposite
		} else {
			max = opposite
			min = current
		}
		mp[[2]int{max, min}]++
	}

	for i := 0; i < n/2; i++ {
		opposite := b[n - i - 1]
		current := b[i]

		var max int
		var min int
		if current > opposite {
			max = current
			min = opposite
		} else {
			max = opposite
			min = current
		}
		arr := [2]int{max, min}

		mp[arr]--
	}

	for _, v := range mp {
		if v != 0 {
			return false
		}
	}

	return true
}

func checkMiddle(a, b []int) bool {
	return a[len(a) / 2] == b[len(b) / 2]
}

package main

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

func main() {
	defer out.Flush()

	var t int
	for scan(&t); t > 0; t-- {
		var n int
		scan(&n)
		a := make([]int, n)
		b := make([]int, n)
		aPairs := make(map[int][]int)
		bPairs := make(map[int][]int)
		for i := range a {
			scan(&a[i])
		}
		for i := range b {
			scan(&b[i])
		}
		for i := range a {
			aPairs[a[i]] = append(aPairs[a[i]], a[n-1-i])
		}
		for i := range b {
			bPairs[b[i]] = append(bPairs[b[i]], b[n-1-i])
		}
		bad := false
		for key, aValue := range aPairs {
			if bValue, ok := bPairs[key]; ok {
				sort.Ints(aValue)
				sort.Ints(bValue)
				if len(aValue) != len(bValue) {
					bad = true
				} else {
					for i, a := range aValue {
						if a != bValue[i] {
							bad = true
							break
						}
					}
				}
			} else {
				bad = true
			}
			if bad {
				break
			}
		}
		if bad {
			println("No")
		} else {
			println("Yes")
		}
	}
}

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

func scan(x ...interface{}) (n int, err error) {
	return fmt.Fscan(in, x...)
}
func println(x ...interface{}) (n int, err error) {
	return fmt.Fprintln(out, x...)
}


Bakry faced a problem, but since he's lazy to solve it, he asks for your help.You are given a tree of $$$n$$$ nodes, the $$$i$$$-th node has value $$$a_i$$$ assigned to it for each $$$i$$$ from $$$1$$$ to $$$n$$$. As a reminder, a tree on $$$n$$$ nodes is a connected graph with $$$n-1$$$ edges.You want to delete at least $$$1$$$, but at most $$$k-1$$$ edges from the tree, so that the following condition would hold:For every connected component calculate the bitwise XOR of the values of the nodes in it. Then, these values have to be the same for all connected components.Is it possible to achieve this condition?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 5 \cdot 10^4)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ $$$(2 \leq k \leq n \leq 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ..., a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i\neq v_i$$$), which means that there's an edge between nodes $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, you should output a single string. If you can delete the edges according to the conditions written above, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteIt can be shown that the objection is not achievable for first, third, and fifth test cases.In the second test case, you can just remove all the edges. There will be $$$5$$$ connected components, each containing only one node with value $$$3$$$, so the bitwise XORs will be $$$3$$$ for all of them.In the fourth test case, this is the tree: .You can remove an edge $$$(4,5)$$$The bitwise XOR of the first component will be, $$$a_1 \oplus a_2 \oplus a_3 \oplus a_4 = 1 \oplus 6 \oplus 4 \oplus 1 = 2$$$ (where $$$\oplus$$$ denotes the bitwise XOR). The bitwise XOR of the second component will be, $$$a_5 = 2$$$.

package main

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

const MOD int64 = 1000000007

var n, k int

var a []int

var gr [][]int

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &n, &k)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &a[j])
		}

		gr = make([][]int, n + 1)

		for j := 0; j < n - 1; j++ {
			var u, v int
			fmt.Fscan(read, &u, &v)
			u--
			v--

			gr[u] = append(gr[u], v)
			gr[v] = append(gr[v], u)
		}

		fmt.Println(solve())
	}
}

func solve() string {

	cnt = 0

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

	if v == 0 {
		return "YES"
	}

	dfs(0, -1, v)

	if cnt >= 2 && cnt <= k - 1 {
		return "YES"
	}
	return "NO"
}

var cnt int

func dfs(v, p int, xor int) int {

	ch := gr[v]

	var x int

	var sons int

	for j := 0; j < len(ch); j++ {
		if ch[j] == p {
			continue
		}
		sons++
		a := dfs(ch[j], v, xor)

		if a == - 1 {
			return -1
		}

		x ^= a
	}

	if sons == 0  {
		if a[v] == xor {
			cnt++

			if cnt >= 2 {
				return -1
			}

			return 0
		}
		return a[v]
	}

	x ^= a[v]

	if x == xor {
		cnt++
	}
	if cnt >= 2 {
		return -1
	}

	if x == xor {
		return 0
	}

	return x
}

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

type treenode struct {
	node, subtreeSize, subtreeXor int
}

func solve() {
	var n, k int
	scan(&n, &k)
	a := make([]int, n)
	for i := range a {
		scan(&a[i])
	}
	adj := make([][]int, n)
	for i := 0; i < n-1; i++ {
		u, v := -1, -1
		scan(&u, &v)
		adj[u-1] = append(adj[u-1], v-1)
		adj[v-1] = append(adj[v-1], u-1)
	}

	tree := maketree(a, adj)
	if tree[0].subtreeXor == 0 {
		printf("YES\n")
		return
	}
	if k == 2 {
		printf("NO\n")
		return
	}
	xorcnt := makePrefixSums(tree, tree[0].subtreeXor)
	zerocnt := makePrefixSums(tree, 0)
	for i := 1; i < n; i++ {
		if tree[i].subtreeXor == tree[0].subtreeXor &&
			(xorcnt[n-1]-xorcnt[i+tree[i].subtreeSize-1] > 0 || zerocnt[i-1]-zerocnt[0] > 0) {
			printf("YES\n")
			return
		}
	}
	printf("NO\n")
}

func makePrefixSums(tree []treenode, x int) []int {
	pref := make([]int, len(tree))
	if tree[0].subtreeXor == x {
		pref[0] = 1
	}
	for i := 1; i < len(tree); i++ {
		pref[i] = pref[i-1]
		if tree[i].subtreeXor == x {
			pref[i]++
		}
	}
	return pref
}

func maketree(xor []int, adj [][]int) []treenode {
	tree := make([]treenode, 0, len(adj))

	var globalnum int
	var dfs func(int, int) treenode

	dfs = func(curr, prev int) treenode {
		tree = append(tree, treenode{
			node:        curr,
			subtreeSize: 1,
			subtreeXor:  xor[curr],
		})
		idx := len(tree) - 1
		globalnum++
		for _, next := range adj[curr] {
			if next != prev {
				tr := dfs(next, curr)
				tree[idx].subtreeSize += tr.subtreeSize
				tree[idx].subtreeXor ^= tr.subtreeXor
			}
		}
		return tree[idx]
	}
	dfs(0, -1)

	return tree
}

package main

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

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

	var T, n, k, v, w int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &k)
		xor := 0
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
			xor ^= a[i]
		}
		g := make([][]int, n)
		for i := 1; i < n; i++ {
			Fscan(in, &v, &w)
			v--
			w--
			g[v] = append(g[v], w)
			g[w] = append(g[w], v)
		}

		var f func(int, int) int
		f = func(v, fa int) (c int) {
			for _, w := range g[v] {
				if w != fa {
					c += f(w, v)
					a[v] ^= a[w]
				}
			}
			if c > 0 {
				if a[v] == 0 {
					c++
				}
			} else if a[v] == xor {
				c++
			}
			return
		}
		if xor == 0 || k > 2 && f(0, -1) > 1 {
			Fprintln(out, "YES")
		} else {
			Fprintln(out, "NO")
		}
	}
}

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

package main

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

const MOD int64 = 1000000007

var n, k int

var a []int

var gr [][]int

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &n, &k)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &a[j])
		}

		gr = make([][]int, n + 1)

		for j := 0; j < n - 1; j++ {
			var u, v int
			fmt.Fscan(read, &u, &v)
			u--
			v--

			gr[u] = append(gr[u], v)
			gr[v] = append(gr[v], u)
		}

		fmt.Println(solve())
	}
}

func solve() string {

	cnt = 0

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

	if v == 0 {
		return "YES"
	}

	dfs(0, -1, v)

	if cnt >= 2 && cnt <= k - 1 {
		return "YES"
	}
	return "NO"
}

var cnt int

func dfs(v, p int, xor int) int {

	ch := gr[v]

	var x int

	var sons int

	for j := 0; j < len(ch); j++ {
		if ch[j] == p {
			continue
		}
		sons++
		a := dfs(ch[j], v, xor)

		if a == - 1 {
			return -1
		}

		x ^= a
	}

	if sons == 0  {
		if a[v] == xor {
			cnt++

			if cnt >= 2 {
				return -1
			}

			return 0
		}
		return a[v]
	}

	x ^= a[v]

	if x == xor {
		cnt++
		return 0
	}
	if cnt >= 2 {
		return -1
	}

	return x
}

package main

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

const MOD int64 = 1000000007

var n, k int

var a []int

var gr [][]int

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &n, &k)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &a[j])
		}

		gr = make([][]int, n + 1)

		for j := 0; j < n - 1; j++ {
			var u, v int
			fmt.Fscan(read, &u, &v)
			u--
			v--

			gr[u] = append(gr[u], v)
			gr[v] = append(gr[v], u)
		}

		fmt.Println(solve())
	}
}

func solve() string {

	cnt = 0

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

	if v == 0 {
		return "YES"
	}

	dfs(0, -1, v)

	if cnt >= 2 && cnt <= k - 1 {
		return "YES"
	}
	return "NO"
}

var cnt int

func dfs(v, p int, xor int) int {

	ch := gr[v]

	var x int

	var sons int

	for j := 0; j < len(ch); j++ {
		if ch[j] == p {
			continue
		}
		sons++
		a := dfs(ch[j], v, xor)

		if a == - 1 {
			return -1
		}

		x ^= a
	}

	if sons == 0  {
		if a[v] == xor {
			cnt++

			if cnt >= 2 {
				return -1
			}

			return 0
		}
		return a[v]
	}

	x ^= a[v]

	if x == xor {
		cnt++
	}
	if cnt >= 2 {
		return -1
	}

	return x
}

package main

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

const MOD int64 = 1000000007

var n, k int

var a []int

var gr [][]int

func main() {

	read := bufio.NewReader(os.Stdin)

	var t int
	fmt.Fscan(read, &t)

	for i := 0; i < t; i++ {

		fmt.Fscan(read, &n, &k)

		a = make([]int, n)

		for j := 0; j < n; j++ {
			fmt.Fscan(read, &a[j])
		}

		gr = make([][]int, n + 1)

		for j := 0; j < n - 1; j++ {
			var u, v int
			fmt.Fscan(read, &u, &v)
			u--
			v--

			gr[u] = append(gr[u], v)
			gr[v] = append(gr[v], u)
		}

		fmt.Println(solve())
	}
}

func solve() string {

	cnt = 0

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

	if v == 0 {
		return "YES"
	}

	dfs(0, -1, v)

	if cnt >= 2 && cnt <= k - 1 {
		return "YES"
	}
	return "NO"
}

var cnt int

func dfs(v, p int, xor int) int {

	ch := gr[v]

	var x int

	var sons int

	for j := 0; j < len(ch); j++ {
		if ch[j] == p {
			continue
		}
		sons++
		a := dfs(ch[j], v, xor)

		if a == - 1 {
			return -1
		}

		x ^= a
	}

	if sons == 0  {
		if a[v] == xor {
			cnt++

			if cnt >= 2 {
				return -1
			}
		}
		return 0
	}

	x ^= a[v]

	if x == xor {
		cnt++
	}
	if cnt >= 2 {
		return -1
	}

	return x
}

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

type treenode struct {
	node, subtreeSize, subtreeXor int
}

func solve() {
	var n, k int
	scan(&n, &k)
	a := make([]int, n)
	for i := range a {
		scan(&a[i])
	}
	adj := make([][]int, n)
	for i := 0; i < n-1; i++ {
		u, v := -1, -1
		scan(&u, &v)
		adj[u-1] = append(adj[u-1], v-1)
		adj[v-1] = append(adj[v-1], u-1)
	}

	tree := maketree(a, adj)
	if tree[0].subtreeXor == 0 {
		printf("YES\n")
		return
	}
	if k == 2 {
		printf("NO\n")
		return
	}
	prefXorCnt := make([]int, n)
	prefXorCnt[0] = 1
	for i := 1; i < n; i++ {
		prefXorCnt[i] = prefXorCnt[i-1]
		if tree[i].subtreeXor == tree[0].subtreeXor {
			prefXorCnt[i]++
		}
	}
	for i := 1; i < n; i++ {
		if tree[i].subtreeXor == tree[0].subtreeXor &&
			prefXorCnt[n-1]-prefXorCnt[i+tree[i].subtreeSize-1] > 0 {
			printf("YES\n")
			return
		}
	}
	printf("NO\n")
}

func maketree(xor []int, adj [][]int) []treenode {
	tree := make([]treenode, 0, len(adj))

	var globalnum int
	var dfs func(int, int) treenode

	dfs = func(curr, prev int) treenode {
		tree = append(tree, treenode{
			node:        curr,
			subtreeSize: 1,
			subtreeXor:  xor[curr],
		})
		idx := len(tree) - 1
		globalnum++
		for _, next := range adj[curr] {
			if next != prev {
				tr := dfs(next, curr)
				tree[idx].subtreeSize += tr.subtreeSize
				tree[idx].subtreeXor ^= tr.subtreeXor
			}
		}
		return tree[idx]
	}
	dfs(0, -1)

	return tree
}

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

type treenode struct {
	node, subtreeSize, subtreeXor int
}

func solve() {
	var n, k int
	scan(&n, &k)
	a := make([]int, n)
	for i := range a {
		scan(&a[i])
	}
	adj := make([][]int, n)
	for i := 0; i < n-1; i++ {
		u, v := -1, -1
		scan(&u, &v)
		adj[u-1] = append(adj[u-1], v-1)
		adj[v-1] = append(adj[v-1], u-1)
	}

	tree := maketree(a, adj)
	if tree[0].subtreeXor == 0 {
		printf("YES\n")
		return
	}
	if k == 2 {
		printf("NO\n")
		return
	}
	prefXorCnt := make([]int, n)
	prefXorCnt[0] = 1
	for i := 1; i < n; i++ {
		prefXorCnt[i] = prefXorCnt[i-1]
		if tree[i].subtreeXor == tree[0].subtreeXor {
			prefXorCnt[i]++
		}
	}
	for i := 1; i < n; i++ {
		if tree[i].subtreeXor == tree[0].subtreeXor &&
			prefXorCnt[n-1]-prefXorCnt[i+tree[i].subtreeSize-1] > 0 {
			printf("YES\n")
			return
		}
	}
	printf("NO\n")
}

func maketree(a []int, adj [][]int) []treenode {
	tree := make([]treenode, 0, len(adj))

	var globalnum int
	var dfs func(int, int) treenode

	dfs = func(curr, prev int) treenode {
		tree = append(tree, treenode{
			node:        globalnum,
			subtreeSize: 1,
			subtreeXor:  a[globalnum],
		})
		idx := len(tree) - 1
		globalnum++
		for _, next := range adj[curr] {
			if next != prev {
				tr := dfs(next, curr)
				tree[idx].subtreeSize += tr.subtreeSize
				tree[idx].subtreeXor ^= tr.subtreeXor
			}
		}
		return tree[idx]
	}
	dfs(0, -1)

	return tree
}


You have an array of integers (initially empty).You have to perform $$$q$$$ queries. Each query is of one of two types:   "$$$1$$$ $$$x$$$" — add the element $$$x$$$ to the end of the array;  "$$$2$$$ $$$x$$$ $$$y$$$" — replace all occurrences of $$$x$$$ in the array with $$$y$$$. Find the resulting array after performing all the queries.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) — the number of queries. Next $$$q$$$ lines contain queries (one per line). Each query is of one of two types:    "$$$1$$$ $$$x$$$" ($$$1 \le x \le 5 \cdot 10^5$$$);  "$$$2$$$ $$$x$$$ $$$y$$$" ($$$1 \le x, y \le 5 \cdot 10^5$$$).  It's guaranteed that there is at least one query of the first type.

In a single line, print $$$k$$$ integers — the resulting array after performing all the queries, where $$$k$$$ is the number of queries of the first type.

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 int
	scan(&n)
	var qs = make([][3]int, n)
	for i := range qs {
		scan(&qs[i][0], &qs[i][1])
		if qs[i][0] == 2 {
			scan(&qs[i][2])
		}
	}
	var (
		N   = 0
		pos = [5e5 + 1][]int{}
	)
	for _, q := range qs {
		typ, x, y := q[0], q[1], q[2]
		if typ == 1 {
			pos[x] = append(pos[x], N)
			N++
		} else if x != y {
			if len(pos[x]) > len(pos[y]) {
				pos[x], pos[y] = pos[y], pos[x]
			}
			pos[y] = append(pos[y], pos[x]...)
			pos[x] = pos[x][:0:0]
		}
	}
	var ans = make([]int, N)
	for x := 1; x <= 5e5; x++ {
		for _, i := range pos[x] {
			ans[i] = x
		}
	}
	for _, i := range ans {
		printf("%v ", i)
	}
}

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 int
	scan(&n)
	var qs = make([][3]int, n)
	for i := range qs {
		scan(&qs[i][0], &qs[i][1])
		if qs[i][0] == 2 {
			scan(&qs[i][2])
		}
	}
	var (
		N   = 0
		pos = [5e5 + 1][]int{}
	)
	for _, q := range qs {
		typ, x, y := q[0], q[1], q[2]
		if typ == 1 {
			pos[x] = append(pos[x], N)
			N++
		} else if x != y {
			if len(pos[x]) > len(pos[y]) {
				pos[x], pos[y] = pos[y], pos[x]
			}
			pos[y] = append(pos[y], pos[x]...)
			pos[x] = pos[x][:0]
		}
	}
	var ans = make([]int, N)
	for x := 1; x <= 5e5; x++ {
		for _, i := range pos[x] {
			ans[i] = x
		}
	}
	for _, i := range ans {
		printf("%v ", i)
	}
}

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 int
	scan(&n)
	var qs = make([][3]int, n)
	for i := range qs {
		scan(&qs[i][0], &qs[i][1])
		if qs[i][0] == 2 {
			scan(&qs[i][2])
		}
	}
	var (
		arr            = make([][2]int, 0)
		numOf          = make(map[int]int)
		transformsInto = make(map[[2]int][2]int)
	)
	for _, q := range qs {
		typ, x, y := q[0], q[1], q[2]
		if typ == 1 {
			arr = append(arr, [2]int{x, numOf[x]})
		} else if x != y {
			transformsInto[[2]int{x, numOf[x]}] = [2]int{y, numOf[y]}
			numOf[x]++
		}
	}
	var walk func(curr [2]int) [2]int
	walk = func(curr [2]int) [2]int {
		if _, ok := transformsInto[curr]; !ok || transformsInto[curr] == curr {
			transformsInto[curr] = curr
		} else {
			transformsInto[curr] = walk(transformsInto[curr])
		}
		return transformsInto[curr]
	}
	for _, i := range arr {
		walk(i)
		printf("%v ", transformsInto[i][0])
	}
	printf("\n")
}

package main

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

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

	var q, op int
	Fscan(in, &q)
	type pair struct{ x, y int }
	qs := make([]pair, q)
	for i := range qs {
		Fscan(in, &op, &qs[i].x)
		if op == 2 {
			Fscan(in, &qs[i].y)
		}
	}

	pa := [5e5 + 1]int{}
	ans := make([]int, 0, 5e5)
	for i := q - 1; i >= 0; i-- {
		x, y := qs[i].x, qs[i].y
		if y == 0 {
			if pa[x] > 0 {
				x = pa[x]
			}
			ans = append(ans, x)
		} else {
			if pa[y] > 0 {
				y = pa[y]
			}
			pa[x] = y
		}
	}
	for i := len(ans) - 1; i >= 0; i-- {
		Fprint(out, ans[i], " ")
	}
}

func main() { CF1620E(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 int
	scan(&n)
	var qs = make([][3]int, n)
	for i := range qs {
		scan(&qs[i][0], &qs[i][1])
		if qs[i][0] == 2 {
			scan(&qs[i][2])
		}
	}
	var (
		arr            = make([][2]int, 0)
		numOf          = make(map[int]int)
		transformsInto = make(map[[2]int][2]int)
	)
	for _, q := range qs {
		typ, x, y := q[0], q[1], q[2]
		if typ == 1 {
			arr = append(arr, [2]int{x, numOf[x]})
		} else {
			transformsInto[[2]int{x, numOf[x]}] = [2]int{y, numOf[y]}
			numOf[x]++
		}
	}
	var walk func(curr [2]int) [2]int
	walk = func(curr [2]int) [2]int {
		if _, ok := transformsInto[curr]; !ok || transformsInto[curr] == curr {
			transformsInto[curr] = curr
		} else {
			transformsInto[curr] = walk(transformsInto[curr])
		}
		return transformsInto[curr]
	}
	for _, i := range arr {
		walk(i)
		printf("%v ", transformsInto[i][0])
	}
	printf("\n")
}


You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.

The first line contains three space-separated integers n (1 ≤ n ≤ 103), k1 and k2 (0 ≤ k1 + k2 ≤ 103, k1 and k2 are non-negative) — size of arrays and number of operations to perform on A and B respectively. Second line contains n space separated integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — array A. Third line contains n space separated integers b1, b2, ..., bn ( - 106 ≤ bi ≤ 106)— array B.

Output a single integer — the minimum possible value of  after doing exactly k1 operations on array A and exactly k2 operations on array B.

NoteIn the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)2 + (2 - 3)2 = 2. In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)2 + (2 - 2)2 = 0. This is the minimum possible error obtainable.In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)2 + (4 - 4)2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8, 5] and E = (8 - 8)2 + (4 - 5)2 = 1.

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

type IntHeap []int64

func (h IntHeap) Len() int            { return len(h) }
func (h IntHeap) Less(i, j int) bool  { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int64)) }
func (h *IntHeap) Pop() interface{}   { r := (*h)[len(*h)-1]; *h = (*h)[:len(*h)-1]; return r }

var in = bufio.NewScanner(os.Stdin)

func nextInt() int64 {
	in.Scan()
	var r, f int64
	r, f = 0, 1
	for _, c := range in.Bytes() {
		if c == '-' {
			f = -1
			continue
		}
		r *= 10
		r += int64(c - '0')
	}
	return r * f
}

func main() {
	in.Split(bufio.ScanWords)
	n, k := nextInt(), nextInt()+nextInt()
	a := make(IntHeap, n)
	for i := range a {
		a[i] = nextInt()
	}
	for i := range a {
		a[i] -= nextInt()
		if a[i] < 0 {
			a[i] = -a[i]
		}
	}
	heap.Init(&a)
	for ; k > 0; k-- {
		v := heap.Pop(&a).(int64)
		if v == 0 {
			if k%2 == 0 {
				fmt.Println(0)
			} else {
				fmt.Println(1)
			}
			return
		}
		heap.Push(&a, v-1)
	}
	var r int64
	for len(a) > 0 {
		v := heap.Pop(&a).(int64)
		r += v * v
	}
	fmt.Println(r)
}

package main

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

type AB struct {
	a int
	b int
}

func solve() {
	n := readInt()
	k1 := readInt()
	k2 := readInt()
	a := readIntArray(n)
	b := readIntArray(n)
	heap := NewMinHeap(n)
	for i := 0; i < n; i++ {
		heap.Add(i, -abs(a[i]-b[i]))
	}
	for k1 > 0 || k2 > 0 {
		ind := heap.ArgMin()
		f := a[ind]
		v := b[ind]
		if f > v {
			if k1 > 0 {
				f--
				k1--
			} else if k2 > 0 {
				v++
				k2--
			}
		} else if v > f {
			if k1 > 0 {
				f++
				k1--
			} else if k2 > 0 {
				v--
				k2--
			}
		} else {
			if k1 > 0 {
				f++
				k1--
			} else if k2 > 0 {
				v--
				k2--
			}
		}
		a[ind] = f
		b[ind] = v

		heap.Update(ind, -abs(f-v))
	}
	total := int64(0)
	for i := 0; i < n; i++ {
		total += int64(a[i]-b[i]) * int64(a[i]-b[i])
	}
	fmt.Println(total)
}

type MinHeap struct {
	a    []int
	vmap []int
	imap []int
	n    int
	pos  int
}

const INF = math.MaxInt32

func NewMinHeap(m int) *MinHeap {
	heap := &MinHeap{}
	m += 2
	heap.n = m
	heap.a = make([]int, heap.n)
	heap.vmap = make([]int, heap.n)
	heap.imap = make([]int, heap.n)
	heap.pos = 1
	for i := 0; i < heap.n; i++ {
		heap.a[i] = INF
		heap.vmap[i] = -1
		heap.imap[i] = -1
	}
	return heap
}

func (h *MinHeap) Add(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	}
	if ret != -1 {
		return h.a[ret]
	}
	return x
}

func (h *MinHeap) Update(ind, x int) int {
	ret := h.imap[ind]
	if h.imap[ind] < 0 {
		h.a[h.pos] = x
		h.vmap[h.pos] = ind
		h.imap[ind] = h.pos
		h.pos++
		h.up(h.pos - 1)
	} else {
		h.a[ret] = x
		h.up(ret)
		h.down(ret)
	}
	return x
}

func (h *MinHeap) Remove(ind int) int {
	if h.pos == 1 {
		return INF
	}
	if h.imap[ind] == -1 {
		return INF
	}

	h.pos--
	rem := h.imap[ind]
	ret := h.a[rem]
	h.vmap[rem] = h.vmap[h.pos]
	h.imap[h.vmap[h.pos]] = rem
	h.imap[ind] = -1
	h.a[rem] = h.a[h.pos]
	h.a[h.pos] = INF
	h.vmap[h.pos] = -1

	h.up(rem)
	h.down(rem)
	return ret
}

func (h *MinHeap) Min() int {
	return h.a[1]
}

func (h *MinHeap) ArgMin() int {
	return h.vmap[1]
}

func (h *MinHeap) Size() int {
	return h.pos - 1
}

func (h *MinHeap) up(cur int) {
	for c, p := cur, cur>>1; p >= 1 && h.a[p] > h.a[c]; c, p = c>>1, p>>1 {
		h.a[p], h.a[c] = h.a[c], h.a[p]
		h.imap[h.vmap[p]], h.imap[h.vmap[c]] = h.imap[h.vmap[c]], h.imap[h.vmap[p]]
		h.vmap[p], h.vmap[c] = h.vmap[c], h.vmap[p]
	}
}

func (h *MinHeap) down(cur int) {
	for c := cur; 2*c < h.pos; {
		b := 0
		if h.a[2*c] < h.a[2*c+1] {
			b = 2 * c
		} else {
			b = 2*c + 1
		}
		if h.a[b] < h.a[c] {
			h.a[c], h.a[b] = h.a[b], h.a[c]
			h.imap[h.vmap[c]], h.imap[h.vmap[b]] = h.imap[h.vmap[b]], h.imap[h.vmap[c]]
			h.vmap[c], h.vmap[b] = h.vmap[b], h.vmap[c]
			c = b
		} else {
			break
		}
	}
}

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

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

var scanner *bufio.Scanner

func main() {
	scanner = bufio.NewScanner(os.Stdin)
	const MaxTokenLength = 1024 * 1024
	scanner.Buffer(make([]byte, 0, MaxTokenLength), MaxTokenLength)
	scanner.Split(bufio.ScanWords)
	solve()
}

// IO

func readString() string {
	scanner.Scan()
	return scanner.Text()
}

func readInt() int {
	val, _ := strconv.Atoi(readString())
	return val
}

func readInt64() int64 {
	v, _ := strconv.ParseInt(readString(), 10, 64)
	return v
}

func readIntArray(sz int) []int {
	a := make([]int, sz)
	for i := 0; i < sz; i++ {
		a[i] = readInt()
	}
	return a
}

func readInt64Array(n int) []int64 {
	res := make([]int64, n)
	for i := 0; i < n; i++ {
		res[i] = readInt64()
	}
	return res
}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

// B problem B
type B struct {
	q     IntHeap
	total int
}

// An IntHeap is a max-heap of ints.
type IntHeap []int

func (h IntHeap) Len() int            { return len(h) }
func (h IntHeap) Less(i, j int) bool  { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

func (b *B) readInput() {
	inp := bufio.NewReader(os.Stdin)

	// read n
	var n, k1, k2, tmp int
	fmt.Fscanf(inp, "%d %d %d\n", &n, &k1, &k2)

	b.total = k1 + k2
	b.q = make(IntHeap, 0, n)

	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(inp, "%d", &a[i])
	}
	fmt.Fscanf(inp, "\n")
	for i := 0; i < n; i++ {
		fmt.Fscanf(inp, "%d", &tmp)
		if tmp = a[i] - tmp; tmp >= 0 {
			heap.Push(&b.q, tmp)
		} else {
			heap.Push(&b.q, -tmp)
		}
	}
}

func (b *B) solve() {
	total := b.total
	q := b.q

	for total > 0 {
		total--
		if q[0] > 0 {
			q[0]--
		} else {
			q[0]++
		}
		heap.Fix(&b.q, 0)
	}

	var sum int64
	for i := range q {
		sum += int64(q[i]) * int64(q[i])
	}
	fmt.Println(sum)
}

func main() {
	b := &B{}
	b.readInput()
	b.solve()
}

package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
)

type IntHeap []int

func (h IntHeap) Len() int            { return len(h) }
func (h IntHeap) Less(i, j int) bool  { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{}   { r := (*h)[len(*h)-1]; *h = (*h)[:len(*h)-1]; return r }

var in = bufio.NewScanner(os.Stdin)

func nextInt() int {
	in.Scan()
	r, f := 0, 1
	for _, c := range in.Bytes() {
		if c == '-' {
			f = -1
			continue
		}
		r *= 10
		r += int(c - '0')
	}
	return r * f
}

func main() {
	in.Split(bufio.ScanWords)
	n, k := nextInt(), nextInt()+nextInt()
	a := make(IntHeap, n)
	for i := range a {
		a[i] = nextInt()
	}
	for i := range a {
		a[i] -= nextInt()
		if a[i] < 0 {
			a[i] = -a[i]
		}
	}
	heap.Init(&a)
	for ; k > 0; k-- {
		v := heap.Pop(&a).(int)
		if v == 0 {
			if k%2 == 0 {
				fmt.Println(0)
			} else {
				fmt.Println(1)
			}
			return
		}
		heap.Push(&a, v-1)
	}
	r := 0
	for len(a) > 0 {
		v := heap.Pop(&a).(int)
		r += v * v
	}
	fmt.Println(r)
}