package main

import "fmt"

func drinkChoosing(sNum int, dNum int, sFav map[int]int) int {
	result := 0
	t := 0
	for _, v := range sFav {
		result += v - v % 2
		t += v % 2
	}
	result += t / 2 + t % 2
	return result
}

func main() {
	var sNum, dNum int

	_, err := fmt.Scanln(&sNum, &dNum)
	if err != nil {
		fmt.Println(err)
	}

	sFav := make(map[int]int)
	for k := 0; k < sNum; k++ {
		a := 0
		_, err := fmt.Scanln(&a)
		if err != nil {
			fmt.Println(err)
		}
		sFav[a] ++
	}
	result := drinkChoosing(sNum, dNum, sFav)
	fmt.Println(result)
}

package main

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

func main() {
	var read = bufio.NewReader(os.Stdin)
	var n, k int
	fmt.Fscan(read, &n, &k)
	var a = make([]int, k)
	for i := 0; i < n; i++ {
		var ai int
		fmt.Fscan(read, &ai)
		a[ai-1]++
	}
	var np int
	var n21 int
	for _, val := range a {
		if val%2 == 0 {
			np = np + val
		} else {
			np = np + val - 1
			n21 = n21 + 1
		}

	}
	if n21%2 == 1 {
		np = np + 1 + n21/2
	} else {
		np = np + n21/2
	}
	fmt.Print(np)
}

package main

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

func main() {
	var read = bufio.NewReader(os.Stdin)
	var n, k int
	fmt.Fscan(read, &n, &k)
	var a = make(map[int]int)
	for i := 0; i < n; i++ {
		var ai int
		fmt.Fscan(read, &ai)
		a[ai]++
	}
	var np int
	var n21 int
	for _, val := range a {
		if val%2 == 0 {
			np = np + val
		} else {
			np = np + val - 1
			n21 = n21 + 1
		}
	}
	if n21%2 == 1 {
		np = np + 1 + n21/2
	} else {
		np = np + n21/2
	}
	fmt.Print(np)
}

package main

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

/* solution */

func solve() {

	n, _ := readInt(), readInt()
	a := make([]int, n)

	for i := 0; i < n; i++ {
		a[i] = readInt()
	}

	sort.Ints(a)

	packs := 0
	remains := n/2 + n%2

	for i := 1; i < n; i++ {
		if a[i] == a[i-1] {
			packs++
			remains--
			i++
		}
	}

	printInt(packs*2 + remains)

}

/* stubs */

func main() {

	var f *os.File
	if runtime.GOROOT() == "C:\\Soft\\Go" {
		f, _ = os.Open("input.txt")
		defer f.Close()
	} else {
		f = os.Stdin
	}

	writer = bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	reader = bufio.NewScanner(f)

	const maxCapacity = 1024 * 1024
	buf := make([]byte, maxCapacity)
	reader.Buffer(buf, maxCapacity)

	reader.Split(bufio.ScanWords)

	solve()

}

var reader *bufio.Scanner
var writer *bufio.Writer

func read() string {
	reader.Scan()
	return reader.Text()
}

func readInt() int {
	reader.Scan()
	ret, _ := strconv.Atoi(reader.Text())
	return ret
}

func print(s string) {
	writer.WriteString(s)
	writer.WriteString("\n")
}

func printInt(i int) {
	print(strconv.Itoa(i))
}

func readInt64() int64 {
	reader.Scan()
	ret, _ := strconv.ParseInt(reader.Text(), 10, 64)
	return ret
}

package main

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

func main() {
	var n, k, res int
	// var a, b, c string

	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &n, &k)

	m := make(map[int]int)
	a := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscanln(scr, &a[i])
		m[a[i]]++
	}

	for _, y := range m {
		res += 2 * (y / 2)
	}

	res += int(math.Ceil(float64(n)/float64(2))) - (res / 2)

	fmt.Println(res)

}

package main

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

func main() {
	var n, k, d int
	var drinks [1010]int
	in := bufio.NewReader(os.Stdin)

	fmt.Fscan(in, &n)
	fmt.Fscan(in, &k)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &d)
		drinks[d-1] += 1
	}

	sort.Sort(sort.Reverse(sort.IntSlice(drinks[:k])))

	pair, alone := 0, 0
	for i := 0; i < k; i++ {
		pair += (drinks[i] / 2) * 2
		alone += drinks[i] % 2
	}
	fmt.Println(pair + alone/2 + alone%2)
}

package main

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

func main() {
	var n, k, d int
	var drinks [1010]int
	in := bufio.NewReader(os.Stdin)

	fmt.Fscan(in, &n)
	fmt.Fscan(in, &k)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &d)
		drinks[d-1] += 1
	}

	sort.Sort(sort.Reverse(sort.IntSlice(drinks[:k])))

	good, bad := 0, 0

	for i := 0; i < k; i++ {
		if drinks[i]%2 == 0 {
			good += drinks[i]
		} else {
			good += drinks[i] - 1
			bad += 1
		}
	}
	ans := good + bad/2
	if bad%2 != 0 {
		ans += 1
	}

	fmt.Println(ans)
}

package main

import "fmt"

func main() {
	var (
		stuNum int
		drkNum int
	)
	if _, err := fmt.Scanln(&stuNum, &drkNum); err != nil {

	}

	stuMap := make([]int, drkNum)
	for i := 0; i < stuNum; i += 1 {
		var fav int

		if _, err := fmt.Scanln(&fav); err != nil {
		}
		fav -= 1
		stuMap[fav] += 1
	}

	total := 0
	others := 0
	for i := 0; i < drkNum; i += 1 {
		if stuMap[i] % 2 == 0{
			total += stuMap[i]
		}else {
			total += stuMap[i] - 1
			others += 1
		}
	}
	total += others/2 + others%2
	fmt.Println(total)
}

// Copyright (C) 2017 Kazumasa Kohtaka <kkohtaka@gmail.com> All right reserved
// This file is available under the MIT license.

package main

import "fmt"

func main() {
	var n, k int
	fmt.Scanf("%d %d\n", &n, &k)
	a := make([]int, k)
	for i := 0; i < n; i++ {
		var j int
		fmt.Scanf("%d\n", &j)
		a[j-1]++
	}

	var flag bool
	var ans int
	for _, i := range a {
		if i%2 == 0 {
			ans += i
		} else if !flag {
			ans += i
			flag = true
		} else {
			ans += i - 1
			flag = false
		}
	}
	fmt.Println(ans)
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, k := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &k)
	a := make([]int, n)
	cnt := make(map[int]int)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d\n", &a[i])
		cnt[a[i]]++
	}
	pair := 0
	single := 0
	for _, v := range cnt {
		if v%2 == 0 {
			pair += v
		} else {
			pair += v - 1
			single++
		}
	}
	ans := pair + (single+1)/2
	fmt.Fprintf(out, "%d\n", ans)
	return
}
func minstep(a, b byte) int {
	return min(int(a-b+26)%26, int(b-a+26)%26)
}

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

package main

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

var inf int = 0x3f3f3f3f
var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n, k int
var a []int

func main() {
	fmt.Fscan(reader, &n, &k)
	a = make([]int, n)
	m := make(map[int]int)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		m[a[i]]++
	}
	ans := 0
	for i := (n + 1) / 2; i != 0; i-- {
		flag := false
		for k, v := range m {
			if v > 1 {
				m[k] -= 2
				ans += 2
				flag = true
				if m[k] == 0 {
					delete(m, k)
				}
				break
			}
		}
		if !flag {
			ans += Min(i, len(m))
			fmt.Println(ans)
			return
		}
	}
	fmt.Println(ans)
}

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

package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	arr := make([]int, k)
	res := 0
	for i := 0; i < n; i++ {
		var drink int
		fmt.Scan(&drink)
		arr[drink-1]++
	}
	single := 0
	for i := range arr {
		last_bit := arr[i] & 1
		res += arr[i] - last_bit
		single += last_bit
	}
	res += single/2 + (single & 1)
	fmt.Println(res)
}

package main

import (
    "fmt"
)

func main() {
    var n, k int
    fmt.Scan(&n, &k)
    cnt := make([]int, k)
    for i := 0; i < n; i++ {
        var x int
        fmt.Scan(&x)
        cnt[x - 1]++
    }
    c := (n + 1) / 2
    ans := 0
    for i := 0; i < k; i++ {
        x := cnt[i] / 2
        c -= x
        ans += 2 * x
    }
    for i := 0; i < k; i++ {
        if cnt[i] > 0 && c > 0 {
            ans++
            c--
        }
    }
    fmt.Println(ans)
}

// Author: sighduck
// URL: https://codeforces.com/contest/1195/problem/A

package main

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

func min(x int, y int) int {
	if x < y {
		return x
	}
	return y
}

func getSets(m map[int]int) (int, int) {
	completeSets := 0
	singleSets := 0
	for _, value := range m {
		completeSets += value / 2
		if value%2 == 1 {
			singleSets += 1
		}
	}
	return completeSets, singleSets
}

func Solve(n int, k int, a []int) int {
	count := make(map[int]int)
	for _, elem := range a {
		count[elem] += 1
	}
	sets := (n + 1) / 2
	completeSets, singleSets := getSets(count)
	students := min(sets, completeSets) * 2
	sets -= min(sets, completeSets)
	return students + min(sets, singleSets)
}

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

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

	fmt.Fprintf(writer, "%d\n", Solve(n, k, a))
}

package main

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

func main() {
	var n, k, res int
	// var a, b, c string

	scr := bufio.NewReader(os.Stdin)
	// ocr := bufio.NewWriter(os.Stdout)

	fmt.Fscanln(scr, &n, &k)

	m := make(map[int]int)
	a := make([]int, n)

	for i := 0; i < n; i++ {
		fmt.Fscanln(scr, &a[i])
		m[a[i]]++
	}

	for _, y := range m {
		res += 2 * (y / 2)
	}

	res += int(math.Ceil(float64(n/2))) - (res / 2)

	fmt.Println(res)

}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, k, d int
	var drinks [1010]int
	fmt.Scanf("%d %d\n", &n, &k)
	// fmt.Printf("n = %d, k = %d\n", n, k)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d\n", &d)
		drinks[d] += 1
	}

	// for i := 0; i < k; i++ {
	// 	fmt.Printf("%d ", drinks[i])
	// }
	// fmt.Println()

	sort.Sort(sort.Reverse(sort.IntSlice(drinks[:n])))

	// for i := 0; i < k; i++ {
	// 	fmt.Printf("%d ", drinks[i])
	// }
	// fmt.Println()

	var rem_drinks int
	if n%2 == 0 {
		rem_drinks = n / 2
	} else {
		rem_drinks = n/2 + 1
	}

	ans := 0

	for i := 0; i < k && rem_drinks > 0; i++ {
		if drinks[i] <= rem_drinks*2 {
			ans += drinks[i]
			if drinks[i]%2 == 0 {
				rem_drinks = rem_drinks - drinks[i]/2
			} else {
				rem_drinks = rem_drinks - drinks[i]/2 - 1
			}
		} else {
			ans += rem_drinks * 2
			rem_drinks = 0
		}
	}
	fmt.Printf("%d\n", ans)
}

package main

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

func main() {
	var n, k, d int
	var drinks [1010]int
	in := bufio.NewReader(os.Stdin)

	fmt.Fscan(in, &n)
	fmt.Fscan(in, &k)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &d)
		drinks[d-1] += 1
	}

	sort.Sort(sort.Reverse(sort.IntSlice(drinks[:k])))

	var rem_drinks int
	if n%2 == 0 {
		rem_drinks = n / 2
	} else {
		rem_drinks = n/2 + 1
	}

	ans := 0

	for i := 0; i < k && rem_drinks > 0; i++ {
		if drinks[i] <= rem_drinks*2 {
			ans += drinks[i]
			if drinks[i]%2 == 0 {
				rem_drinks = rem_drinks - drinks[i]/2
			} else {
				rem_drinks = rem_drinks - drinks[i]/2 - 1
			}
		} else {
			ans += rem_drinks * 2
			rem_drinks = 0
		}
	}
	fmt.Println(ans)
}

package main

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

var inf int = 0x3f3f3f3f
var reader *bufio.Reader

func init() {
	stdin := os.Stdin
	// stdin, _ = os.Open("1.in")
	reader = bufio.NewReaderSize(stdin, 1<<20)
}

var n, k int
var a []int

func main() {
	fmt.Fscan(reader, &n, &k)
	a = make([]int, n)
	m := make(map[int]int)
	for i := 0; i < n; i++ {
		fmt.Fscan(reader, &a[i])
		m[a[i]]++
	}
	ans := 0
	n = (n + 1) / 2
	for i := (n + 1) / 2; i != 0; i-- {
		flag := false
		for k, v := range m {
			if v > 1 {
				m[k] -= 2
				ans += 2
				flag = true
				if m[k] == 0 {
					delete(m, k)
				}
			}
		}
		if !flag {
			ans += Min(i, len(m))
			fmt.Println(ans)
			return
		}
	}
	fmt.Println(ans)
}

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


package main

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

type Int int64

const (
	INF = 3e5 + 10
	L0  = Int(0)
	L1  = Int(1)
)

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

	var T int
	Fscan(in, &T)

	for tt := 0; tt < T; tt++ {
		var n Int
		Fscan(in, &n)
		a := make([]Int, n+1)
		segTree := newSegTree(n)
		for i := L1; i <= n; i++ {
			Fscan(in, &a[i])
			segTree.Modify(1, i, i, a[i])
		}

		incV := make([]Int, 0, n+1)
		desV := make([]Int, 0, n+1)

		lastG := make([]Int, n+1)
		lastL := make([]Int, n+1)

		for i := L1; i <= n; i++ {

			for len(desV) > 0 && a[i] > a[desV[len(desV)-1]] {
				desV = desV[:len(desV)-1]
			}

			if len(desV) > 0 {
				lastG[i] = desV[len(desV)-1]
			} else {
				lastG[i] = 0
			}

			desV = append(desV, i)

			for len(incV) > 0 && a[i] < a[incV[len(incV)-1]] {
				incV = incV[:len(incV)-1]
			}

			if len(incV) > 0 {
				lastL[i] = incV[len(incV)-1]
			} else {
				lastL[i] = 0
			}

			incV = append(incV, i)

		}

		dis := make([]Int, n+1)
		dis[1] = 0
		for i := Int(2); i <= n; i++ {
			dis[i] = dis[i-1] + 1
			_, minIdx := segTree.Query(1, lastG[i]+1, i)
			if minIdx < i {
				dis[i].MinAs(dis[minIdx] + 1)
			}

			_, maxIdx := segTree.QueryMax(1, lastL[i]+1, i)
			if maxIdx < i {
				dis[i].MinAs(dis[maxIdx] + 1)
			}

		}
		Fprintln(out, dis[n])
	}
}

func MakeGrid(h, w int) [][]Int {
	index := make([][]Int, h)
	data := make([]Int, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

func Abs(x Int) Int {
	if x > 0 {
		return x
	}
	return -x
}

func Min(nums ...Int) Int {
	return nums[MinIdx(nums...)]
}

func MinIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num < nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

func Max(nums ...Int) Int {
	return nums[MaxIdx(nums...)]
}

func MaxIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

var (
	mod  Int
	fmod func(Int) Int = doNothing
)

// SetMod sets the mod. It must be called first.
func SetMod(newMod Int) {
	mod = newMod
	fmod = dynamicMod
}

func dynamicMod(m Int) Int {
	m %= mod
	if m < 0 {
		return m + mod
	}
	return m
}

func doNothing(m Int) Int {
	return m
}

// Mod returns m % mod.
func (m Int) Mod() Int {
	return fmod(m)
}

// Inv returns modular multiplicative inverse
func (m Int) Inv() Int {
	return m.Pow(Int(0).Sub(2))
}

// Pow returns m^n
func (m Int) Pow(n Int) Int {
	p := Int(1)
	for n > 0 {
		if n&1 == 1 {
			p.MulAs(m)
		}
		m.MulAs(m)
		n >>= 1
	}
	return p
}

// Add returns m+x
func (m Int) Add(x Int) Int {
	return (m + x).Mod()
}

// Sub returns m-x
func (m Int) Sub(x Int) Int {
	return (m - x).Mod()
}

// Mul returns m*x
func (m Int) Mul(x Int) Int {
	return (m * x).Mod()
}

// Div returns m/x
func (m Int) Div(x Int) Int {
	return m.Mul(x.Inv())
}

// AddAs assigns *m + x to *m and returns m
func (m *Int) AddAs(x Int) *Int {
	*m = m.Add(x)
	return m
}

// SubAs assigns *m - x to *m and returns m
func (m *Int) SubAs(x Int) *Int {
	*m = m.Sub(x)
	return m
}

// MulAs assigns *m * x to *m and returns m
func (m *Int) MulAs(x Int) *Int {
	*m = m.Mul(x)
	return m
}

// DivAs assigns *m / x to *m and returns m
func (m *Int) DivAs(x Int) *Int {
	*m = m.Div(x)
	return m
}

func (m *Int) MaxAs(x ...Int) *Int {
	*m = Max(append(x, *m)...)
	return m
}

func (m *Int) MinAs(x ...Int) *Int {
	*m = Min(append(x, *m)...)
	return m
}

type Void struct{}

var void Void

type HashSet struct {
	ma map[Int]Void
}

func NewHashSet() *HashSet {
	return &HashSet{
		ma: make(map[Int]Void),
	}
}

func (s *HashSet) add(x Int) bool {
	_, exists := s.ma[x]
	if !exists {
		s.ma[x] = void
		return true
	} else {
		return false
	}
}

func (s *HashSet) del(x Int) {
	delete(s.ma, x)
}

func (s *HashSet) exist(x Int) bool {
	_, exists := s.ma[x]
	return exists
}

// An Item is something we manage in a priority queue.
type Item struct {
	value    Int // The value of the item; arbitrary.
	priority Int // The priority of the item in the queue.
	indices  Int
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func NewItem(value, priority Int) *Item {
	return &Item{
		value:    value,
		priority: priority,
		index:    -1,
	}

}

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value Int, priority Int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

type SegTree struct {
	st []Segment
}

type Segment struct {
	l, r, val, add, maxVal, maxIndex, minIndex Int
}

func newSegTree(n Int) SegTree {
	segTree := SegTree{make([]Segment, n<<2)}
	segTree.Build(1, 1, n)
	return segTree
}

func (segTree SegTree) Build(x, l, r Int) {
	segTree.st[x].l = l
	segTree.st[x].r = r
	if l == r {
		segTree.st[x].minIndex = l
		segTree.st[x].maxIndex = l
		return
	}
	mid := (l + r) >> 1
	segTree.Build(x<<1, l, mid)
	segTree.Build(x<<1|1, mid+1, r)
}

func (segTree SegTree) push(x Int) {
	if segTree.st[x].add != 0 {
		segTree.modifyOne(x<<1, segTree.st[x].add)
		segTree.modifyOne(x<<1|1, segTree.st[x].add)
		segTree.st[x].add = 0
	}
}

func (segTree SegTree) update(x Int) {
	if segTree.st[x<<1].val < segTree.st[x<<1|1].val {
		segTree.st[x].val = segTree.st[x<<1].val
		segTree.st[x].minIndex = segTree.st[x<<1].minIndex
	} else {
		segTree.st[x].val = segTree.st[x<<1|1].val
		segTree.st[x].minIndex = segTree.st[x<<1|1].minIndex
	}

	if segTree.st[x<<1].maxVal > segTree.st[x<<1|1].maxVal {
		segTree.st[x].maxVal = segTree.st[x<<1].maxVal
		segTree.st[x].maxIndex = segTree.st[x<<1].maxIndex
	} else {
		segTree.st[x].maxVal = segTree.st[x<<1|1].maxVal
		segTree.st[x].maxIndex = segTree.st[x<<1|1].maxIndex
	}
}

func (segTree SegTree) modifyOne(x, add Int) {
	segTree.st[x].val += add
	segTree.st[x].maxVal += add
	if segTree.st[x].l != segTree.st[x].r {
		segTree.st[x].add += add
	}
}

func (segTree SegTree) Modify(x, l, r, add Int) {
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		segTree.modifyOne(x, add)
		return
	}
	segTree.push(x)
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		segTree.Modify(x<<1, l, r, add)
	}
	if mid < r {
		segTree.Modify(x<<1|1, l, r, add)
	}
	segTree.update(x)
}

func updateMinRes(cRes, cIndex, res, index Int) (Int, Int) {
	if cRes > res {
		return res, index
	}
	return cRes, cIndex
}

func (segTree SegTree) Query(x, l, r Int) (Int, Int) {
	res := Int(math.MaxInt64)
	resInd := -L1
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		res, resInd = updateMinRes(res, resInd, segTree.st[x].val, segTree.st[x].minIndex)
		return res, resInd
	}
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		sonRes, sonInd := segTree.Query(x<<1, l, r)
		res, resInd = updateMinRes(res, resInd, sonRes, sonInd)
	}
	if mid < r {
		sonRes, sonInd := segTree.Query(x<<1|1, l, r)
		res, resInd = updateMinRes(res, resInd, sonRes, sonInd)
	}
	return res, resInd
}

func updateMaxRes(cRes, cIndex, res, index Int) (Int, Int) {
	if cRes < res {
		return res, index
	}
	return cRes, cIndex
}

func (segTree SegTree) QueryMax(x, l, r Int) (Int, Int) {
	res := Int(math.MinInt64)
	resInd := -L1
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		res, resInd = updateMaxRes(res, resInd, segTree.st[x].maxVal, segTree.st[x].maxIndex)
		return res, resInd
	}
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		sonRes, sonInd := segTree.QueryMax(x<<1, l, r)
		res, resInd = updateMaxRes(res, resInd, sonRes, sonInd)
	}
	if mid < r {
		sonRes, sonInd := segTree.QueryMax(x<<1|1, l, r)
		res, resInd = updateMaxRes(res, resInd, sonRes, sonInd)
	}
	return res, resInd
}

type Graph struct {
	nodeSize Int
	edges    []Edge
	head     []Int
	dis      []Int
	vis      []bool
	nCnt     Int
	ans      []Int
}

type Edge struct {
	u, v, c, indices, next Int
}

func NewGraph(nodeSize Int) *Graph {
	return &Graph{
		nodeSize: nodeSize,
		edges:    make([]Edge, (2e5+10)<<2),
		head:     make([]Int, nodeSize+100),
		dis:      make([]Int, nodeSize+100),
		vis:      make([]bool, nodeSize+100),
		nCnt:     L1,
		ans:      make([]Int, nodeSize),
	}
}

func (g *Graph) addEdge(u Int, v Int, cost Int, indices Int) {
	g.nCnt++
	g.edges[g.nCnt] = Edge{u, v, cost, indices, g.head[u]}
	g.head[u] = g.nCnt
}

func (g *Graph) Dijkstra(begin Int) {
	for i := L1; i <= g.nodeSize; i++ {
		g.dis[i] = math.MaxInt64
	}
	pq := make(PriorityQueue, 0)
	heap.Init(&pq)

	g.dis[begin] = 0
	heap.Push(&pq, &Item{begin, 0, -1, -1})

	id := L0

	for len(pq) > 0 {
		it := heap.Pop(&pq).(*Item)
		u := it.value
		if g.vis[u] {
			continue
		}
		g.vis[u] = true

		if it.indices != -1 && id < g.nodeSize-1 {
			g.ans[id] = it.indices
			id++
		}

		for i := g.head[u]; i != 0; i = g.edges[i].next {
			v := g.edges[i].v
			if g.dis[v] > g.dis[u]+g.edges[i].c {
				g.dis[v] = g.dis[u] + g.edges[i].c

				heap.Push(&pq, &Item{v, g.dis[v], g.edges[i].indices, -1})
			}
		}
	}
}

package main

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

func Solve(testCaseIdx int, reader io.Reader, writer io.Writer) {
	var n int
	fmt.Fscan(reader, &n)
	a := make([]int, n)
	l := make([]int, n)
	r := make([]int, n)
	for k := 0; k < n; k++ {
		fmt.Fscan(reader, &a[k])
		l[k] = k
		r[k] = n - 1 - k
	}

	mn, mx := 0, 0
	for k := 1; k < n; k++ {
		switch {
		case a[k] < a[mn]:
			mn = k
			l[k] = l[mx] + 1
		case a[k] > a[mx]:
			mx = k
			l[k] = l[mn] + 1
		}
	}

	mn, mx = n - 1, n - 1
	for k := n - 2; k >= 0; k-- {
		switch {
		case a[k] < a[mn]:
			mn = k
			r[k] = r[mx] + 1
		case a[k] > a[mx]:
			mx = k
			r[k] = r[mn] + 1
		}
	}

	ans := n - 1;
	for k := 0; k < n; k++ {
		if ans > l[k] + r[k] {
			ans = l[k] + r[k]
		}
	}

	fmt.Fprintln(writer, ans)
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	var testCaseCount int
	fmt.Fscan(reader, &testCaseCount)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	for t := 0; t < testCaseCount; t++ {
		Solve(t, reader, writer)
	}
}

package main

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

type Int int64

const (
	INF = 3e5 + 10
	L0  = Int(0)
	L1  = Int(1)
)

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

	var T int
	Fscan(in, &T)

	for tt := 0; tt < T; tt++ {
		var n Int
		Fscan(in, &n)
		a := make([]Int, n+1)
		segTree := newSegTree(n)
		for i := L1; i <= n; i++ {
			Fscan(in, &a[i])
			segTree.Modify(1, i, i, a[i])
		}

		incV := make([]Int, 0, n+1)
		desV := make([]Int, 0, n+1)

		lastG := make([]Int, n+1)
		lastL := make([]Int, n+1)

		for i := L1; i <= n; i++ {

			for len(desV) > 0 && a[i] > a[desV[len(desV)-1]] {
				desV = desV[:len(desV)-1]
			}

			if len(desV) > 0 {
				lastG[i] = desV[len(desV)-1]
			} else {
				lastG[i] = 0
			}

			desV = append(desV, i)

			for len(incV) > 0 && a[i] < a[incV[len(incV)-1]] {
				incV = incV[:len(incV)-1]
			}

			if len(incV) > 0 {
				lastL[i] = incV[len(incV)-1]
			} else {
				lastL[i] = 0
			}

			incV = append(incV, i)

		}

		dis := make([]Int, n+1)
		dis[1] = 0
		for i := Int(2); i <= n; i++ {
			dis[i] = dis[i-1] + 1
			_, minIdx := segTree.Query(1, lastG[i]+1, i)
			if minIdx < i {
				dis[i].MinAs(dis[minIdx] + 1)
			}

			_, maxIdx := segTree.QueryMax(1, lastL[i]+1, i)
			if maxIdx < i {
				dis[i].MinAs(dis[maxIdx] + 1)
			}

		}
		Fprintln(out, dis[n])
	}
}

func MakeGrid(h, w int) [][]Int {
	index := make([][]Int, h)
	data := make([]Int, h*w)
	for i := 0; i < h; i++ {
		index[i] = data[i*w : (i+1)*w]
	}
	return index
}

func Abs(x Int) Int {
	if x > 0 {
		return x
	}
	return -x
}

func Min(nums ...Int) Int {
	return nums[MinIdx(nums...)]
}

func MinIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num < nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

func Max(nums ...Int) Int {
	return nums[MaxIdx(nums...)]
}

func MaxIdx(nums ...Int) Int {
	maxNumIdx := L0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = Int(i)
		}
	}
	return maxNumIdx
}

var (
	mod  Int
	fmod func(Int) Int = doNothing
)

// SetMod sets the mod. It must be called first.
func SetMod(newMod Int) {
	mod = newMod
	fmod = dynamicMod
}

func dynamicMod(m Int) Int {
	m %= mod
	if m < 0 {
		return m + mod
	}
	return m
}

func doNothing(m Int) Int {
	return m
}

// Mod returns m % mod.
func (m Int) Mod() Int {
	return fmod(m)
}

// Inv returns modular multiplicative inverse
func (m Int) Inv() Int {
	return m.Pow(Int(0).Sub(2))
}

// Pow returns m^n
func (m Int) Pow(n Int) Int {
	p := Int(1)
	for n > 0 {
		if n&1 == 1 {
			p.MulAs(m)
		}
		m.MulAs(m)
		n >>= 1
	}
	return p
}

// Add returns m+x
func (m Int) Add(x Int) Int {
	return (m + x).Mod()
}

// Sub returns m-x
func (m Int) Sub(x Int) Int {
	return (m - x).Mod()
}

// Mul returns m*x
func (m Int) Mul(x Int) Int {
	return (m * x).Mod()
}

// Div returns m/x
func (m Int) Div(x Int) Int {
	return m.Mul(x.Inv())
}

// AddAs assigns *m + x to *m and returns m
func (m *Int) AddAs(x Int) *Int {
	*m = m.Add(x)
	return m
}

// SubAs assigns *m - x to *m and returns m
func (m *Int) SubAs(x Int) *Int {
	*m = m.Sub(x)
	return m
}

// MulAs assigns *m * x to *m and returns m
func (m *Int) MulAs(x Int) *Int {
	*m = m.Mul(x)
	return m
}

// DivAs assigns *m / x to *m and returns m
func (m *Int) DivAs(x Int) *Int {
	*m = m.Div(x)
	return m
}

func (m *Int) MaxAs(x ...Int) *Int {
	*m = Max(append(x, *m)...)
	return m
}

func (m *Int) MinAs(x ...Int) *Int {
	*m = Min(append(x, *m)...)
	return m
}

type Void struct{}

var void Void

type HashSet struct {
	ma map[Int]Void
}

func NewHashSet() *HashSet {
	return &HashSet{
		ma: make(map[Int]Void),
	}
}

func (s *HashSet) add(x Int) bool {
	_, exists := s.ma[x]
	if !exists {
		s.ma[x] = void
		return true
	} else {
		return false
	}
}

func (s *HashSet) del(x Int) {
	delete(s.ma, x)
}

func (s *HashSet) exist(x Int) bool {
	_, exists := s.ma[x]
	return exists
}

// An Item is something we manage in a priority queue.
type Item struct {
	value    Int // The value of the item; arbitrary.
	priority Int // The priority of the item in the queue.
	indices  Int
	// The index is needed by update and is maintained by the heap.Interface methods.
	index int // The index of the item in the heap.
}

// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue []*Item

func NewItem(value, priority Int) *Item {
	return &Item{
		value:    value,
		priority: priority,
		index:    -1,
	}

}

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	// We want Pop to give us the highest, not lowest, priority so we use greater than here.
	return pq[i].priority < pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *PriorityQueue) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Item)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

// update modifies the priority and value of an Item in the queue.
func (pq *PriorityQueue) update(item *Item, value Int, priority Int) {
	item.value = value
	item.priority = priority
	heap.Fix(pq, item.index)
}

type SegTree struct {
	st []Segment
}

type Segment struct {
	l, r, val, add, maxVal, maxIndex, minIndex Int
}

func newSegTree(n Int) SegTree {
	segTree := SegTree{make([]Segment, n<<2)}
	segTree.Build(1, 1, n)
	return segTree
}

func (segTree SegTree) Build(x, l, r Int) {
	segTree.st[x].l = l
	segTree.st[x].r = r
	if l == r {
		segTree.st[x].minIndex = l
		segTree.st[x].maxIndex = l
		return
	}
	mid := (l + r) >> 1
	segTree.Build(x<<1, l, mid)
	segTree.Build(x<<1|1, mid+1, r)
}

func (segTree SegTree) push(x Int) {
	if segTree.st[x].add != 0 {
		segTree.modifyOne(x<<1, segTree.st[x].add)
		segTree.modifyOne(x<<1|1, segTree.st[x].add)
		segTree.st[x].add = 0
	}
}

func (segTree SegTree) update(x Int) {
	if segTree.st[x<<1].val < segTree.st[x<<1|1].val {
		segTree.st[x].val = segTree.st[x<<1].val
		segTree.st[x].minIndex = segTree.st[x<<1].minIndex
	} else {
		segTree.st[x].val = segTree.st[x<<1|1].val
		segTree.st[x].minIndex = segTree.st[x<<1|1].minIndex
	}

	if segTree.st[x<<1].maxVal > segTree.st[x<<1|1].maxVal {
		segTree.st[x].maxVal = segTree.st[x<<1].maxVal
		segTree.st[x].maxIndex = segTree.st[x<<1].maxIndex
	} else {
		segTree.st[x].maxVal = segTree.st[x<<1|1].maxVal
		segTree.st[x].maxIndex = segTree.st[x<<1|1].maxIndex
	}
}

func (segTree SegTree) modifyOne(x, add Int) {
	segTree.st[x].val += add
	if segTree.st[x].l != segTree.st[x].r {
		segTree.st[x].add += add
	}
}

func (segTree SegTree) Modify(x, l, r, add Int) {
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		segTree.modifyOne(x, add)
		return
	}
	segTree.push(x)
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		segTree.Modify(x<<1, l, r, add)
	}
	if mid < r {
		segTree.Modify(x<<1|1, l, r, add)
	}
	segTree.update(x)
}

func updateMinRes(cRes, cIndex, res, index Int) (Int, Int) {
	if cRes > res {
		return res, index
	}
	return cRes, cIndex
}

func (segTree SegTree) Query(x, l, r Int) (Int, Int) {
	res := Int(math.MaxInt64)
	resInd := -L1
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		res, resInd = updateMinRes(res, resInd, segTree.st[x].val, segTree.st[x].minIndex)
		return res, resInd
	}
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		sonRes, sonInd := segTree.Query(x<<1, l, r)
		res, resInd = updateMinRes(res, resInd, sonRes, sonInd)
	}
	if mid < r {
		sonRes, sonInd := segTree.Query(x<<1|1, l, r)
		res, resInd = updateMinRes(res, resInd, sonRes, sonInd)
	}
	return res, resInd
}

func updateMaxRes(cRes, cIndex, res, index Int) (Int, Int) {
	if cRes < res {
		return res, index
	}
	return cRes, cIndex
}

func (segTree SegTree) QueryMax(x, l, r Int) (Int, Int) {
	res := Int(math.MinInt64)
	resInd := -L1
	if segTree.st[x].l >= l && segTree.st[x].r <= r {
		res, resInd = updateMaxRes(res, resInd, segTree.st[x].maxVal, segTree.st[x].maxIndex)
		return res, resInd
	}
	mid := (segTree.st[x].l + segTree.st[x].r) >> 1
	if mid >= l {
		sonRes, sonInd := segTree.QueryMax(x<<1, l, r)
		res, resInd = updateMaxRes(res, resInd, sonRes, sonInd)
	}
	if mid < r {
		sonRes, sonInd := segTree.QueryMax(x<<1|1, l, r)
		res, resInd = updateMaxRes(res, resInd, sonRes, sonInd)
	}
	return res, resInd
}

type Graph struct {
	nodeSize Int
	edges    []Edge
	head     []Int
	dis      []Int
	vis      []bool
	nCnt     Int
	ans      []Int
}

type Edge struct {
	u, v, c, indices, next Int
}

func NewGraph(nodeSize Int) *Graph {
	return &Graph{
		nodeSize: nodeSize,
		edges:    make([]Edge, (2e5+10)<<2),
		head:     make([]Int, nodeSize+100),
		dis:      make([]Int, nodeSize+100),
		vis:      make([]bool, nodeSize+100),
		nCnt:     L1,
		ans:      make([]Int, nodeSize),
	}
}

func (g *Graph) addEdge(u Int, v Int, cost Int, indices Int) {
	g.nCnt++
	g.edges[g.nCnt] = Edge{u, v, cost, indices, g.head[u]}
	g.head[u] = g.nCnt
}

func (g *Graph) Dijkstra(begin Int) {
	for i := L1; i <= g.nodeSize; i++ {
		g.dis[i] = math.MaxInt64
	}
	pq := make(PriorityQueue, 0)
	heap.Init(&pq)

	g.dis[begin] = 0
	heap.Push(&pq, &Item{begin, 0, -1, -1})

	id := L0

	for len(pq) > 0 {
		it := heap.Pop(&pq).(*Item)
		u := it.value
		if g.vis[u] {
			continue
		}
		g.vis[u] = true

		if it.indices != -1 && id < g.nodeSize-1 {
			g.ans[id] = it.indices
			id++
		}

		for i := g.head[u]; i != 0; i = g.edges[i].next {
			v := g.edges[i].v
			if g.dis[v] > g.dis[u]+g.edges[i].c {
				g.dis[v] = g.dis[u] + g.edges[i].c

				heap.Push(&pq, &Item{v, g.dis[v], g.edges[i].indices, -1})
			}
		}
	}
}


package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		aa := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &aa[i])
		}
		bb := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &bb[i])
		}

		var g int64
		for x := 31; x >= 0; x-- {
			z := g | (1 << x)
			f := true
			mm := make(map[int64]int, n)
			for _, v := range bb {
				mm[v&z]++
			}
			for _, v := range aa {
				if mm[(v&z)^z] <= 0 {
					f = false
					break
				}
				mm[(v&z)^z]--
			}
			if f {
				g = z
			}
		}
		fmt.Fprintln(out, g)
	}
}

package main

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

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

func qwq() {
	var n int
	fmt.Fscan(in, &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	for i := range b {
		fmt.Fscan(in, &b[i])
	}
	res := 0
	c := make([]int, n)
	d := make([]int, n)

	for i := 30; i >= 0; i-- {
		x := res | (1 << i)
		for j := range a {
			c[j] = x & a[j]
			d[j] = x & (^b[j])
		}
		sort.Ints(c)
		sort.Ints(d)
		if reflect.DeepEqual(c, d) {
			res = x
		}
	}
	fmt.Fprintln(out, res)
}

func main() {
	defer out.Flush()
	q := 1
	fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
}

package main

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

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

func main() {
	defer writer.Flush()
	var Q int
	fmt.Fscan(reader, &Q)
	for ; Q > 0; Q-- {
		var n int
		fmt.Fscan(reader, &n)
		a := make([]int, n)
		b := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &a[i])
		}
		for i := 0; i < n; i++ {
			fmt.Fscan(reader, &b[i])
		}

		var ans int64 = 0
		for cur_b := 29; cur_b >= 0; cur_b-- {
      // if cur_b-th bit is in result, there will be
      // prefix in A that match with one prefix in B.
			A := make([]int64, n)
			B := make([]int64, n)
			for i := 0; i < n; i++ {
				A[i] = int64(a[i]) & (ans | (1 << cur_b))
				B[i] = int64(^b[i]) & (ans | (1 << cur_b))
			}
			sort.Slice(A, func(i, j int) bool {
				return A[i] < A[j]
			})
			sort.Slice(B, func(i, j int) bool {
				return B[i] < B[j]
			})

			ok := true
			for i := 0; i < n; i++ {
				if A[i] != B[i] {
					ok = false
					break
				}
			}
			if ok {
				ans |= (1 << cur_b)
			}
		}

		fmt.Fprintf(writer, "%d\n", ans)
	}
}

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 int
		fmt.Fscan(r, &n)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}
		b := make([]int, n)
		for i := range b {
			fmt.Fscan(r, &b[i])
		}
		w1 := do(n, a, b)
		fmt.Fprintln(w, w1)
	}
}

var maxK = 29

func do(n int, a, b []int) int {
	// fmt.Println("a")
	// for _, v := range a {
	// 	fmt.Printf("%3d %05b\n", v)
	// }
	// fmt.Println("b")
	// for _, v := range b {
	// 	fmt.Printf("%3d %05b\n", v)
	// }
	d := [][2][]int{}
	d = append(d, [2][]int{a, b})
	ans := 0
	for k := maxK; k >= 0; k-- {
		ok := true
		for _, v := range d {
			a, b = v[0], v[1]
			x, y := 0, 0
			for i := range a {
				if (a[i]>>k)&1 == 1 {
					x++
				}
				if (b[i]>>k)&1 == 1 {
					y++
				}
			}
			if x != len(a)-y {
				ok = false
				break
			}
		}
		if ok {
			ans |= (1 << k)
		} else {
			continue
		}
		p := [][2][]int{}
		for _, v := range d {
			a, b = v[0], v[1]
			var x, y [2][]int
			for i := range a {
				if (a[i]>>k)&1 == 1 {
					x[0] = append(x[0], a[i])
				} else {
					y[0] = append(y[0], a[i])
				}
				if (b[i]>>k)&1 == 1 {
					y[1] = append(y[1], b[i])
				} else {
					x[1] = append(x[1], b[i])
				}
			}
			if len(x[0]) > 0 {
				p = append(p, x)
			}
			if len(y[0]) > 0 {
				p = append(p, y)
			}
		}
		d = p
	}
	return ans
}

package main

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

var P107 int = 1000000007

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

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

func Abs(a int) int {
	return Max(a, -a)
}

func Gcd(a, b int) int {
	min := Min(a, b)
	max := Max(a, b)
	if min == 0 {
		return max
	}

	for max%min != 0 {
		min, max = max%min, min
	}

	return min
}

func Lcm(a, b int) int {
	return a / Gcd(a, b) * b
}

// var facs []int = make([]int, X + 1)
func FacP(n, p int) int {
	// if facs[n] != 0 {
	//   return facs[n]
	// }
	result := 1
	// facs[0] = 1
	for i := 1; i <= n; i++ {
		result = (result * i) % p
		// facs[i] = result
	}

	return result
}

func ExpP(a, x, p int) int {
	if x == 0 {
		return 1
	}

	if x%2 == 0 {
		half := ExpP(a, x/2, p)
		return (half * half) % p
	} else {
		return ((a % p) * ExpP(a, x-1, p)) % p
	}
}

func CombP(n, c, p int) int {
	// If CombP be called multiple times, you should optimize FacP using memoization.
	return (FacP(n, p) * ((ExpP(FacP(n-c, p), p-2, p) * ExpP(FacP(c, p), p-2, p)) % p)) % p
}

func Solve(reader *bufio.Reader) {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()

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

	for _i := 0; _i < t; _i++ {
		scanner.Scan()
		n, _ := strconv.Atoi(scanner.Text())

		aArr := make([]int, n)
		for i := 0; i < n; i++ {
			scanner.Scan()
			aArr[i], _ = strconv.Atoi(scanner.Text())
		}
		bArr := make([]int, n)
		for i := 0; i < n; i++ {
			scanner.Scan()
			bArr[i], _ = strconv.Atoi(scanner.Text())
		}

		aGrp := make([][]int, 1)
		aGrp[0] = make([]int, n)
		bGrp := make([][]int, 1)
		bGrp[0] = make([]int, n)
		for i := 0; i < n; i++ {
			aGrp[0][i] = aArr[i]
			bGrp[0][i] = bArr[i]
		}

		result := 0
		for i := 30; i >= 0; i-- {
			ln := len(aGrp)
			check := 0
			for j := 0; j < ln; j++ {
				aCnt := 0
				bCnt := 0
				for k := 0; k < len(aGrp[j]); k++ {
					ithA := ((1 << i) & aGrp[j][k]) >> i
					ithB := ((1 << i) & bGrp[j][k]) >> i

					aCnt += ithA
					bCnt += ithB
				}

				if aCnt == len(aGrp[j])-bCnt {
					check++
				}
			}
			if check != ln {
				continue
			}

			for j := 0; j < ln; j++ {
				aOnes := make([]bool, len(aGrp[j]))
				bOnes := make([]bool, len(aGrp[j]))
				for k := 0; k < len(aGrp[j]); k++ {
					ithA := ((1 << i) & aGrp[j][k]) >> i
					ithB := ((1 << i) & bGrp[j][k]) >> i

					if ithA == 1 {
						aOnes[k] = true
					}
					if ithB == 1 {
						bOnes[k] = true
					}
				}

				var newAGrp0 []int
				var newBGrp0 []int
				var newAGrp1 []int
				var newBGrp1 []int

				for k := 0; k < len(aGrp[j]); k++ {
					if aOnes[k] {
						newAGrp1 = append(newAGrp1, aGrp[j][k])
					} else {
						newAGrp0 = append(newAGrp0, aGrp[j][k])
					}
					if bOnes[k] {
						newBGrp1 = append(newBGrp1, bGrp[j][k])
					} else {
						newBGrp0 = append(newBGrp0, bGrp[j][k])
					}
				}

				if len(newAGrp0) >= len(newAGrp1) {
					aGrp[j] = newAGrp0
					bGrp[j] = newBGrp1
					if len(newAGrp1) != 0 {
						aGrp = append(aGrp, newAGrp1)
						bGrp = append(bGrp, newBGrp0)
					}
				} else {
					aGrp[j] = newAGrp1
					bGrp[j] = newBGrp0
					if len(newAGrp0) != 0 {
						aGrp = append(aGrp, newAGrp0)
						bGrp = append(bGrp, newBGrp1)
					}
				}
				result |= (1 << i)
			}
		}

		wr.WriteString(strconv.Itoa(result) + "\n")
	}
}

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

package main

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

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

type S struct {
	arr []int
	p   int
	m   int
}

func (a *S) Len() int      { return len(a.arr) }
func (a *S) Swap(i, j int) { a.arr[i], a.arr[j] = a.arr[j], a.arr[i] }
func (a *S) Less(i, j int) bool {
	if a.m == 0 {
		return a.arr[i]>>a.p&1 < a.arr[j]>>a.p&1
	}
	return a.arr[i]>>a.p&1 > a.arr[j]>>a.p&1
}

func Sort(a, b *[]int, l, r, p int) {
	if l >= r || p == -1 {
		return
	}
	x, y := 0, 0
	for i := range *a {
		if (*a)[i]>>p&1 == 0 {
			x++
		}
		if (*b)[i]>>p&1 == 1 {
			y++
		}
	}
	if x != y {
		return
	}

	ta := make([]int, len(*a))
	tb := make([]int, len(*a))
	copy(ta, *a)
	copy(tb, *b)

	sort.Sort(&S{ta[l : r+1], p, 0})
	sort.Sort(&S{tb[l : r+1], p, 1})
	pa, pb := l, l
	for pa <= r && (ta[pa]>>p&1) != 1 {
		pa++
	}
	for pb <= r && (tb[pb]>>p&1) != 0 {
		pb++
	}
	// fmt.Println(p, l, r, format(ta))
	// fmt.Println(p, l, r, format(tb))
	// fmt.Println("=============")

	if pa == pb {
		*a, *b = ta, tb
		Sort(a, b, l, pa-1, p-1)
		Sort(a, b, pa, r, p-1)
	} else {
		Sort(a, b, l, r, p-1)
	}
}

func format(a []int) (res string) {
	for _, x := range a {
		f := strconv.FormatInt(int64(x), 2)
		for len(f) < 5 {
			f = "0" + f
		}
		res = res + f + " "
	}
	return res
}

func qwq() {
	var n int
	fmt.Fscan(in, &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	for i := range b {
		fmt.Fscan(in, &b[i])
	}
	Sort(&a, &b, 0, n-1, 31)
	var res int64 = (1 << 32) - 1
	for i := range a {
		res &= int64(a[i] ^ b[i])
	}
	// fmt.Fprintln(out, format(a))
	// fmt.Fprintln(out, format(b))
	fmt.Fprintln(out, res)
}

func main() {
	defer out.Flush()
	q := 1
	fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
	// a := []int{6, 0, 4}

	// fmt.Println(a)

}

package main

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

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

type S struct {
	arr []int
	p   int
	m   int
}

func (a *S) Len() int      { return len(a.arr) }
func (a *S) Swap(i, j int) { a.arr[i], a.arr[j] = a.arr[j], a.arr[i] }
func (a *S) Less(i, j int) bool {
	if a.m == 0 {
		return a.arr[i]>>a.p&1 < a.arr[j]>>a.p&1
	}
	return a.arr[i]>>a.p&1 > a.arr[j]>>a.p&1
}

func Sort(a, b *[]int, l, r, p int) {
	if l >= r || p == -1 {
		return
	}
	ta := make([]int, len(*a))
	tb := make([]int, len(*a))
	copy(ta, *a)
	copy(tb, *b)

	sort.Sort(&S{ta[l : r+1], p, 0})
	sort.Sort(&S{tb[l : r+1], p, 1})
	pa, pb := l, l
	for pa <= r && (ta[pa]>>p&1) != 1 {
		pa++
	}
	for pb <= r && (tb[pb]>>p&1) != 0 {
		pb++
	}
	// fmt.Println(p, l, r, format(ta))
	// fmt.Println(p, l, r, format(tb))
	// fmt.Println("=============")

	if pa == pb {
		*a, *b = ta, tb
		Sort(a, b, l, pa-1, p-1)
		Sort(a, b, pa, r, p-1)
	} else {
		Sort(a, b, l, r, p-1)
	}
}

func format(a []int) (res string) {
	for _, x := range a {
		f := strconv.FormatInt(int64(x), 2)
		for len(f) < 5 {
			f = "0" + f
		}
		res = res + f + " "
	}
	return res
}

func qwq() {
	var n int
	fmt.Fscan(in, &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	for i := range b {
		fmt.Fscan(in, &b[i])
	}
	Sort(&a, &b, 0, n-1, 31)
	var res int64 = (1 << 32) - 1
	for i := range a {
		res &= int64(a[i] ^ b[i])
	}
	// fmt.Fprintln(out, format(a))
	// fmt.Fprintln(out, format(b))
	fmt.Fprintln(out, res)
}

func main() {
	defer out.Flush()
	q := 1
	fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
	// a := []int{6, 0, 4}

	// fmt.Println(a)

}

package main

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

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

type S struct {
	arr []int
	p   int
}

func (a *S) Len() int           { return len(a.arr) }
func (a *S) Swap(i, j int)      { a.arr[i], a.arr[j] = a.arr[j], a.arr[i] }
func (a *S) Less(i, j int) bool { return a.arr[i]>>a.p&1 < a.arr[j]>>a.p&1 }

func Sort(a, b *[]int, l, r, p int) {
	if l >= r || p == -1 {
		return
	}
	ta := make([]int, len(*a))
	tb := make([]int, len(*a))
	copy(ta, *a)
	copy(tb, *b)

	sort.Sort(&S{ta[l : r+1], p})
	sort.Sort(&S{tb[l : r+1], p})
	pa, pb := l, l
	for pa <= r && (ta[pa]>>p&1) != 1 {
		pa++
	}
	for pb <= r && (tb[pb]>>p&1) != 0 {
		pb++
	}
	// fmt.Println(p, l, r, format(ta))
	// fmt.Println(p, l, r, format(tb))
	// fmt.Println("=============")

	if pa == pb {
		*a, *b = ta, tb
		Sort(a, b, l, pa-1, p-1)
		Sort(a, b, pa, r, p-1)
	} else {
		Sort(a, b, l, r, p-1)
	}
}

func format(a []int) (res string) {
	for _, x := range a {
		f := strconv.FormatInt(int64(x), 2)
		for len(f) < 5 {
			f = "0" + f
		}
		res = res + f + " "
	}
	return res
}

func qwq() {
	var n int
	fmt.Fscan(in, &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	for i := range b {
		fmt.Fscan(in, &b[i])
	}
	Sort(&a, &b, 0, n-1, 31)
	var res int64 = (1 << 32) - 1
	for i := range a {
		res &= int64(a[i] ^ b[i])
	}
	// fmt.Fprintln(out, format(a))
	// fmt.Fprintln(out, format(b))
	fmt.Fprintln(out, res)
}

func main() {
	defer out.Flush()
	q := 1
	fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
	// a := []int{6, 0, 4}

	// fmt.Println(a)

}

package main

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

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

func Sort(a, b *[]int, l, r, p int) {
	if l >= r || p == -1 {
		return
	}

	ta := make([]int, len(*a))
	tb := make([]int, len(*a))
	copy(ta, *a)
	copy(tb, *b)

	sort.Slice(ta[l:r+1], func(i, j int) bool {
		return ta[i]>>p&1 < ta[j]>>p&1
	})
	sort.Slice(tb[l:r+1], func(i, j int) bool {
		return tb[i]>>p&1 > tb[j]>>p&1
	})
	pa, pb := l, l
	for pa <= r && (ta[pa]>>p&1) != 1 {
		pa++
	}
	for pb <= r && (tb[pb]>>p&1) != 0 {
		pb++
	}
	// fmt.Println(p, format(ta))
	// fmt.Println(p, format(tb))
	// fmt.Println("=============")

	if pa == pb {
		*a, *b = ta, tb
		Sort(a, b, l, pa-1, p-1)
		Sort(a, b, pa, r, p-1)
	} else {
		Sort(a, b, l, r, p-1)
	}
}

func format(a []int) (res string) {
	for _, x := range a {
		f := strconv.FormatInt(int64(x), 2)
		for len(f) < 5 {
			f = "0" + f
		}
		res = res + f + " "
	}
	return res
}

func qwq() {
	var n int
	fmt.Fscan(in, &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	for i := range b {
		fmt.Fscan(in, &b[i])
	}
	Sort(&a, &b, 0, n-1, 31)
	var res int64 = (1 << 32) - 1
	for i := range a {
		res &= int64(a[i] ^ b[i])
	}
	// fmt.Fprintln(out, format(a))
	// fmt.Fprintln(out, format(b))
	fmt.Fprintln(out, res)
}

func main() {
	defer out.Flush()
	q := 1
	fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
}

package main

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

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

func Sort(a, b *[]int, l, r, p int) {
	if l >= r || p == -1 {
		return
	}

	ta := make([]int, len(*a))
	tb := make([]int, len(*a))
	copy(ta, *a)
	copy(tb, *b)

	sort.Slice(ta[l:r+1], func(i, j int) bool {
		return ta[i]>>p < ta[j]>>p
	})
	sort.Slice(tb[l:r+1], func(i, j int) bool {
		return tb[i]>>p > tb[j]>>p
	})
	pa, pb := l, l
	for pa <= r && ta[pa] != 1 {
		pa++
	}
	for pb <= r && tb[pb] != 0 {
		pb++
	}
	if pa == pb {
		*a, *b = ta, tb
		Sort(a, b, l, pa-1, p-1)
		Sort(a, b, pa, r, p-1)
	} else {
		Sort(a, b, l, r, p-1)
	}
}

func qwq() {
	var n int
	fmt.Fscan(in, &n)
	a := make([]int, n)
	b := make([]int, n)
	for i := range a {
		fmt.Fscan(in, &a[i])
	}
	for i := range b {
		fmt.Fscan(in, &b[i])
	}
	Sort(&a, &b, 0, n-1, 31)
	var res int64 = (1 << 32) - 1
	for i := range a {
		res &= int64(a[i] ^ b[i])
	}
	fmt.Fprintln(out, res)
}

func main() {
	defer out.Flush()
	q := 1
	fmt.Fscanln(in, &q)
	for ; q > 0; q-- {
		qwq()
	}
}

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 int
		fmt.Fscan(r, &n)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}
		b := make([]int, n)
		for i := range b {
			fmt.Fscan(r, &b[i])
		}
		w1 := do(n, a, b)
		fmt.Fprintln(w, w1)
	}
}

const maxK = 29

func do(n int, a, b []int) int {
	d := [][2][]int{}
	d = append(d, [2][]int{a, b})
	ans := 0
	for k := maxK; k >= 0; k-- {
		ok := true
		for _, v := range d {
			a, b = v[0], v[1]
			x, y := 0, 0
			for i := range a {
				if (a[i]>>k)&1 == 1 {
					x++
				}
				if (b[i]>>k)&1 == 1 {
					y++
				}
			}
			if x != len(a)-y {
				ok = false
				break
			}
		}
		if ok {
			ans |= (1 << k)
		} else {
			continue
		}
		p := [][2][]int{}
		for _, v := range d {
			a, b = v[0], v[1]
			var x, y [2][]int
			for i := range a {
				if (a[i]>>k)&1 == 1 {
					x[0] = append(x[0], a[i])
				} else {
					y[0] = append(y[0], a[i])
				}
				if (b[i]>>k)&1 == 1 {
					y[1] = append(y[1], a[i])
				} else {
					x[1] = append(x[1], a[i])
				}
			}
			if len(x[0]) > 0 {
				p = append(p, x)
			}
			if len(y[0]) > 0 {
				p = append(p, x)
			}
		}
		d = p
	}
	return ans
}

package main

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

var P107 int = 1000000007

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

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

func Abs(a int) int {
	return Max(a, -a)
}

func Gcd(a, b int) int {
	min := Min(a, b)
	max := Max(a, b)
	if min == 0 {
		return max
	}

	for max%min != 0 {
		min, max = max%min, min
	}

	return min
}

func Lcm(a, b int) int {
	return a / Gcd(a, b) * b
}

// var facs []int = make([]int, X + 1)
func FacP(n, p int) int {
	// if facs[n] != 0 {
	//   return facs[n]
	// }
	result := 1
	// facs[0] = 1
	for i := 1; i <= n; i++ {
		result = (result * i) % p
		// facs[i] = result
	}

	return result
}

func ExpP(a, x, p int) int {
	if x == 0 {
		return 1
	}

	if x%2 == 0 {
		half := ExpP(a, x/2, p)
		return (half * half) % p
	} else {
		return ((a % p) * ExpP(a, x-1, p)) % p
	}
}

func CombP(n, c, p int) int {
	// If CombP be called multiple times, you should optimize FacP using memoization.
	return (FacP(n, p) * ((ExpP(FacP(n-c, p), p-2, p) * ExpP(FacP(c, p), p-2, p)) % p)) % p
}

func Solve(reader *bufio.Reader) {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()

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

	for _i := 0; _i < t; _i++ {
		scanner.Scan()
		n, _ := strconv.Atoi(scanner.Text())

		aArr := make([]int, n)
		for i := 0; i < n; i++ {
			scanner.Scan()
			aArr[i], _ = strconv.Atoi(scanner.Text())
		}
		bArr := make([]int, n)
		for i := 0; i < n; i++ {
			scanner.Scan()
			bArr[i], _ = strconv.Atoi(scanner.Text())
		}

		aGrp := make([][]int, 1)
		aGrp[0] = make([]int, n)
		bGrp := make([][]int, 1)
		bGrp[0] = make([]int, n)
		for i := 0; i < n; i++ {
			aGrp[0][i] = aArr[i]
			bGrp[0][i] = bArr[i]
		}

		result := 0
		for i := 30; i >= 0; i-- {
			ln := len(aGrp)
			for j := 0; j < ln; j++ {
				aOnes := make([]bool, len(aGrp[j]))
				bOnes := make([]bool, len(aGrp[j]))
				aCnt := 0
				bCnt := 0
				for k := 0; k < len(aGrp[j]); k++ {
					ithA := ((1 << i) & aGrp[j][k]) >> i
					ithB := ((1 << i) & bGrp[j][k]) >> i

					aCnt += ithA
					bCnt += ithB
					if ithA == 1 {
						aOnes[k] = true
					}
					if ithB == 1 {
						bOnes[k] = true
					}
				}

				if aCnt == len(aGrp[j])-bCnt {
					var newAGrp0 []int
					var newBGrp0 []int
					var newAGrp1 []int
					var newBGrp1 []int

					for k := 0; k < len(aGrp[j]); k++ {
						if aOnes[k] {
							newAGrp1 = append(newAGrp1, aGrp[j][k])
						} else {
							newAGrp0 = append(newAGrp0, aGrp[j][k])
						}
						if bOnes[k] {
							newBGrp1 = append(newBGrp1, bGrp[j][k])
						} else {
							newBGrp0 = append(newBGrp0, bGrp[j][k])
						}
					}

					if len(newAGrp0) >= len(newAGrp1) {
						aGrp[j] = newAGrp0
						bGrp[j] = newBGrp1
						if len(newAGrp1) != 0 {
							aGrp = append(aGrp, newAGrp1)
							bGrp = append(bGrp, newBGrp0)
						}
					} else {
						aGrp[j] = newAGrp1
						bGrp[j] = newBGrp0
						if len(newAGrp0) != 0 {
							aGrp = append(aGrp, newAGrp0)
							bGrp = append(bGrp, newBGrp1)
						}
					}
					result |= (1 << i)
				}
			}
		}

		wr.WriteString(strconv.Itoa(result) + "\n")
	}
}

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

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n int
		fmt.Fscan(in, &n)

		aa := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &aa[i])
		}
		bb := make([]int64, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &bb[i])
		}

		var g int64
		for x := 31; x >= 0; x-- {
			z := g | (1 << x)
			f := true
			mm := make(map[int64]int, n)
			for _, v := range bb {
				mm[v&z]++
			}
			for _, v := range aa {
				fmt.Println("want: ", v, (v&z)^z)
				if mm[(v&z)^z] <= 0 {
					f = false
					break
				}
				mm[(v&z)^z]--
			}
			if f {
				g = z
			}
		}
		fmt.Fprintln(out, g)
	}
}


package main

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

type CF1700A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1700A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1700A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1700A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1700A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1700A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1700A
Date: 26/06/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1700/A
Problem: CF1700A
**/
func (in *CF1700A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n, m := in.NextInt64(), in.NextInt64()
		sum := (m * (m + 1)) / 2

		for i := int64(1); i < n; i++ {
			sum += m*(i+1)
		}

		fmt.Println(sum)
	}
}

func NewCF1700A(r *bufio.Reader) *CF1700A {
	return &CF1700A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1700A(bufio.NewReader(os.Stdin)).Run()
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for ; t > 0; t-- {
		var m, n int64
		fmt.Scanf("%d %d\n", &m, &n)
		val1 := (1+n)*n/2 + n*(1+m)*m/2 - n
		val2 := n*(0+m-1)*m/2 + m + m*n*n - (0+n-2)*(n-1)/2
		ans := int64(math.Min(float64(val1), float64(val2)))
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d\n", &t)
	for ; t > 0; t-- {
		var m, n int64
		fmt.Scanf("%d%d\n", &m, &n)
		val1 := (1+n)*n/2 + n*(1+m)*m/2 - n
		val2 := n*(0+m-1)*m/2 + m + m*n*n - (0+n-2)*(n-1)/2
		ans := int64(math.Min(float64(val1), float64(val2)))
		fmt.Println(ans)
	}
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var n, m int64
		fmt.Scan(&n, &m)
		ans := m*(m+1)/2 + (n-1)*(m*2+n*m)/2
		fmt.Println(ans)
	}

}

package main

import "fmt"

func main() {
	var T int
	var a, b float64
	var res float64

	fmt.Scan(&T)

	for T > 0 {
		res = 0
		fmt.Scan(&a)
		fmt.Scan(&b)
		firstRow := ((1 + b) * (b / 2.0))
		lastColumn := ((b + (a * b)) * (a / 2.0))
		res = firstRow + lastColumn - b
		fmt.Printf("%d\n", int64(res))
		T--
	}

}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func tc() {
	var n, m int64
	fmt.Fscan(r, &n)
	fmt.Fscan(r, &m)
	var sol int64
	sol = (m * (m + 1)) / 2
	sol += m * (n * (n + 1)) / 2
	sol -= m
	fmt.Fprintln(w, sol)
}

func main() {
	defer w.Flush()
	var t int
	fmt.Fscan(r, &t)
	for i := 0; i < t; i++ {
		tc()
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var y,x int
		fmt.Fscan(in,&y,&x)
		sum:= (x*x+x)/2
		for j:=2;j<=y;j++{
			sum += j*x
		}
		fmt.Fprintln(out,sum)
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func gi64() int64     { i,e := strconv.ParseInt(gs(),10,64); if e != nil {panic(e)}; return i }
func gis64(n int) []int64  { res := make([]int64,n); for i:=0;i<n;i++ { res[i] = gi64() }; return res }

func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int) int { if a > b { return a }; return b }
func min(a,b int) int { if a > b { return b }; return a }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}

func ia64(m int) []int64 { return make([]int64,m) }
func iai64(m int,v int64) []int64 { a := make([]int64,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi64(n int,m int,v int64) [][]int64 {
	r := make([][]int64,n); for i:=0;i<n;i++ { x := make([]int64,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill264(m int) ([]int64,[]int64) { a,b := ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i] = gi64(),gi64()}; return a,b }
func fill364(m int) ([]int64,[]int64,[]int64) { a,b,c := ia64(m),ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi64(),gi64(),gi64()}; return a,b,c }
func fill464(m int) ([]int64,[]int64,[]int64,[]int64) { a,b,c,d := ia64(m),ia64(m),ia64(m),ia64(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi64(),gi64(),gi64(),gi64()}; return a,b,c,d }
func abs64(a int64) int64 { if a < 0 { return -a }; return a }
func rev64(a []int64) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max64(a,b int64) int64 { if a > b { return a }; return b }
func min64(a,b int64) int64 { if a > b { return b }; return a }
func maxarr64(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr64(a []int64) int64 { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr64(a []int64) int64 { ans := int64(0); for _,aa := range(a) { ans += aa }; return ans }
func zeroarr64(a []int64) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod64(a,e,mod int64) int64 { res, m := int64(1), a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint64(a,e int64) int64 { res, m := int64(1), a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd64(a,b int64) int64 { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended64(a,b int64) (int64,int64,int64) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended64(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv64(a,m int64) (int64,bool) { g,x,_ := gcdExtended64(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func vecint64string(a []int64) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.FormatInt(a,10) }; return strings.Join(astr," ") }
func makefact64(n int,mod int64) ([]int64,[]int64) {
	fact,factinv := make([]int64,n+1),make([]int64,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * int64(i) % mod }
	factinv[n] = powmod64(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * int64(i+1) % mod }
	return fact,factinv
}
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		N,M := gi64(),gi64(); fmt.Fprintln(wrtr, M * (M-1) / 2 + M * (N+1) * N / 2 )
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush();

	qq := 0
	fmt.Fscan(in, &qq)
	for ii := 0; ii < qq; ii++ {
		n := uint64(0)
		m := uint64(0)
		fmt.Fscan(in, &n)
		fmt.Fscan(in, &m)
		fmt.Fprintln(out, m * (m - 1) / 2 + (m + n * m) * n / 2)
	}
}

package main

import "fmt"

func main() {
	var t, n, m, ans int64
	fmt.Scan(&t)
	for ; t > 0; t-- {
		fmt.Scan(&n, &m)
		ans = m * (m - 1) / 2
		ans += n * (n + 1) / 2 * m
		fmt.Println(ans)
	}
}

package main

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

var (
	reader bufio.Reader
	writer bufio.Writer
)

func solve() {
	var n, m int64

	scan(&n, &m)

	printf("%v\n", m * (m - 1) / 2 + m * n * (n + 1) / 2)
}

func main() {
	inp, err := os.Open("input.txt")
	if err == nil {
		os.Stdin = inp
		outp, _ := os.Create("output.txt")
		os.Stdout = outp
		defer outp.Close()
		defer inp.Close()
	}

	reader = *bufio.NewReader(os.Stdin)
	writer = *bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	T := 1
	scan(&T)

	for ; T > 0; T-- {
		solve()
	}
}

func scan(a ...interface{}) (n int, err error) { return fmt.Fscan(&reader, a...) }
func printf(format string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(&writer, format, a...)
}

package main

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

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

func solve() {
	var n, m int64
	fmt.Fscan(rr, &n, &m)
	// fmt.Fscan(rr,&m)
	var ans int64 = 0
	ans += (1 + m) * m / 2
	ans += (2*m + n*m) * (n - 1) / 2
	fmt.Println(ans)

}
func main() {
	var T int
	fmt.Fscan(rr, &T)
	for ; T > 0; T-- {
		solve()
	}
}

package main

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

var (
	reader = bufio.NewReader(os.Stdin)
	t      int
	n, m   int64
)

func solve(n, m int64) int64 {
	return m*(m-1)/2 + m*(n*(n+1)/2)
}

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n, &m)
		fmt.Println(solve(n, m))
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)

	for t := 0; t < T; t++ {
		var n, m int64
		fmt.Fscan(in, &n, &m)
		fmt.Fprintln(out, m*(1+m+(n+2)*(n-1))>>1)
	}
}

package main

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

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

	var T int
	fmt.Fscan(in, &T)
	for t := 0; t < T; t++ {
		var n, m int64
		fmt.Fscan(in, &n, &m)

		fmt.Fprintln(out, (m*(m+1)/2)+(m*n*(n+1)/2)-m)

	}
}

package main

import (
	"fmt"
	//"math"
)

func main() {
	var n int
	fmt.Scan(&n)
	for k := 0; k < n; k++ {
		var n int64
		var m int64
		fmt.Scan(&n)
		fmt.Scan(&m)
		res := (m*(m-1)/2 + (m+n*m)*n/2)
		fmt.Println(res)
	}
}

package main

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

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

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

	var T int
	var n int
	var m int

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &m)
		Fscan(in, &n)
		ans := int64(0)
		for i := 0; i < n; i++ {
			ans += int64(i + 1)
		}
		for j := 2; j <= m; j++ {
			ans += int64(j*n)
		}

		Fprintln(out, ans)
	}
}

package main

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

func A1() {
	_in, _out := os.Stdin, os.Stdout
	in, out := bufio.NewReader(_in), bufio.NewWriter(_out)
	defer out.Flush()
	var cas int = 1
	Fscan(in, &cas)
	// max := func(a, b int) int {
	// 	if a > b {
	// 		return a
	// 	}
	// 	return b
	// }
	var sol func()
	// Coding...beg!
	sol = func() {
		var n, m int64
		Fscan(in, &n, &m)
		Fprintln(out, (1+m)*m/2+(m+n*m)*n/2-m)
	}
	// Coding...ove!
	for i := 0; i < cas; i++ {
		sol()
	}
}
func main() { A1() }

package main

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

/*
1
3 4
---
30

1  2  3  4
5  6  7  8
9 10 11 12

1 2 3
4 5 6

1
2 3

*/

//goland:noinspection GoUnhandledErrorResult
func solve() {
	var n, m int64
	scanf("%d %d\n", &n, &m)

	pathLen := m * (m + 1) / 2

	for i := int64(2); i <= n; i++ {
		pathLen += i * m
	}

	fmt.Fprintln(writer, pathLen)
}

//goland:noinspection GoUnhandledErrorResult
func main() {
	defer writer.Flush()

	t := 1
	scanf("%d\n", &t)

	for ; t > 0; t-- {
		solve()
	}
}

const maxUint = ^uint(0)

//goland:noinspection GoUnusedConst
const minUint = 0
const maxInt = int(maxUint >> 1)

//goland:noinspection GoUnusedConst
const minInt = -maxInt - 1

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

func scanf(f string, a ...interface{}) {
	if _, err := fmt.Fscanf(reader, f, a...); err != nil {
		panic(err)
	}
}

//goland:noinspection GoUnusedFunction
func reversed(s string) string {
	input := []rune(s)
	li := len(input)
	ret := make([]rune, li)
	for i, r := range input {
		ret[li-i-1] = r
	}
	return string(ret)
}

//goland:noinspection GoUnusedFunction
func divCeil(num, div int64) int64 {
	quot := num / div
	if num%div > 0 {
		quot++
	} else if num%div < 0 {
		quot--
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	return nums[minIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func minIdx(nums ...int) int {
	minNumIdx := 0
	for i, num := range nums {
		if num < nums[minNumIdx] {
			minNumIdx = i
		}
	}

	return minNumIdx
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	return nums[maxIdx(nums...)]
}

//goland:noinspection GoUnusedFunction
func maxIdx(nums ...int) int {
	maxNumIdx := 0
	for i, num := range nums {
		if num > nums[maxNumIdx] {
			maxNumIdx = i
		}
	}

	return maxNumIdx
}

//goland:noinspection GoUnusedFunction
func sum(nums ...int) (sum int) {
	for _, num := range nums {
		sum += num
	}
	return
}

//goland:noinspection GoUnusedFunction
func abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

//goland:noinspection GoUnusedFunction
func isPrime(num int64) bool {
	if num == 2 || num == 3 {
		return true
	}

	if num <= 1 || num%2 == 0 || num%3 == 0 {
		return false
	}

	for i := int64(5); i*i <= num; i += 6 {
		if num%i == 0 || num%(i+2) == 0 {
			return false
		}
	}

	return true
}

//goland:noinspection GoUnusedFunction
func gcd(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

//goland:noinspection GoUnusedFunction
func lcm(a, b int) int {
	return abs(a) / gcd(a, b) * abs(b)
}

// Examples:
//	digitAt(1234, -1) -> panic!
//	digitAt(1234, 0) -> 4
//	digitAt(1234, 1) -> 3
//	digitAt(1234, 2) -> 2
//	digitAt(1234, 3) -> 1
//	digitAt(1234, 4) -> panic!
//goland:noinspection GoUnusedFunction
func digitAt(num, pos int) int {
	if num == 0 {
		return 0
	}

	num = abs(num)

	lenNum := int(math.Log10(float64(num))) + 1
	if pos < 0 || pos >= lenNum {
		err := fmt.Sprintf("Out of bound access for digit. Position passed %d, number %d", pos, num)
		panic(err)
	}

	rem := num % int(math.Pow10(pos+1))
	return rem / int(math.Pow10(pos))
}

//goland:noinspection GoUnusedFunction
func factorize(num int64) []int64 {
	factors := make([]int64, 0)

	for ftr := int64(2); ftr*ftr <= num; ftr++ {
		for num%ftr == 0 {
			num /= ftr
			factors = append(factors, ftr)
		}
	}

	if num > 1 {
		factors = append(factors, num)
	}

	return factors
}

//template from https://github.com/Cody-Wolf/Golang-in-ACM
package main

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

func Solve() {
	n, m := ri(), ri()
	var ans int64
	ans = 0
	for i := 1; i <= m; i++ {
		ans += int64(i)
	}
	for i := m + m; i <= n*m; i += m {
		ans += int64(i)
	}
	println(ans)
}

//-------------------------------------------------------

func main() {
	T := 0 // 如果是多组样例，请讲 T := 1 改为 T := 0
	in, out = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	if T == 0 {
		scan(&T)
	}
	for t := 0; t < T; t++ {
		Solve()
	}
	out.Flush()
}

var in *bufio.Reader
var out *bufio.Writer

// ri 将直接读入并返回一个 int
func ri() (x int) {
	scan(&x)
	return x
}

// ri64 将直接读入并返回一个 int64
func ri64() (x int64) {
	scan(&x)
	return x
}

//rl 将直接读入一行整数，并返回一个 int 切片
func rl(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ri())
	}
	return a
}

//rl64 将直接读入一行整数，并返回一个 int64 切片
func rl64(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ri64())
	}
	return a
}

//rs 将直接读入并返回一个 string
func rs() (s string) {
	scan(&s)
	return s
}

//scan 用法与 fmt.scan() 相似，可以传入多个变量的地址进行读入操作
func scan(a ...interface{}) { Fscan(in, a...) }

//print 用法与 fmt.print() 相似，可以传入多个变量进行输出。
func print(a ...interface{}) { Fprint(out, a...) }

//println 用法与 fmt.println() 相似，可以传入多个变量进行输出并在最后换行。
func println(a ...interface{}) { Fprintln(out, a...) }

//min 可以传入多个 int 变量，求出这些变量的最小值
func min(a ...int) int {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] < ans {
			ans = a[i]
		}
	}
	return ans
}

//min64 可以传入多个 int64 变量，求出这些变量的最小值
func min64(a ...int64) int64 {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] < ans {
			ans = a[i]
		}
	}
	return ans
}

//max 可以传入多个 int 变量，求出这些变量的最大值
func max(a ...int) int {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] > ans {
			ans = a[i]
		}
	}
	return ans
}

//max64 可以传入多个 int64 变量，求出这些变量的最大值
func max64(a ...int64) int64 {
	ans := a[0]
	for i := 1; i < len(a); i++ {
		if a[i] > ans {
			ans = a[i]
		}
	}
	return ans
}

//sum 可以传入多个 int 变量，求出这些变量的总和，并返回总和。
//
//你可以使用 ... 运算符打散数组，使得 sum 函数可以求出数组的和。
func sum(a ...int) int {
	ans := 0
	for _, x := range a {
		ans += x
	}
	return ans
}

//sum64 可以传入多个 int64 变量，求出这些变量的总和，并返回总和。
//
//你可以使用 ... 运算符打散数组，使得 sum64 函数可以求出数组的和。
func sum64(a ...int64) int64 {
	ans := int64(0)
	for _, x := range a {
		ans += x
	}
	return ans
}

//reverse 用于翻转 int 切片，所有元素将会变成原切片的倒序
func reverse(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]
	}
}

//reverse64 用于翻转 int64 切片，所有元素将会变成原切片的倒序
func reverse64(a []int64) {
	for l, r := 0, len(a)-1; l < r; l, r = l+1, r-1 {
		a[l], a[r] = a[r], a[l]
	}
}

// lowerBound 类似于 C++ 中的 lower_bound，用于二分查找 int 切片中，第一个大于等于 k 的元素在切片中的位置。
//
//如果元素不存在，则返回切片的长度。
//
//注意，lowerBound 作用的 int 切片必须升序。
func lowerBound(a []int, k int) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] < k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

//lowerBound64 类似于 C++ 中的 lower_bound，用于二分查找 int64 切片中，第一个大于等于 k 的元素在切片中的位置。
//
//如果元素不存在，则返回切片的长度。
//
//注意，lowerBound64 作用的 int64 切片必须升序。
func lowerBound64(a []int64, k int64) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] < k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

//upperBound 类似于 C++ 中的 upper_bound，用于二分查找 int 切片中，第一个大于 k 的元素在切片中的位置。
//
//如果元素不存在，则返回切片的长度。
//
//注意，upperBound 作用的 int 切片必须升序。
func upperBound(a []int, k int) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] <= k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

//upperBound64 类似于 C++ 中的 upper_bound，用于二分查找 int64 切片中，第一个大于 k 的元素在切片中的位置。
//
//如果元素不存在，则返回切片的长度。
//
//注意，upperBound64 作用的 int64 切片必须升序。
func upperBound64(a []int64, k int64) int {
	l, r, pos := 0, len(a)-1, len(a)
	for l <= r {
		mid := (l + r) >> 1
		if a[mid] <= k {
			l = mid + 1
		} else {
			pos, r = mid, mid-1
		}
	}
	return pos
}

//unique 类似于 C++ 中的 unique，用于给切片去重。
//
//区别在于: unique 函数接受一个 int 切片，并返回一个新的、去好重的切片
//
//注意: 传入的切片必须升序
func unique(a []int) []int {
	var b []int
	b = append(b, a[0])
	for i := 1; i < len(a); i++ {
		if a[i] != a[i-1] {
			b = append(b, a[i])
		}
	}
	return b
}

//valSet 将传入切片的所有元素，统一赋值为传入的元素 k
func valSet(a []int, k int) {
	for i, _ := range a {
		a[i] = k
	}
}

//Stack 类型是一个 int 类型的栈
type Stack struct {
	s []int
}

//top 获取栈顶元素
func (st *Stack) top() int { return st.s[len(st.s)-1] }

//size 返回栈内的元素个数
func (st *Stack) size() int { return len(st.s) }

//empty 返回一个 bool 类型，表示栈是否为空
func (st *Stack) empty() bool { return st.size() == 0 }

//pop 弹出栈顶元素
func (st *Stack) pop() { st.s = st.s[:len(st.s)-1] }

//push 将一个 int 类型从栈顶添加入栈
func (st *Stack) push(x int) { st.s = append(st.s, x) }

//get 得到栈的内容（一个新的 int切片）
func (st *Stack) get() (ans []int) {
	copy(ans, st.s)
	return ans
}

//Queue 类型是一个 int 类型的队列
type Queue struct {
	q    []int
	head int
}

//front 获取队首元素
func (que *Queue) front() int { return que.q[que.head] }

//size 返回队列的元素个数
func (que *Queue) size() int { return len(que.q) - que.head }

//empty 返回一个 bool 类型，表示队列是否为空
func (que *Queue) empty() bool { return que.size() == 0 }

//pop 弹出队首元素
func (que *Queue) pop() { que.head++ }

//push 将一个 int 类型从队尾添加入队
func (que *Queue) push(x int) { que.q = append(que.q, x) }

//get 得到队列的内容（一个新的 int切片）
func (que *Queue) get() (ans []int) {
	copy(ans, que.q)
	return ans
}

//PriorityQueue 类似是一个 int 型的优先队列
//
//注意：你需要通过 newPriorityQueue 函数来获取一个优先队列实例，而不是直接创建
type PriorityQueue struct {
	heap []int
	cmp  func(int, int) bool
}

//heapifyUp 从 x 结点开始到堆顶，调整结点使得满足堆的性质
//
//注意：你不应该直接使用这个函数
func (pq *PriorityQueue) heapifyUp(x int) {
	for x > 1 && pq.cmp(pq.heap[x-1], pq.heap[x/2-1]) {
		pq.heap[x-1], pq.heap[x/2-1] = pq.heap[x/2-1], pq.heap[x-1]
		x >>= 1
	}
}

//heapifyDown 从 x 结点开始向子节点，调整结点使得满足堆的性质
//
//注意：你不应该直接使用这个函数
func (pq *PriorityQueue) heapifyDown(x int) {
	for (x << 1) <= len(pq.heap) {
		t := x << 1
		if t+1 <= len(pq.heap) && pq.cmp(pq.heap[t+1-1], pq.heap[t-1]) {
			t++
		}
		if !pq.cmp(pq.heap[t-1], pq.heap[x-1]) {
			break
		}
		pq.heap[x-1], pq.heap[t-1] = pq.heap[t-1], pq.heap[x-1]
		x = t
	}
}

//push 向优先队列中加入一个元素（并自动调整优先队列）
func (pq *PriorityQueue) push(x int) {
	pq.heap = append(pq.heap, x)
	pq.heapifyUp(len(pq.heap))
}

//size 返回优先队列内的元素个数
func (pq *PriorityQueue) size() int { return len(pq.heap) }

//top 返回优先队列中优先级最高的元素
func (pq *PriorityQueue) top() int { return pq.heap[1-1] }

//pop 弹出优先队列中优先级最高的元素
func (pq *PriorityQueue) pop() {
	pq.heap[1-1], pq.heap[len(pq.heap)-1] = pq.heap[len(pq.heap)-1], pq.heap[1-1]
	pq.heap = pq.heap[:len(pq.heap)-1]
	pq.heapifyDown(1)
}

//newPriorityQueue 返回一个指向优先队列的指针
//
//第一个形参：传入一个 int 类型切片，创建优先队列时，你可以用一个 int 类型切片作为初始来创建，也可以设为空切片（nil)
//
//第二个形参：传入一个 func(int, int) bool 类型的函数指针作为比较器，以规定优先队列的优先级。
//传入比较器的两个元素如果满足前者比后者大，则返回 true；否则返回 false。
//
//你可以使用已有的 greater 函数指定小的 int 优先，也可以使用已有的 less 函数指定大的 int 优先
func newPriorityQueue(a []int, fun func(int, int) bool) *PriorityQueue {
	var q PriorityQueue
	copy(q.heap, a)
	q.cmp = fun
	for i := len(a); i >= 1; i-- {
		q.heapifyDown(i)
	}
	return &q
}

//less 判断传入参数 a 和 b 是否满足 a > b
func less(a, b int) bool {
	if a > b {
		return true
	} else {
		return false
	}
}

//greater 判断传入参数 a 和 b 是否满足 a < b
func greater(a, b int) bool {
	if a < b {
		return true
	} else {
		return false
	}
}

package main

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

func path_calc(n, m uint64) uint64 {
	var sum = m * (m + 1) / 2
	sum += m * (n*(n+1)/2 - 1)
	return sum
}

func main() {

	// rd := bufio.NewReader(os.Stdin)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var line = scanner.Text()
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	ans_arr := make([]uint64, num)
	// fmt.Print(num)
	var i = 0
	for i < num {
		scanner.Scan()
		line = scanner.Text()
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		// fmt.Println()
		ans_arr[i] = path_calc(uint64(n), uint64(m))
		i++
	}
	for i := 0; i < num; i++ {
		fmt.Fprintf(os.Stdout, "%d\n", ans_arr[i])
	}
	return
}

package main

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

func path_calc(n, m int32) int32 {
	var sum = m * (m + 1) / 2
	sum += m * (n*(n+1)/2 - 1)
	return sum
}

func main() {

	// rd := bufio.NewReader(os.Stdin)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var line = scanner.Text()
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	ans_arr := make([]int32, num)
	// fmt.Print(num)
	var i = 0
	for i < num {
		scanner.Scan()
		line = scanner.Text()
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		// fmt.Println()
		ans_arr[i] = path_calc(int32(n), int32(m))
		i++
	}
	for i := 0; i < num; i++ {
		fmt.Fprintf(os.Stdout, "%d\n", ans_arr[i])
	}
	return
}

package main

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

func path_calc(n, m int) int {
	var sum = m * (m + 1) / 2
	sum += m * (n*(n+1)/2 - 1)
	return sum
}

func main() {

	// rd := bufio.NewReader(os.Stdin)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var line = scanner.Text()
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	ans_arr := make([]int, num)
	// fmt.Print(num)
	var i = 0
	for i < num {
		scanner.Scan()
		line = scanner.Text()
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		// fmt.Println()
		ans_arr[i] = path_calc(n, m)
		i++
	}
	for i := 0; i < num; i++ {
		fmt.Fprintf(os.Stdout, "%d\n", ans_arr[i])
	}
	return
}

package main

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

func path_calc(n, m int) int {
	var sum = n * (n + 1) / 2
	sum += n * (m*(m+1)/2 - 1)
	return sum
}

func main() {

	// rd := bufio.NewReader(os.Stdin)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	var line = scanner.Text()
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	ans_arr := make([]int, num)
	// fmt.Print(num)
	var i = 0
	for i < num {
		scanner.Scan()
		line = scanner.Text()
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		// fmt.Println()
		ans_arr[i] = path_calc(n, m)
		i++
	}
	for i := 0; i < num; i++ {
		fmt.Fprintf(os.Stdout, "%d\n", ans_arr[i])
	}
	return
}

package main

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

func path_calc(n, m int) int {
	var sum = n * (n + 1) / 2
	sum += n * (m*(m+1)/2 - 1)
	return sum
}

func main() {

	rd := bufio.NewReader(os.Stdin)
	var line, _ = rd.ReadString('\n')
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	fmt.Print(num)
	var i = 0
	for i < num {
		line, _ = rd.ReadString('\n')
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		fmt.Println(path_calc(n, m))
		i++
	}
	return
}

package main

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

func path_calc(n, m int) int {
	var sum = n * (n + 1) / 2
	sum += n * (m*(m+1)/2 - 1)
	return sum
}

func main() {

	rd := bufio.NewReader(os.Stdin)
	var line, _ = rd.ReadString('\n')
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	// fmt.Print(num)
	var i = 0
	for i < num {
		line, _ = rd.ReadString('\n')
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		fmt.Printf("%d/n", path_calc(n, m))
		i++
	}
	return
}

package main

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

func path_calc(n, m int) int {
	var sum = n * (n + 1) / 2
	sum += n * (m*(m+1)/2 - 1)
	return sum
}

func main() {

	rd := bufio.NewReader(os.Stdin)
	var line, _ = rd.ReadString('\n')
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	ans_arr := make([]int, num)
	// fmt.Print(num)
	var i = 0
	for i < num {
		line, _ = rd.ReadString('\n')
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		// fmt.Println()
		ans_arr[i] = path_calc(n, m)
		i++
	}
	for i := 0; i < num; i++ {
		fmt.Println(ans_arr[i])
	}
	return
}

package main

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

func path_calc(n, m int) int {
	var sum = n * (n + 1) / 2
	sum += n * (m*(m+1)/2 - 1)
	return sum
}

func main() {

	rd := bufio.NewReader(os.Stdin)
	var line, _ = rd.ReadString('\n')
	var num, _ = strconv.Atoi(strings.ReplaceAll(line, "\n", ""))
	// fmt.Print(num)
	var i = 0
	for i < num {
		line, _ = rd.ReadString('\n')
		var s = strings.Split(line, " ")
		n, _ := strconv.Atoi(s[0])
		m, _ := strconv.Atoi(strings.ReplaceAll(s[1], "\n", ""))
		fmt.Println(path_calc(n, m))
		i++
	}
	return
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for ; t > 0; t-- {
		var m, n int64
		fmt.Scanf("%d%d", &m, &n)
		val1 := (1+n)*n/2 + n*(1+m)*m/2 - n
		val2 := n*(0+m-1)*m/2 + m + m*n*n - (0+n-2)*(n-1)/2
		ans := int64(math.Min(float64(val1), float64(val2)))
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int64
	fmt.Scanf("%d", &t)
	for ; t > 0; t-- {
		var m, n int64
		fmt.Scanf("%d %d", &m, &n)
		val1 := (1+n)*n/2 + n*(1+m)*m/2 - n
		val2 := n*(0+m-1)*m/2 + m + m*n*n - (0+n-2)*(n-1)/2
		ans := int64(math.Min(float64(val1), float64(val2)))
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for ; t > 0; t-- {
		var m, n int64
		fmt.Scanf("%d %d", &m, &n)
		val1 := (1+n)*n/2 + n*(1+m)*m/2 - n
		val2 := n*(0+m-1)*m/2 + m + m*n*n - (0+n-2)*(n-1)/2
		ans := int64(math.Min(float64(val1), float64(val2)))
		fmt.Println(ans)
	}
}

package main

import (
	"fmt"
	"math"
)

func main() {
	var t int
	fmt.Scanf("%d", &t)
	for ; t > 0; t-- {
		var m, n int64
		fmt.Scanf("%d %d", &m, &n)
		val1 := (1+n)*n/2 + n*(1+m)*m/2 - n
		val2 := n*(0+m-1)*m/2 + m + m*n*n - (0+n-2)*(n-1)/2
		ans := int(math.Min(float64(val1), float64(val2)))
		fmt.Println(ans)
	}
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var n, m int
		fmt.Scan(&n, &m)
		ans := m*(m+1)/2 + (n-1)*(m*2+n*m)/2
		fmt.Println(ans)
	}

}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		var n, m int
		fmt.Scan(&n, &m)
		ans := m*(m+1)/2 + (n-1)*(m*2+n*m)/2
		println(ans)
	}

}

package main

import "fmt"

func main() {
	var T int
	var a, b float64
	var res float64

	fmt.Scan(&T)

	for T > 0 {
		res = 0
		fmt.Scan(&a)
		fmt.Scan(&b)
		firstRow := ((1 + b) * (b / 2.0))
		lastColumn := ((b + (a * b)) * (a / 2.0))
		res = firstRow + lastColumn - b
		fmt.Printf("%d\n", int(res))
		T--
	}

}

package main

import "fmt"

func main() {
	var T int
	var a, b float64
	var res float64

	fmt.Scan(&T)

	for T > 0 {
		res = 0
		fmt.Scan(&a)
		fmt.Scan(&b)
		firstRow := ((1 + b) * (b / 2.0))
		lastColumn := ((b + (a * b)) * (a / 2.0))
		res = firstRow + lastColumn - b
		fmt.Println(res)
		T--
	}

}

package main

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

var r = bufio.NewReader(os.Stdin)
var w = bufio.NewWriter(os.Stdout)

func tc() {
	var n int
	fmt.Fscan(r, &n)
	var m int
	fmt.Fscan(r, &m)
	sol := (m * (m + 1)) / 2
	sol += m * (n * (n + 1)) / 2
	sol -= m
	fmt.Fprintln(w, sol)
}

func main() {
	defer w.Flush()
	var t int
	fmt.Fscan(r, &t)
	for i := 0; i < t; i++ {
		tc()
	}
}

package main

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

type CF1700A struct {
	sc        *bufio.Reader
	split     []string
	index     int
	separator string
}

func (in *CF1700A) GetLine() string {
	line, err := in.sc.ReadString('\n')
	if err != nil {
		fmt.Println("error line:", line, " err: ", err)
	}
	in.split = []string{}
	in.index = 0
	return line
}
func (in *CF1700A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

func (in *CF1700A) NextInt() int {
	in.load()
	val, _ := strconv.Atoi(strings.TrimSpace(in.split[in.index]))
	in.index++
	return val
}

func (in *CF1700A) NextInt64() int64 {
	in.load()
	val, _ := strconv.ParseInt(strings.TrimSpace(in.split[in.index]), 10, 64)
	in.index++
	return val
}

func (in *CF1700A) NextString() string {
	in.load()
	val := strings.TrimSpace(in.split[in.index])
	in.index++
	return val
}

/**
Run solve the problem CF1700A
Date: 26/06/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1700/A
Problem: CF1700A
**/
func (in *CF1700A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n, m := in.NextInt(), in.NextInt()
		sum := (m * (m + 1)) / 2

		for i := 1; i < n; i++ {
			sum += m*(i+1)
		}

		fmt.Println(sum)
	}
}

func NewCF1700A(r *bufio.Reader) *CF1700A {
	return &CF1700A{
		sc:        r,
		split:     []string{},
		index:     0,
		separator: " ",
	}
}

func main() {
	NewCF1700A(bufio.NewReader(os.Stdin)).Run()
}


package main

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

const (
	mod = int(1e9 + 7)
)

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	n, k := 0, 0
	fmt.Fscanf(in, "%d %d\n", &n, &k)
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, 0)
	}
	for i := 0; i < n-1; i++ {
		aa, b, c := 0, 0, 0
		fmt.Fscanf(in, "%d %d %d\n", &aa, &b, &c)
		aa--
		b--
		if c == 0 {
			a[aa] = append(a[aa], b)
			a[b] = append(a[b], aa)
		}
	}
	blk := []int{}
	vis := make([]bool, n)
	for i := 0; i < n; i++ {
		if !vis[i] {
			vis[i] = true
			queue := make([]int, 0)
			queue = append(queue, i)
			cnt := 0
			for len(queue) > 0 {
				cnt++
				cur := queue[0]
				queue = queue[1:]
				for j := 0; j < len(a[cur]); j++ {
					if !vis[a[cur][j]] {
						vis[a[cur][j]] = true
						queue = append(queue, a[cur][j])
					}
				}
			}
			blk = append(blk, cnt)
		}
	}
	ans := int64(0)
	q := int64(1)
	for i := 0; i < k; i++ {
		q *= int64(n)
		q %= int64(mod)
	}
	ans = q
	//fmt.Println(blk)
	for i := 0; i < len(blk); i++ {
		m := blk[i]
		q = 1
		for j := 0; j < k; j++ {
			q *= int64(m)
			q %= int64(mod)
		}
		ans -= q
		if ans < 0 {
			ans += int64(mod)
		}
		ans %= int64(mod)
	}
	fmt.Fprintf(out, "%d\n", ans)
	return
}

package main

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

var mod int64 = 1000000007;
var n int = 0;
var k int = 0;
var g [][]int;
var visited = make([]int, 123456);

func pot(a int64, m int) int64 {
    if m == 0 {
        return 1;
    }
    sq := pot(a, m/2);
    sq *= sq;
    sq %= mod;
    if m % 2 == 0 {
        return sq;
    }
    return (sq * a) % mod;
}

func dfs(v int) int {
    if (visited[v] != 0) {
        return 0;
    }
    lans := 1;
    visited[v] = 1;
    for _, w := range g[v] {
        lans += dfs(w);
    }
    return lans;
}

func main() {
	in := bufio.NewReader(os.Stdin)
	fmt.Fscanf(in, "%d %d\n", &n, &k);

    g = make([][]int, n);

	for i:=0; i < n - 1; i++ {
        a,b,c := 0,0,0;
        fmt.Fscanf(in, "%d %d %d\n", &a, &b, &c);
        a--; b--;
        if c == 0 {
            g[a] = append(g[a], b);
            g[b] = append(g[b], a);
        }
	}
    ans := pot(int64(n), k);
    for i := 0; i < n; i++ {
        visited[i] = 0;
    }
    for i := 0; i < n; i++ {
        if visited[i] == 0 {
            m := dfs(i);
            ans = ans + mod - pot(int64(m), k);
            ans %= mod;
        }
    }
	fmt.Println(ans);
}

package main

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

func power(a, b, p int64) int64 {
	if b == 0 || a == 1 {
		return 1
	}
	ret := power(a, b/2, p)
	ret = (ret * ret) % p
	if (b % 2) == 1 {
		ret = (ret * a) % p
	}
	return ret % p
}
func eddE(u, v int, edge map[int][]int) {
	if len(edge[u]) <= 0 {
		edge[u] = make([]int, 0)
	}
	edge[u] = append(edge[u], v)
}
func dfs(root int, flag []bool, edge map[int][]int) int {
	flag[root] = true
	ret := 1
	for _, v := range edge[root] {
		if flag[v] == false {
			ret += dfs(v, flag, edge)
		}
	}
	return ret
}
func Cal(n, m, p int64) int64 {
	var a, b int64
	a = 1
	b = 1
	for i := m + 1; i <= n; i++ {
		a = (a * i) % p
	}
	for i := n - m; i >= 1; i-- {
		b = (b * i) % p
	}
	return (a * (power(b, p-2, p))) % p
}
func main() {
	buf := bufio.NewReader(os.Stdin)
	var n, k int
	var p int64 = 1000000007
	fmt.Fscanf(buf, "%d %d\n", &n, &k)
	edge := make(map[int][]int)
	var u, v, b int
	for i := 0; i < n-1; i++ {
		fmt.Fscanf(buf, "%d %d %d\n", &u, &v, &b)
		if b == 1 {
			continue
		}
		eddE(u, v, edge)
		eddE(v, u, edge)
	}
	flag := make([]bool, n+1)
	var del int64 = 0
	for i := 1; i <= n; i++ {
		if flag[i] == false {
			cnt := dfs(i, flag, edge)
		//	fmt.Printf("i=%d cnt=%d\n",i,cnt)
			del += power(int64(cnt), int64(k), p)
			del %= p
		}
	}
	ans := power(int64(n), int64(k), p)
	ans = ans - del + p

	fmt.Printf("%d\n", ans%p)
}

/**
0 0
0 1
3
UDD
 */