You are asked to watch your nephew who likes to play with toy blocks in a strange way.He has $$$n$$$ boxes and the $$$i$$$-th box has $$$a_i$$$ blocks. His game consists of two steps:   he chooses an arbitrary box $$$i$$$;  he tries to move all blocks from the $$$i$$$-th box to other boxes.  If he can make the same number of blocks in each of $$$n - 1$$$ other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box $$$i$$$ he chooses he won't be sad. What is the minimum number of extra blocks you need to put?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of boxes. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of blocks in each box. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite.

NoteIn the first test case, you can, for example, put one extra block into the first box and make $$$a = [4, 2, 2]$$$. If your nephew chooses the box with $$$4$$$ blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with $$$2$$$ blocks then he will move these two blocks to the other box with $$$2$$$ blocks.In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal.In the third test case, you should put $$$3$$$ extra blocks. For example, you can put $$$2$$$ blocks in the first box and $$$1$$$ block in the third box. You'll get array $$$a = [2, 3, 1]$$$.

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

package main

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

var (
	t int

	n int
	A []int64
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		n = readi()
		A = readlls(n)

		solve()
	}
}

func solve() {
	M := Max(A...)
	s := Sum(A...)
	D := int64(n - 1)

	if D*M >= s {
		ans := D*M - s
		fmt.Println(ans)
		// debugf("ok\n")
		return
	}

	x := Kiriage(s, D)
	ans := D*x - s
	fmt.Println(ans)

	// y := Kiriage(maxi, D)
	// x := y * D
	// ans := x*D - s
	// fmt.Println(ans)
}

// Kiriage returns Ceil(a/b)
// a >= 0, b > 0
func Kiriage(a, b int64) int64 {
	return (a + (b - 1)) / b
}

// Sum returns multiple integers sum.
func Sum(integers ...int64) int64 {
	var s int64
	s = 0

	for _, i := range integers {
		s += i
	}

	return s
}

// Max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func Max(integers ...int64) int64 {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

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

/********** common constants **********/

const (
	MOD = 1000000000 + 7
	// MOD          = 998244353
	ALPH_N  = 26
	INF_I64 = math.MaxInt64
	INF_B60 = 1 << 60
	INF_I32 = math.MaxInt32
	INF_B30 = 1 << 30
	NIL     = -1
	EPS     = 1e-10
)

/********** bufio setting **********/

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

// mod can calculate a right residual whether value is positive or negative.
func mod(val, m int) int {
	res := val % m
	if res < 0 {
		res += m
	}
	return res
}

// min returns the min integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func min(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m > integer {
			m = integer
		}
	}
	return m
}

// max returns the max integer among input set.
// This function needs at least 1 argument (no argument causes panic).
func max(integers ...int) int {
	m := integers[0]
	for i, integer := range integers {
		if i == 0 {
			continue
		}
		if m < integer {
			m = integer
		}
	}
	return m
}

// chmin accepts a pointer of integer and a target value.
// If target value is SMALLER than the first argument,
//	then the first argument will be updated by the second argument.
func chmin(updatedValue *int, target int) bool {
	if *updatedValue > target {
		*updatedValue = target
		return true
	}
	return false
}

// chmax accepts a pointer of integer and a target value.
// If target value is LARGER than the first argument,
//	then the first argument will be updated by the second argument.
func chmax(updatedValue *int, target int) bool {
	if *updatedValue < target {
		*updatedValue = target
		return true
	}
	return false
}

// sum returns multiple integers sum.
func sum(integers ...int) int {
	var s int
	s = 0

	for _, i := range integers {
		s += i
	}

	return s
}

// abs is integer version of math.Abs
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// pow is integer version of math.Pow
// pow calculate a power by Binary Power (二分累乗法(O(log e))).
func pow(a, e int) int {
	if a < 0 || e < 0 {
		panic(errors.New("[argument error]: PowInt does not accept negative integers"))
	}

	if e == 0 {
		return 1
	}

	if e%2 == 0 {
		halfE := e / 2
		half := pow(a, halfE)
		return half * half
	}

	return a * pow(a, e-1)
}

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

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

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

//str := reads()
//i := readi()
//X := readis(n)
//S := readrs()
//a := readf()
//A := readfs(n)

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

/*********** Input ***********/

var (
	// reads returns a WORD string.
	reads  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()
	}
}

// readi returns an integer.
func readi() int {
	return int(_readInt64())
}
func readi2() (int, int) {
	return int(_readInt64()), int(_readInt64())
}
func readi3() (int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64())
}
func readi4() (int, int, int, int) {
	return int(_readInt64()), int(_readInt64()), int(_readInt64()), int(_readInt64())
}

// readll returns as integer as int64.
func readll() int64 {
	return _readInt64()
}
func readll2() (int64, int64) {
	return _readInt64(), _readInt64()
}
func readll3() (int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64()
}
func readll4() (int64, int64, int64, int64) {
	return _readInt64(), _readInt64(), _readInt64(), _readInt64()
}

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

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

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

// readf returns an float64.
func readf() float64 {
	return float64(_readFloat64())
}

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

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

// readrs returns a rune slice.
func readrs() []rune {
	return []rune(reads())
}

/*********** Output ***********/

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

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

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

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

// 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
}

package main

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

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

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

func min_int(a int, b int) int { if a < b { return a } else { return b } }
func min_int64(a int64, b int64) int64 { if a < b { return a } else { return b } }

func max_int(a int, b int) int { if a > b { return a } else { return b } }
func max_int64(a int64, b int64) int64 { if a > b { return a } else { return b } }

func main() {
	defer writer.Flush()

	var T int = 0
	scanf("%d\n", &T)

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

		var N int64
		scanf("%d\n", &N)

		var a_max int64 = 0
		var a_sum int64
		for n := int64(0); n < N; n++ {
			var a int64
			if(n != N-1) {
				scanf("%d ", &a)
			} else {
				scanf("%d\n", &a)
			}
			a_sum += a
			if(a > a_max) {
				a_max = a
			}
		}

		var k int64 = max_int64(a_max, (a_sum + N - 2)/(N - 1))
		var res int64 = k * (N-1) - a_sum
		printf("%d\n", res)

	}

}

package main

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

// github.com/EndlessCheng/codeforces-go
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	max := func(a, b int64) int64 {
		if a > b {
			return a
		}
		return b
	}
	solve := func(Case int) {
		var n int
		Fscan(in, &n)
		s := int64(0)
		mx := int64(0)
		for i := 0; i < n; i++ {
			var v int64
			Fscan(in, &v)
			s+=v
			mx = max(mx, v)
		}
		ans :=  mx*int64(n-1)-s
		if ans < 0 {
			s%=int64(n-1)
			if s > 0 {
				s= int64(n-1)-s
			}
			ans = s
		}
		Fprintln(out,ans)
	}

	var t int
	Fscan(in, &t)
	for Case := 1; Case <= t; Case++ {
		solve(Case)
	}
}

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

package main

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

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

func ceiledDivision(a, b int64) int64 {
	if a%b == 0 {
		return a / b
	}
	return a/b + 1
}

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

	var t, n, a int64
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		sum := int64(0)
		aMax := int64(0)
		for i := int64(0); i < n; i++ {
			fmt.Fscan(in, &a)
			aMax = max(aMax, a)
			sum += a
		}
		aMax = max(aMax, ceiledDivision(sum, n-1))
		fmt.Println(aMax*int64(n-1) - sum)
	}
}

package main

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

/*
3
3
3 2 2
4
2 2 3 2
3
0 3 0

1
0
3
*/

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

	var T, N, D int64

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &N)
		var max int64
		var sum int64
		for i := 0; i < int(N); i++ {
			Fscan(in, &D)
			if max < D {
				max = D
			}
			sum += D
		}

		if N == 2 {
			Fprintln(out, 0)
			continue
		}

		min := max*(N-1) - sum
		if min < 0 {
			min = ((min%(N-1))+N-1)%(N-1)
			Fprintln(out, min)
		} else {
			Fprintln(out, min)
		}

	}
}

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

package main

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

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

	var t, n int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
		}
		sort.Sort(sort.Reverse(sort.IntSlice(a)))
		if n == 2 {
			fmt.Println(0)
		} else if n == 3 {
			if a[0] == a[1]+a[2] {
				fmt.Println(0)
			} else if a[0] > a[1]+a[2] {
				fmt.Println(a[0] - a[1] - a[2])
			} else {
				fmt.Println(a[1] + a[2] - a[0])
			}
		} else {
			k := 0
			for i := 0; (n-1)*i <= a[0] || (n-2)*i <= a[1]; i++ {
				k = i
			}
			result := (n-1)*k - a[0]
			for i := 1; i < n; i++ {
				result += (n-2)*k - a[i]
			}
			fmt.Println(result)
		}
	}
}

package main

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

func solve1(a []int) int {
	n := len(a)

	k := 0
	for i := 0; true; i++ {
		k = i
		if (n-1)*i >= a[0] && (n-2)*i >= a[1] {
			break
		}
	}
	result := (n-1)*k - a[0]
	for i := 1; i < n; i++ {
		result += (n-2)*k - a[i]
	}
	return result
}

func solve2(a []int) int {
	n := len(a)

	if a[n-1]+a[n-2] > a[0] {
		a[0] = a[n-1] + a[n-2]
	}
	result := abs(a[n-1] + a[n-2] - a[0])
	for i := 1; i < n-2; i++ {
		result += a[0] - a[i]
	}
	return result
}

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

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

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

	var t, n int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
		}
		sort.Sort(sort.Reverse(sort.IntSlice(a)))
		if n == 2 {
			fmt.Println(0)
		} else if n == 3 {
			fmt.Println(abs(a[1] + a[2] - a[0]))
		} else {
			fmt.Println(min(solve1(a), solve2(a)))
		}
	}
}

package main

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

func solve1(a []int) int {
	n := len(a)

	k := 0
	for i := 0; (n-1)*i <= a[0] || (n-2)*i <= a[1]; i++ {
		k = i
	}
	result := (n-1)*k - a[0]
	for i := 1; i < n; i++ {
		result += (n-2)*k - a[i]
	}
	return result
}

func solve2(a []int) int {
	n := len(a)

	if a[n-1]+a[n-2] > a[0] {
		a[0] = a[n-1] + a[n-2]
	}
	result := abs(a[n-1] + a[n-2] - a[0])
	for i := 1; i < n-2; i++ {
		result += a[0] - a[i]
	}
	return result
}

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

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

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

	var t, n int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
		}
		sort.Sort(sort.Reverse(sort.IntSlice(a)))
		if n == 2 {
			fmt.Println(0)
		} else if n == 3 {
			fmt.Println(abs(a[1] + a[2] - a[0]))
		} else {
			fmt.Println(min(solve1(a), solve2(a)))
		}
	}
}

package main

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

func solve1(a []int) int {
	n := len(a)

	k := 0
	for i := 0; (n-1)*i <= a[0] || (n-2)*i <= a[1]; i++ {
		k = i
	}
	result := (n-1)*k - a[0]
	for i := 1; i < n; i++ {
		result += (n-2)*k - a[i]
	}
	return result
}

func solve2(a []int) int {
	n := len(a)

	if a[n-1]+a[n-2] > a[0] {
		a[0] = a[n-1] + a[n-2]
	}
	result := a[n-1] + a[n-2] - a[0]
	for i := 1; i < n-2; i++ {
		result += a[0] - a[i]
	}
	return result
}

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

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

	var t, n int
	fmt.Fscan(in, &t)

	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		a := make([]int, n)
		for i := range a {
			fmt.Fscan(in, &a[i])
		}
		sort.Sort(sort.Reverse(sort.IntSlice(a)))
		if n == 2 {
			fmt.Println(0)
		} else if n == 3 {
			if a[0] == a[1]+a[2] {
				fmt.Println(0)
			} else if a[0] > a[1]+a[2] {
				fmt.Println(a[0] - a[1] - a[2])
			} else {
				fmt.Println(a[1] + a[2] - a[0])
			}
		} else {
			fmt.Println(min(solve1(a), solve2(a)))
		}
	}
}

package main

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

/*
3
3
3 2 2
4
2 2 3 2
3
0 3 0

1
0
3
*/

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

	var T, N, D int64

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &N)
		var max int64
		var sum int64
		for i := 0; i < int(N); i++ {
			Fscan(in, &D)
			if max < D {
				max = D
			}
			sum += D
		}

		if N == 2 {
			Fprintln(out, 0)
			continue
		}

		min := max*(N-1) - sum
		if min < 0 {
			Fprintln(out, N-1-min)
		} else {
			Fprintln(out, min)
		}

	}
}

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

package main

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

/*
3
3
3 2 2
4
2 2 3 2
3
0 3 0

1
0
3
*/

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

	var T, N, D int64

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &N)
		var max int64
		var sum int64
		for i := 0; i < int(N); i++ {
			Fscan(in, &D)
			if max < D {
				max = D
			}
			sum += D
		}

		min := max*(N-1) - sum
		if min < 0 {
			Fprintln(out, -min)
		} else {
			Fprintln(out, min)
		}

	}
}

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

package main

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

/*
3
3
3 2 2
4
2 2 3 2
3
0 3 0

1
0
3
*/

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

	var T, N, D int64

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &N)
		if N == 2 {
			Fprintln(out, 0)
		}

		var max int64
		var sum int64
		for i := 0; i < int(N); i++ {
			Fscan(in, &D)
			if max < D {
				max = D
			}
			sum += D
		}

		min := max*(N-1) - sum
		if min < 0 {
			Fprintln(out, -min)
		} else {
			Fprintln(out, min)
		}

	}
}

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

package main

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

/*
3
3
3 2 2
4
2 2 3 2
3
0 3 0

1
0
3
*/

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

	var T, N, D int64

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &N)
		var max int64
		var sum int64
		for i := 0; i < int(N); i++ {
			Fscan(in, &D)
			if max < D {
				max = D
			}
			sum += D
		}

		if N == 2 {
			Fprintln(out, 0)
			continue
		}

		min := max*(N-1) - sum
		if min < 0 {
			Fprintln(out, -min)
		} else {
			Fprintln(out, min)
		}

	}
}

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

package main

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

/*
3
3
3 2 2
4
2 2 3 2
3
0 3 0

1
0
3
*/

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

	var T, N, D int64

	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &N)
		var max int64
		var sum int64
		for i := 0; i < int(N); i++ {
			Fscan(in, &D)
			if max < D {
				max = D
			}
			sum += D
		}

		if N == 2 {
			Fprintln(out, 0)
			continue
		}

		min := max*(N-1) - sum
		if min < 0 {
			Fprintln(out, N-1+min)
		} else {
			Fprintln(out, min)
		}

	}
}

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


This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field $$$n \cdot m$$$, consisting of $$$n$$$ rows and $$$m$$$ columns, where point's coordinates $$$(x, y)$$$ mean it is situated in the $$$x$$$-th row and $$$y$$$-th column, considering numeration from one ($$$1 \leq x \leq n, 1 \leq y \leq m$$$). Initially, you stand in the cell $$$(1, 1)$$$. Every move you can jump from cell $$$(x, y)$$$, which you stand in, by any non-zero vector $$$(dx, dy)$$$, thus you will stand in the $$$(x+dx, y+dy)$$$ cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!

The first and only line contains two positive integers $$$n, m$$$ ($$$1 \leq n \cdot m \leq 10^{6}$$$) — the number of rows and columns of the field respectively.

Print "-1" (without quotes) if it is impossible to visit every cell exactly once. Else print $$$n \cdot m$$$ pairs of integers, $$$i$$$-th from them should contain two integers $$$x_i, y_i$$$ ($$$1 \leq x_i \leq n, 1 \leq y_i \leq m$$$) — cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have $$$(1, 1)$$$ coordinates, according to the statement.

NoteThe vectors from the first example in the order of making jumps are $$$(0, 2), (0, -1), (1, 0), (0, 1), (0, -2)$$$.

// Author: sighduck
// URL: https://codeforces.com/contest/1179/problem/B

package main

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

type Cell struct {
	X int
	Y int
}

func processRow(topRow int, bottomRow int, m int) []Cell {
	cells := []Cell{}
	if topRow%2 == 1 {
		for i := 1; i <= m; i++ {
			cells = append(cells, Cell{X: topRow, Y: i})
			cells = append(cells, Cell{X: bottomRow, Y: m - i + 1})
		}
	} else {
		for i := 1; i <= m; i++ {
			cells = append(cells, Cell{X: topRow, Y: m - i + 1})
			cells = append(cells, Cell{X: bottomRow, Y: i})
		}
	}
	return cells
}

func processMiddleRow(row int, m int) []Cell {
	cells := []Cell{}
	for i := 0; i < m/2; i++ {
		cells = append(cells, Cell{X: row, Y: i + 1})
		cells = append(cells, Cell{X: row, Y: m - i})
	}
	if m%2 == 1 {
		cells = append(cells, Cell{X: row, Y: m/2 + 1})
	}
	return cells
}

func Solve(n int, m int) []Cell {
	cells := []Cell{}
	for i := 1; i <= n/2; i++ {
		for _, cell := range processRow(i, n-i+1, m) {
			cells = append(cells, cell)
		}
	}
	if n%2 == 1 {
		for _, cell := range processMiddleRow(n/2+1, m) {
			cells = append(cells, cell)
		}
	}
	return cells
}

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

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)

	cells := Solve(n, m)
	for _, cell := range cells {
		fmt.Fprintf(writer, "%d %d\n", cell.X, cell.Y)
	}
}

// Author: sighduck
// URL: https://codeforces.com/contest/1179/problem/B

package main

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

type Cell struct {
	X int
	Y int
}

func processRow(topRow int, bottomRow int, m int) []Cell {
	cells := []Cell{}
	if topRow%2 == 1 {
		for i := 1; i <= m; i++ {
			cells = append(cells, Cell{X: topRow, Y: i})
			cells = append(cells, Cell{X: bottomRow, Y: m - i + 1})
		}
	} else {
		for i := 1; i <= m; i++ {
			cells = append(cells, Cell{X: topRow, Y: m - i + 1})
			cells = append(cells, Cell{X: bottomRow, Y: i})
		}
	}
	return cells
}

func processMiddleRow(row int, m int) []Cell {
	cells := []Cell{}
	for i := 0; i < m/2; i++ {
		cells = append(cells, Cell{X: row, Y: m - i})
		cells = append(cells, Cell{X: row, Y: i + 1})
	}
	if m%2 == 1 {
		cells = append(cells, Cell{X: row, Y: m/2 + 1})
	}
	return cells
}

func Solve(n int, m int) []Cell {
	cells := []Cell{}
	for i := 1; i <= n/2; i++ {
		for _, cell := range processRow(i, n-i+1, m) {
			cells = append(cells, cell)
		}
	}
	if n%2 == 1 {
		for _, cell := range processMiddleRow(n/2+1, m) {
			cells = append(cells, cell)
		}
	}
	return cells
}

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

	var n, m int
	fmt.Fscanf(reader, "%d %d\n", &n, &m)

	cells := Solve(n, m)
	for _, cell := range cells {
		fmt.Fprintf(writer, "%d %d\n", cell.X, cell.Y)
	}
}


Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.

The first line contains the number n (1 ≤ n ≤ 3·105) — the length of the glade. The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1, b2, ..., bn (1 ≤ bi ≤ 106) is the growth rate of mushrooms in the second row of the glade.

Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.

NoteIn the first test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.In the second test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.

package main

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

// func - row and col must be in [0,1]
// idx - zig zag that many number of columns
func f1(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == 0 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func f2(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == idx%2 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	suff := make([]int64, n+1)
	for i := n - 1; i >= 0; i-- {
		suff[i] = suff[i+1] + int64(a[0][i]+a[1][i])
	}

	cur := int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f1(0, r, c, a)-1) * int64(a[r][c])
		}
	}

	ans := cur
	for c := 2; c < n; c += 2 {
		cur -= int64(f1(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f1(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f1(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f1(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f1(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f1(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f1(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f1(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	cur = int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f2(1, r, c, a)-1) * int64(a[r][c])
		}
	}

	if cur > ans {
		ans = cur
	}

	for c := 3; c < n; c += 2 {
		cur -= int64(f2(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f2(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f2(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f2(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f2(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f2(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f2(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f2(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	fmt.Println(ans)
}

package main

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

// func - row and col must be in [0,1]
// idx - zig zag that many number of columns
func f(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == idx%2 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	suff := make([]int64, n+1)
	for i := n - 1; i >= 0; i-- {
		suff[i] = suff[i+1] + int64(a[0][i]+a[1][i])
	}

	cur := make([]int64, 2)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			cur[0] += int64(f(0, r, c, a)-1) * int64(a[r][c])
			cur[1] += int64(f(1, r, c, a)-1) * int64(a[r][c])
		}
	}

	ans := cur[0]
	if cur[1] > ans {
		ans = cur[1]
	}
	for c := 2; c < n; c++ {
		diff := int64(0)
		diff -= int64(f(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		diff -= int64(f(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		diff -= int64(f(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		diff -= int64(f(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		diff += int64(f(c, 0, c-2, a)-1) * int64(a[0][c-2])
		diff += int64(f(c, 1, c-2, a)-1) * int64(a[1][c-2])
		diff += int64(f(c, 0, c-1, a)-1) * int64(a[0][c-1])
		diff += int64(f(c, 1, c-1, a)-1) * int64(a[1][c-1])
		diff += suff[c] * 2

		cur[c%2] += diff
		if cur[c%2] > ans {
			ans = cur[c%2]
		}
	}

	fmt.Println(ans)
}

package main

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

// func - row and col must be in [0,1]
// idx - zig zag that many number of columns
func f1(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == 0 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func f2(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == 1 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	suff := make([]int64, n+1)
	for i := n - 1; i >= 0; i-- {
		suff[i] = suff[i+1] + int64(a[0][i]+a[1][i])
	}

	cur := int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f1(0, r, c, a)-1) * int64(a[r][c])
		}
	}

	ans := cur
	for c := 2; c < n; c += 2 {
		cur -= int64(f1(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f1(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f1(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f1(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f1(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f1(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f1(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f1(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	cur = int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f2(1, r, c, a)-1) * int64(a[r][c])
		}
	}

	if cur > ans {
		ans = cur
	}

	for c := 3; c < n; c += 2 {
		cur -= int64(f2(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f2(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f2(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f2(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f2(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f2(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f2(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f2(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	fmt.Println(ans)
}

package main

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

// func - row and col must be in [0,1]
// idx - zig zag that many number of columns
func f(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == idx%2 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	suff := make([]int64, n+1)
	for i := n - 1; i >= 0; i-- {
		suff[i] = suff[i+1] + int64(a[0][i]+a[1][i])
	}

	cur := int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			cur += int64(f(0, r, c, a)-1) * int64(a[r][c])
		}
	}

	ans := cur
	for c := 2; c < n; c += 2 {
		cur -= int64(f(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	cur = int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f(1, r, c, a)-1) * int64(a[r][c])
		}
	}

	if cur > ans {
		ans = cur
	}

	for c := 3; c < n; c += 2 {
		cur -= int64(f(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	fmt.Println(ans)
}

package main

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

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	ans1, ans2 := 0.0, 0.0
	for i := 0; i < (2 * n); i++ {
		ans1 += float64(i) * float64(f1(i, a))
		ans2 += float64(i) * float64(f2(i, a))
	}
	fmt.Println(math.Max(ans1, ans2))
}

func f1(t int, a [][]int) int {
	length := len(a[0])
	if t < length {
		return a[0][t]
	} else {
		return a[1][2*length-t-1]
	}
}

func f2(t int, a [][]int) int {
	col := t / 2
	var row int
	if t%4 < 2 {
		row = t % 2
	} else {
		row = 1 - t%2
	}
	return a[row][col]
}

package main

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

// func - row and col must be in [0,1]
// idx - zig zag that many number of columns
func f1(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == 0 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	suff := make([]int64, n+1)
	for i := n - 1; i >= 0; i-- {
		suff[i] = suff[i+1] + int64(a[0][i]+a[1][i])
	}

	cur := int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f1(0, r, c, a)-1) * int64(a[r][c])
		}
	}

	ans := cur
	for c := 2; c < n; c += 2 {
		cur -= int64(f1(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f1(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f1(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f1(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f1(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f1(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f1(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f1(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	fmt.Println(ans)
}

package main

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

// func - row and col must be in [0,1]
// idx - zig zag that many number of columns
func f1(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 2
		} else {
			return ans + 1
		}
	} else {
		if row == 0 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	suff := make([]int64, n+1)
	for i := n - 1; i >= 0; i-- {
		suff[i] = suff[i+1] + int64(a[0][i]+a[1][i])
	}

	cur := int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(0, r, c, a))
			cur += int64(f1(0, r, c, a)-1) * int64(a[r][c])
		}
	}

	ans := cur
	for c := 2; c < n; c += 2 {
		cur -= int64(f1(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f1(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f1(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f1(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f1(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f1(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f1(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f1(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	fmt.Println(ans)
}

package main

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

// func - row and col must be in [0,1]
// idx - zig zag that many number of columns
func f1(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == 0 {
			return idx*2 + (col - idx + 1)
		} else {
			return idx*2 + (N - idx) + (N - col)
		}
	}
}

func f2(idx int, row int, col int, a [][]int) int {
	N := len(a[0])
	if col < idx {
		ans := col * 2
		if (col%4)%2 == row%2 {
			return ans + 1
		} else {
			return ans + 2
		}
	} else {
		if row == idx%2 {
			return idx*2 + (N - idx) + (N - col)
		} else {
			return idx*2 + (col - idx + 1)
		}
	}
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	nstr := scanner.Text()
	n, _ := strconv.Atoi(nstr)

	a := make([][]int, 2)
	for i := 0; i < len(a); i++ {
		a[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[0][i], _ = strconv.Atoi(txt)
	}
	for i := 0; i < n; i++ {
		scanner.Scan()
		txt := scanner.Text()
		a[1][i], _ = strconv.Atoi(txt)
	}

	suff := make([]int64, n+1)
	for i := n - 1; i >= 0; i-- {
		suff[i] = suff[i+1] + int64(a[0][i]+a[1][i])
	}

	cur := int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f1(0, r, c, a)-1) * int64(a[r][c])
		}
	}

	ans := cur
	for c := 2; c < n; c += 2 {
		cur -= int64(f1(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f1(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f1(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f1(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f1(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f1(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f1(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f1(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	cur = int64(0)
	for r := 0; r < 2; r++ {
		for c := 0; c < n; c++ {
			//fmt.Println(r, c, f1(2, r, c, a)-1)
			cur += int64(f2(1, r, c, a)-1) * int64(a[r][c])
		}
	}

	if cur > ans {
		ans = cur
	}

	for c := 3; c < n; c += 2 {
		cur -= int64(f2(c-2, 0, c-2, a)-1) * int64(a[0][c-2])
		cur -= int64(f2(c-2, 1, c-2, a)-1) * int64(a[1][c-2])
		cur -= int64(f2(c-2, 0, c-1, a)-1) * int64(a[0][c-1])
		cur -= int64(f2(c-2, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += int64(f2(c, 0, c-2, a)-1) * int64(a[0][c-2])
		cur += int64(f2(c, 1, c-2, a)-1) * int64(a[1][c-2])
		cur += int64(f2(c, 0, c-1, a)-1) * int64(a[0][c-1])
		cur += int64(f2(c, 1, c-1, a)-1) * int64(a[1][c-1])

		cur += suff[c] * 2
		if cur > ans {
			ans = cur
		}
	}

	fmt.Println(ans)
}


You are given a rectangular table 3 × n. Each cell contains an integer. You can move from one cell to another if they share a side.Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.

The first line contains an integer n (1 ≤ n ≤ 105)  — the number of columns in the table. Next three lines contain n integers each  — the description of the table. The j-th number in the i-th line corresponds to the cell aij ( - 109 ≤ aij ≤ 109) of the table.

Output the maximum sum of numbers on a path from the upper left cell to the bottom right cell of the table, that doesn't visit any of the cells twice.

NoteThe path for the first example:  The path for the second example:

package main

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

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	defer w.Flush()
	for I(&n) == nil {
		solve(n)
	}
}

var in [][3]int64
var n int

func solve(n int) {
	in = make([][3]int64, n+1)
	for i := 0; i < 3; i++ {
		for j := 1; j <= n; j++ {
			I(&in[j][i])
		}
	}
	arr := make([][4]int64, n+1)
	for i := 0; i <= n; i++ {
		for j := 0; j <= 3; j++ {
			if j == 0 && i == 0 {
				continue
			}
			arr[i][j] = -1e18
		}
	}
	for i := 1; i <= n; i++ {
		max(&arr[i][0], arr[i-1][0]+in[i][0])
		max(&arr[i][0], arr[i-1][1]+in[i][0]+in[i][1])
		max(&arr[i][0], arr[i-1][2]+in[i][0]+in[i][1]+in[i][2])

		max(&arr[i][1], arr[i-1][0]+in[i][0]+in[i][1])
		max(&arr[i][1], arr[i-1][1]+in[i][1])
		max(&arr[i][1], arr[i-1][2]+in[i][1]+in[i][2])

		max(&arr[i][2], arr[i-1][0]+in[i][0]+in[i][1]+in[i][2])
		max(&arr[i][2], arr[i-1][1]+in[i][1]+in[i][2])
		max(&arr[i][2], arr[i-1][2]+in[i][2])

		d := in[i][0] + in[i][1] + in[i][2]
		max(&arr[i][0], arr[i-1][3]+d)
		max(&arr[i][2], arr[i-1][3]+d)

		max(&arr[i][3], arr[i-1][0]+d)
		max(&arr[i][3], arr[i-1][2]+d)
	}
	O(arr[n][2], "\n")
}

func max(a *int64, b int64) {
	if *a < b {
		*a = b
	}
}


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$) —   $$$(p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1$$$, where $$$\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).

For every test, output any good permutation of length $$$n$$$ on a separate line.

package main

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

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

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

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

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

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
}

var (
	dx [4]int = [4]int{-1, 0, 1, 0}
	dy [4]int = [4]int{0, 1, 0, -1}
)

func solve() {
	n := nextInt()
	for i := 0; i < n; i++ {
		printf("%d ", i+1)
	}
	printf("\n")
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		name := "in"
		file1, err := os.Open(name + ".in")
		if err != nil {
			log.Fatal(err)
		}
		// file2, err := os.Create(name + ".out")
		// if err != nil {
		// 	log.Fatal(err)
		// }
		in = bufio.NewReaderSize(file1, 8192)
		// out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	for t := nextInt(); t > 0; t-- {
		solve()
	}
}

package main

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

func main() {
	var t, n int
	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &n)
		for j := 0; j < n; j++ {
			fmt.Printf("%d ", j+1)
		}
		fmt.Println()
	}
}

package main

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

func main() {
	io := NewFastIO(os.Stdin, os.Stdout)
	defer io.Flush()

	for t := io.NextInt(); t > 0; t-- {
		n := io.NextInt()
		a := make([]int, n)
		for i := range a {
			a[i] = i + 1
		}
		io.PrintlnInts(a...)
	}
}

type FastIO struct {
	*bufio.Reader
	*bufio.Writer
	c [1]byte
}

func NewFastIO(r io.Reader, w io.Writer) *FastIO {
	return &FastIO{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)}
}

func (f *FastIO) readC() byte {
	f.Read(f.c[:])
	return f.c[0]
}

func (f *FastIO) NextInt() int {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	neg := false
	if c == '-' {
		neg = true
		c = f.readC()
	}
	n := 0
	for ; '0' <= c && c <= '9'; c = f.readC() {
		n = n*10 + int(c) - '0'
	}
	if neg {
		return -n
	}
	return n
}

func (f *FastIO) NextInts(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = f.NextInt()
	}
	return a
}

func (f *FastIO) Next() string {
	c := f.readC()
	for ; c <= ' '; c = f.readC() {
	}
	var s []byte
	for ; c > ' '; c = f.readC() {
		s = append(s, f.c[0])
	}
	return string(s)
}

func (f *FastIO) Println(a ...interface{}) {
	fmt.Fprintln(f.Writer, a...)
}

func (f *FastIO) Print(a ...interface{}) {
	fmt.Fprint(f.Writer, a...)
}

func (f *FastIO) PrintInts(a ...int) {
	if len(a) > 0 {
		f.Print(a[0])
		for _, x := range a[1:] {
			f.Print(" ", x)
		}
	}
}

func (f *FastIO) PrintlnInts(a ...int) {
	f.PrintInts(a...)
	f.Println()
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var t int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		var n int
		fmt.Fscan(in, &n)
		for j := 1; j <= n; j++ {
			fmt.Print(j, " ")
		}
		fmt.Println()
	}
}

package main

import (
	"fmt"
)

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

/*
URL:
https://codeforces.com/contest/1391/problem/A
*/

package main

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

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

const (
	// General purpose
	MOD = 1000000000 + 7
	// MOD          = 998244353
	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
)

var (
	t int
	n int
)

func main() {
	t = ReadInt()
	for tc := 0; tc < t; tc++ {
		n = ReadInt()

		solve()
	}
}

func solve() {
	ans := []int{}
	for i := 1; i <= n; i++ {
		ans = append(ans, i)
	}

	fmt.Println(PrintIntsLine(ans...))
}

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

/********** bufio setting **********/

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

/********** 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...)

/*********** Input ***********/

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

/*********** Output ***********/

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

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

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

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

// 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
}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	for tim := 1; tim <= t; tim++ {
		var n int
		fmt.Scan(&n)
		for i := 1; i <= n; i++ {
			fmt.Printf("%d ", i)
		}
		fmt.Printf("\n")
	}
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		solve()
		t--
	}
}

func solve() {
	var n int
	fmt.Scan(&n)
	for i := 1; i <= n; i++ {
		fmt.Printf("%d ", i)
	}
	fmt.Println()
}

package main

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

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

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

func main() {
	defer writer.Flush()

	var i int
	fmt.Scan(&i)
	for j := 0; j < i; j++ {
		var n int
		fmt.Scan(&n)
		for k := 1; k <= n; k++ {
			fmt.Printf("%d ", k)
		}
		fmt.Println()
	}
}

package main

import "fmt"

func main() {
	//app := fiber.New()
	//
	//app.Get("/", func(c *fiber.Ctx) {
	//	c.Send("Hello, World 👋!")
	//})
	//
	//app.Listen(3000)

	var a, t int
	fmt.Scanf("%d\n",&t)
	for k:=0; k<t; k++{
		fmt.Scanf("%d\n", &a)
		for i:=1; i <=a; i++{
			fmt.Print(i)
			fmt.Print(" ")
		}
		fmt.Println()
	}

}

package main

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

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) Scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) Scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) Scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) Print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) Println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) Printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	var testcases int
	con.Scan(&testcases)
	for testcase := 0; testcase < testcases; testcase++ {
		var n int
		con.Scan(&n)
		for i := 1; i <= n; i++ {
			con.Print(i)
			if i != n {
				con.Print(" ")
			}
		}
		con.Println()
	}
	return nil
}

package main

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

var reader *bufio.Reader
var writer *bufio.Writer

func main() {
	//ioutil.WriteFile("input.txt", []byte(generateInput()), os.ModeExclusive)

	debug := 1
	filename := "input.txt"
	if debug != 0 && len(os.Args) > 1 && os.Args[1] == "debug" {
		file, _ := os.Open(filename)
		reader = bufio.NewReaderSize(file, 1024*1024)
	} else {
		reader = bufio.NewReaderSize(os.Stdin, 1024*1024)
	}
	writer = bufio.NewWriterSize(os.Stdout, 1024*1024)

	t := readInt()
	for ; t > 0; t-- {
		n := readInt()
		for ; n > 0; n-- {
			fmt.Fprintf(writer, "%d ", n)
		}
		fmt.Fprintln(writer)
	}

	writer.Flush()
}

func readInts() []int {
	line := readLine()
	fields := strings.Fields(line)
	res := make([]int, len(fields))
	for i := range fields {
		v, _ := strconv.ParseInt(fields[i], 10, 64)
		res[i] = int(v)
	}
	return res
}

func readInt() int {
	line := readLine()
	n, _ := strconv.ParseInt(line, 10, 64)
	return int(n)
}

func readLine() string {
	str, _, err := reader.ReadLine()
	if err == io.EOF {
		return ""
	}

	return strings.TrimRight(string(str), "\r\n")
}

package main

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

var (
	reader *bufio.Reader
	writer *bufio.Writer
)

func init() {
	reader = bufio.NewReader(os.Stdin)
	writer = bufio.NewWriter(os.Stdout)
}
func scanf(format string, args ...interface{}) (int, error) {
	return fmt.Fscanf(reader, format, args...)
}

func printf(format string, args ...interface{}) (int, error) {
	return fmt.Fprintf(writer, format, args...)
}

func getAddresses(n []int) []interface{} {
	adds := make([]interface{}, len(n))
	for i := 0; i < len(n); i++ {
		adds[i] = &n[i]
	}
	return adds
}

func main() {
	defer writer.Flush()
	var t int
	scanf("%d\n", &t)
	arr := make([]int, t)
	result := make([]string, t)
	for i := 0; i < t; i++ {
		scanf("%d\n", &arr[i])
		var output strings.Builder
		for j := 0; j < arr[i]; j++ {
			output.WriteString(fmt.Sprintf("%d ", j+1))
		}
		result[i] = output.String()
	}
	for i := 0; i < t; i++ {
		printf("%s\n", result[i])
	}

}

package main

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

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

func printf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fprintf(out, x, a...)
}

func scanf(x string, a ...interface{}) (n int, err error) {
	return fmt.Fscanf(in, x, a...)
}

type priorityQueue [][2]int

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

func (pq priorityQueue) Less(i, j int) bool {
	return pq[i][1] > pq[j][1]
}

func (pq priorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.([2]int))
}

func (pq *priorityQueue) Pop() (res interface{}) {
	res = (*pq)[len(*pq)-1]
	*pq = (*pq)[:len(*pq)-1]
	return res
}

var err error

func next() (n string) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return ""
		}
	}
}

func nextInt() (n int) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextLong() (n int64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func nextDouble() (n float64) {
	for {
		_, err = scanf("%v", &n)
		if err == nil {
			return n
		}
		if err.Error() == "EOF" {
			return 0
		}
	}
}

func Fill(a []int, v int) {
	for i := range a {
		a[i] = v
	}
}

func FillB(a []bool, v bool) {
	for i := range a {
		a[i] = v
	}
}

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
}

var (
	dx [4]int = [4]int{-1, 0, 1, 0}
	dy [4]int = [4]int{0, 1, 0, -1}
)

func solve() {
	n := nextInt()
	for i := 0; i < n; i++ {
		printf("%d ", n)
	}
	printf("\n")
}

func main() {
	in = bufio.NewReaderSize(os.Stdin, 8192)
	out = bufio.NewWriterSize(os.Stdout, 8192)
	if false {
		name := "in"
		file1, err := os.Open(name + ".in")
		if err != nil {
			log.Fatal(err)
		}
		// file2, err := os.Create(name + ".out")
		// if err != nil {
		// 	log.Fatal(err)
		// }
		in = bufio.NewReaderSize(file1, 8192)
		// out = bufio.NewWriterSize(file2, 8192)
	}
	defer out.Flush()

	for t := nextInt(); t > 0; t-- {
		solve()
	}
}

package main

import (
	"fmt"
)

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

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)
	for t > 0 {
		solve()
		t--
	}
}

func solve() {
	var n int
	fmt.Scan(&n)
	for i := 1; i <= n; i++ {
		fmt.Print(i)
		fmt.Print(' ')
	}
	fmt.Println()
}

package main

import "fmt"

func main() {
	//app := fiber.New()
	//
	//app.Get("/", func(c *fiber.Ctx) {
	//	c.Send("Hello, World 👋!")
	//})
	//
	//app.Listen(3000)
	var a int
	fmt.Scanf("%d", &a)
	for i:=1; i <=a; i++{
		fmt.Println(i)
	}

}

package main

import "fmt"

func main() {
	//app := fiber.New()
	//
	//app.Get("/", func(c *fiber.Ctx) {
	//	c.Send("Hello, World 👋!")
	//})
	//
	//app.Listen(3000)

	var a, t int
	fmt.Scanf("%d",&t)
	for k:=0; k<t; k++{
		fmt.Scanf("%d", &a)
		for i:=1; i <=a; i++{
			fmt.Println(i)
		}
	}

}

package main

import "fmt"

func main() {
	//app := fiber.New()
	//
	//app.Get("/", func(c *fiber.Ctx) {
	//	c.Send("Hello, World 👋!")
	//})
	//
	//app.Listen(3000)

	var a, t int
	fmt.Scanf("%d",&t)
	for k:=0; k<t; k++{
		fmt.Scanf("%d", &a)
		for i:=1; i <=a; i++{
			fmt.Print(i)
			fmt.Print(" ")
		}
		fmt.Println()
	}

}


You have decided to open a new school. You have already found $$$n$$$ teachers and $$$m$$$ groups of students. The $$$i$$$-th group of students consists of $$$k_i \geq 2$$$ students. You know age of each teacher and each student. The ages of teachers are $$$a_1, a_2, \ldots, a_n$$$ and the ages of students of the $$$i$$$-th group are $$$b_{i, 1}, b_{i, 2}, \ldots, b_{i, k_i}$$$.To start lessons you should assign the teacher to each group of students. Such assignment should satisfy the following requirements:  To each group exactly one teacher assigned.  To each teacher at most $$$1$$$ group of students assigned.  The average of students' ages in each group doesn't exceed the age of the teacher assigned to this group. The average of set $$$x_1, x_2, \ldots, x_k$$$ of $$$k$$$ integers is $$$\frac{x_1 + x_2 + \ldots + x_k}{k}$$$.Recently you have heard that one of the students will refuse to study in your school. After this, the size of one group will decrease by $$$1$$$ while all other groups will remain unchanged.You don't know who will refuse to study. For each student determine if you can start lessons in case of his refusal.Note, that it is not guaranteed that it is possible to start lessons before any refusal.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq m \leq n \leq 10^5$$$) — the number of teachers and the number of groups of students. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — the ages of teachers. The next $$$2m$$$ lines contains descriptions of groups.  The first line of description of group contains a single integer $$$k_i$$$ ($$$2 \leq k_i \leq 10^5$$$) — the number of students in this group.  The second line of description of group contains $$$k_i$$$ integers $$$b_{i, 1}, b_{i, 2}, \ldots, b_{i, k_i}$$$ ($$$1 \leq b_{i, j} \leq 10^5$$$) — the ages of students of this group. It is guaranteed that the total sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$ and that the total sum of $$$k_1 + k_2 + \ldots + k_m$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$

For each test case output string of symbols $$$0$$$ and $$$1$$$ of length $$$k_1 + k_2 + \ldots + k_m$$$. The $$$i$$$-th symbol of this string should be equals $$$1$$$ if it is possible to start lessons in case of the $$$i$$$-th student refuse and it should be equals $$$0$$$ otherwise. Students are numbered by integers from $$$1$$$ to $$$k_1 + k_2 + \ldots + k_m$$$ in the order they appear in the input. Thus, students of the $$$1$$$-st group are numbered by integers $$$1$$$, $$$2$$$, $$$\ldots$$$, $$$k_1$$$, students of the $$$2$$$-nd group are numbered by integers $$$k_1 + 1$$$, $$$k_1 + 2$$$, $$$\ldots$$$, $$$k_1 + k_2$$$ and so on.

NoteIn the first test case there is one group of students with average age $$$\frac{25+16+37}{3}=26$$$ and one teacher with age $$$30$$$. There exists only one assignment that allows to start lessons.If the student with age $$$16$$$ will refuse to study, the average age of students in this group will become $$$\frac{25+37}{2}=31$$$ so there won't be any assignment that allows to start lessons.In the second test case it is impossible to start lessons initially. However, if the $$$3$$$-rd student with age $$$111$$$ will refuse to study, the average ages of groups will become $$$\frac{4 + 5}{2}=4.5$$$ and $$$\frac{11+11}{2} = 11$$$ correspondingly. Then it is possible to assing the first group to the first teacher and the second group to the third teacher.

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1621E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type group struct {
		a []int
		s int64
		i int
	}

	var T, n, m, k int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		te := make(sort.IntSlice, n)
		for i := range te {
			Fscan(in, &te[i])
		}
		sort.Sort(sort.Reverse(te))
		te = te[:m]
		gs := make([]group, m)
		for i := range gs {
			Fscan(in, &k)
			a := make([]int, k)
			for j := range a {
				Fscan(in, &a[j])
				gs[i].s += int64(a[j])
			}
			gs[i].a = a
			gs[i].i = i
		}
		sort.Slice(gs, func(i, j int) bool { a, b := gs[i], gs[j]; return a.s*int64(len(b.a)) > b.s*int64(len(a.a)) })

		match := make([]int, m+1)
		matchL := make([]int, m+1)
		matchR := make([]int, m+1)
		for i, v := range te {
			match[i+1] = match[i]
			if int64(v)*int64(len(gs[i].a)) >= gs[i].s {
				match[i+1]++
			}
			matchL[i+1] = matchL[i]
			if i > 0 && int64(v)*int64(len(gs[i-1].a)) >= gs[i-1].s {
				matchL[i+1]++
			}
			matchR[i+1] = matchR[i]
			if i < m-1 && int64(v)*int64(len(gs[i+1].a)) >= gs[i+1].s {
				matchR[i+1]++
			}
		}

		ans := make([][]byte, m)
		for i, g := range gs {
			res := bytes.Repeat([]byte{'0'}, len(g.a))
			for ri, v := range g.a {
				v := int64(v)
				l := int64(len(g.a))
				if v*l == g.s {
					if match[m] == m {
						res[ri] = '1'
					}
					continue
				}
				j := sort.Search(len(te), func(j int) bool { return int64(te[j])*(l-1) < g.s-v }) - 1
				if j < 0 {
					continue
				}
				if v*l < g.s { // avg ↑
					if matchL[i+1]-matchL[j+1] == i-j && match[m]-(match[i+1]-match[j]) == m-(i+1-j) {
						res[ri] = '1'
					}
				} else { // avg ↓
					if matchR[j]-matchR[i] == j-i && match[m]-(match[j+1]-match[i]) == m-(j+1-i) {
						res[ri] = '1'
					}
				}
			}
			ans[g.i] = res
		}
		for _, s := range ans {
			Fprintf(out, "%s", s)
		}
		Fprintln(out)
	}
}

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

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1621E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type group struct {
		a []int
		s int64
		i int
	}

	var T, n, m, k int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		te := make(sort.IntSlice, n)
		for i := range te {
			Fscan(in, &te[i])
		}
		sort.Sort(sort.Reverse(te))
		te = te[:m]
		gs := make([]group, m)
		for i := range gs {
			Fscan(in, &k)
			a := make([]int, k)
			for j := range a {
				Fscan(in, &a[j])
				gs[i].s += int64(a[j])
			}
			gs[i].a = a
			gs[i].i = i
		}
		sort.Slice(gs, func(i, j int) bool { a, b := gs[i], gs[j]; return a.s*int64(len(b.a)) > b.s*int64(len(a.a)) })

		match := make([]int, m+1)
		matchL := make([]int, m+1)
		matchR := make([]int, m+1)
		for i, v := range te {
			match[i+1] = match[i]
			if int64(v)*int64(len(gs[i].a)) >= gs[i].s {
				match[i+1]++
			}
			matchL[i+1] = matchL[i]
			if i > 0 && int64(v)*int64(len(gs[i-1].a)) >= gs[i-1].s {
				matchL[i+1]++
			}
			matchR[i+1] = matchR[i]
			if i < m-1 && int64(v)*int64(len(gs[i+1].a)) >= gs[i+1].s {
				matchR[i+1]++
			}
		}

		ans := make([][]byte, m)
		for i, g := range gs {
			res := bytes.Repeat([]byte{'0'}, len(g.a))
			for ri, v := range g.a {
				v := int64(v)
				l := int64(len(g.a))
				if v*l == g.s {
					if match[m] == m {
						res[ri] = '1'
					}
				} else if v*l < g.s { // avg ↑
					s := g.s - v
					l := l - 1
					j := sort.Search(len(te), func(j int) bool { return int64(te[j])*l < s }) - 1
					if j >= 0 {
						if matchL[i+1]-matchL[j+1] == i-j && match[m]-(match[i+1]-match[j]) == m-(i+1-j) {
							res[ri] = '1'
						}
					}
				} else { // avg ↓
					s := g.s - v
					l := l - 1
					j := sort.Search(len(te), func(j int) bool { return int64(te[j])*l < s }) - 1
					if j >= 0 {
						if matchR[j]-matchR[i] == j-i && match[m]-(match[j+1]-match[i]) == m-(j+1-i) {
							res[ri] = '1'
						}
					}
				}
			}
			ans[g.i] = res
		}
		for _, s := range ans {
			Fprintf(out, "%s", s)
		}
		Fprintln(out)
	}
}

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

package main

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

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

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

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

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

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

func solve() {
	var n, m int64
	scan(&n, &m)
	var items = make([]item, 0, n+m)
	for i := int64(0); i < n; i++ {
		var x int64
		scan(&x)
		items = append(items, item{x, 1, 1, nil})
	}
	var studentNum int64
	for i := int64(0); i < m; i++ {
		var (
			x, s, k int64
			ss      [][2]int64
		)
		scan(&k)
		for j := int64(0); j < k; j++ {
			scan(&x)
			s += x
			ss = append(ss, [2]int64{x, studentNum})
			studentNum++
		}
		items = append(items, item{s, k, -1, ss})
	}
	sort.Slice(items, func(i, j int) bool { return itemless(items[i], items[j]) })
	var suffsum = make([]int64, len(items))
	for i := len(items) - 1; i >= 0; i-- {
		suffsum[i] = items[i].typ
		if i+1 < len(items) {
			suffsum[i] += suffsum[i+1]
		}
	}
	var (
		_, get, _ = NewSparseTable(suffsum, min)
		query     = func(l, r int) int64 {
			var res int64 = 1 << 30
			if 0 <= l && l <= r && r < len(items) {
				res = get(l, r)
			}
			return res
		}
		ans    = make([]byte, studentNum)
		getans = func(prevpos int, olditem item, student [2]int64) byte {
			newitem := item{
				ages: olditem.ages - student[0],
				cnt:  olditem.cnt - 1,
				typ:  olditem.typ,
			}
			l, r := -1, len(items)
			for r-l > 1 {
				m := l + (r-l)/2
				if itemless(items[m], newitem) {
					l = m
				} else {
					r = m
				}
			}
			// printf("%v %v\n", newitem, r)
			if r > prevpos {
				mn1, mn2, mn3 := query(0, prevpos-1), query(prevpos+1, l), query(r, len(items)-1)
				sum := int64(-2)
				if r < len(items) {
					sum = suffsum[r]
				}
				if mn1 >= 0 && mn2 >= 1 && mn3 >= 0 && sum >= 1 {
					return '1'
				}
				return '0'
			}
			if r < prevpos {
				mn1, mn2, mn3 := query(0, l), query(r, prevpos-1), query(prevpos+1, len(items)-1)
				sum := int64(-2)
				if r < len(items) {
					sum = suffsum[r]
				}
				if mn1 >= 0 && mn2 >= -1 && mn3 >= 0 && sum >= 0 {
					return '1'
				}
				return '0'
			}
			if get(0, len(items)-1) >= 0 {
				return '1'
			}
			return '0'
		}
	)
	// printf("%v\n", items)
	for i, it := range items {
		if it.typ == 1 { // item is teacher
			continue
		}
		for _, student := range it.students {
			ans[student[1]] = getans(i, it, student)
		}
	}
	printf("%v\n", string(ans))
}

type item struct {
	ages, cnt, typ int64
	students       [][2]int64
}

func itemless(a, b item) bool {
	x, y := a.ages*b.cnt, b.ages*a.cnt
	if x == y {
		return a.typ < b.typ
	}
	return x < y
}

func min(e1, e2 int64) int64 {
	if e1 < e2 {
		return e1
	}
	return e2
}

func NewSparseTable(s []int64, op func(e1, e2 int64) int64) (tab [][]int64, get func(l, r int) int64, log2 []int64) {
	var N = len(s)
	log2 = make([]int64, N+1)
	for i := 2; i <= N; i++ {
		log2[i] = log2[i>>1] + 1
	}
	tab = make([][]int64, log2[N]+1)
	for i := range tab {
		tab[i] = make([]int64, N)
	}
	for i := range tab[0] {
		tab[0][i] = s[i]
	}
	for i := 1; i <= int(log2[N]); i++ {
		for j := (1 << i) - 1; j < N; j++ {
			tab[i][j] = op(tab[i-1][j], tab[i-1][j-(1<<(i-1))])
		}
	}
	get = func(l, r int) int64 {
		log := log2[r-l+1]
		return op(tab[log][r], tab[log][l+(1<<log)-1])
	}
	return
}

package main

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

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

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n, m := readTwoNums(reader)
		teachers := readNNums(reader, n)
		groups := make([][]int, m)
		for i := 0; i < m; i++ {
			sz := readNum(reader)
			groups[i] = readNNums(reader, sz)
		}
		res := solve(teachers, groups)
		buf.WriteString(res)
		buf.WriteByte('\n')
	}
	fmt.Print(buf.String())
}

func normalize(s string) string {

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

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(teachers []int, groups [][]int) string {
	sort.Ints(teachers)
	reverse(teachers)

	avg := make([]StudentGroup, len(groups))

	for i, g := range groups {
		avg[i] = StudentGroup{Pair{sum(g), len(g)}, i}
	}

	sort.Sort(sort.Reverse(SGS(avg)))

	pos := make([]int, len(groups))

	for i, sg := range avg {
		pos[sg.pos] = i
	}

	m := len(avg)
	next := make([]int, m)
	prev := make([]int, m)
	curr := make([]int, m)
	for i := 0; i < m-1; i++ {
		if (Pair{int64(teachers[i+1]), 1}).Less(avg[i].group) {
			next[i] = 1
		}
	}

	for i := 0; i < m; i++ {
		if (Pair{int64(teachers[i]), 1}).Less(avg[i].group) {
			curr[i] = 1
		}
	}

	for i := 1; i < m; i++ {
		if (Pair{int64(teachers[i-1]), 1}).Less(avg[i].group) {
			prev[i] = 1
		}
	}

	for i := 1; i < m; i++ {
		next[i] += next[i-1]
		prev[i] += prev[i-1]
		curr[i] += curr[i-1]
	}

	tot := curr[m-1]
	var buf bytes.Buffer
	for i := 0; i < m; i++ {
		id := pos[i]
		cur := Pair{sum(groups[i]), len(groups[i]) - 1}
		for j := 0; j < len(groups[i]); j++ {
			cur = Pair{cur.first - int64(groups[i][j]), cur.second}
			l, r := -1, m
			for l+1 < r {
				mid := (l + r) / 2
				if !avg[mid].group.Less(cur) {
					l = mid
				} else {
					r = mid
				}
			}
			if r > id {
				r--
			}
			tr := 1
			if (Pair{int64(teachers[r]), 1}).Less(cur) {
				tr = 0
			}
			if min(r, id)-1 >= 0 && curr[min(r, id)-1] > 0 {
				tr = 0
			}
			if curr[max(r, id)] != tot {
				tr = 0
			}
			if r < id && (r > 0 && next[r-1] != next[id-1] || r == 0 && next[id-1] > 0) {
				tr = 0
			}
			if r > id && (prev[r] != prev[id]) {
				tr = 0
			}
			buf.WriteByte(byte('0' + tr))
			cur = Pair{cur.first + int64(groups[i][j]), cur.second}
		}
	}
	return buf.String()
}

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

func max(a, b int) int {
	return a + b - min(a, b)
}

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 sum(arr []int) int64 {
	var res int64
	for _, num := range arr {
		res += int64(num)
	}
	return res
}

type Pair struct {
	first  int64
	second int
}

func (this Pair) Less(that Pair) bool {
	return this.first*int64(that.second) < int64(this.second)*that.first
}

type StudentGroup struct {
	group Pair
	pos   int
}

type SGS []StudentGroup

func (ps SGS) Len() int {
	return len(ps)
}

func (ps SGS) Less(i, j int) bool {
	return ps[i].group.Less(ps[j].group)
}

func (ps SGS) Swap(i, j int) {
	ps[i], ps[j] = ps[j], ps[i]
}

package main

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

// github.com/EndlessCheng/codeforces-go
func CF1621E(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	type group struct {
		a []int
		s int64
		i int
	}

	var T, n, m, k int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &m)
		te := make(sort.IntSlice, n)
		for i := range te {
			Fscan(in, &te[i])
		}
		sort.Sort(sort.Reverse(te))
		te = te[:m]
		gs := make([]group, m)
		for i := range gs {
			Fscan(in, &k)
			a := make([]int, k)
			for j := range a {
				Fscan(in, &a[j])
				gs[i].s += int64(a[j])
			}
			gs[i].a = a
			gs[i].i = i
		}
		sort.Slice(gs, func(i, j int) bool { a, b := gs[i], gs[j]; return a.s*int64(len(b.a)) > b.s*int64(len(a.a)) })

		match := make([]int, m+1)
		matchL := make([]int, m+1)
		matchR := make([]int, m+1)
		for i, v := range te {
			match[i+1] = match[i]
			if int64(v)*int64(len(gs[i].a)) >= gs[i].s {
				match[i+1]++
			}
			matchL[i+1] = matchL[i]
			if i > 0 && int64(v)*int64(len(gs[i-1].a)) >= gs[i-1].s {
				matchL[i+1]++
			}
			matchR[i+1] = matchR[i]
			if i < m-1 && int64(v)*int64(len(gs[i+1].a)) >= gs[i+1].s {
				matchR[i+1]++
			}
		}

		ans := make([][]byte, m)
		for i, g := range gs {
			res := bytes.Repeat([]byte{'0'}, len(g.a))
			for ri, v := range g.a {
				v := int64(v)
				l := int64(len(g.a))
				s := g.s
				if v*l == s {
					if match[m] == m {
						res[ri] = '1'
					}
					continue
				}
				s -= v
				l--
				j := sort.Search(len(te), func(j int) bool { return int64(te[j])*l < s }) - 1
				if j < 0 {
					continue
				}
				if v*l < g.s { // avg ↑
					if matchL[i+1]-matchL[j+1] == i-j && match[m]-(match[i+1]-match[j]) == m-(i+1-j) {
						res[ri] = '1'
					}
				} else { // avg ↓
					if matchR[j]-matchR[i] == j-i && match[m]-(match[j+1]-match[i]) == m-(j+1-i) {
						res[ri] = '1'
					}
				}
			}
			ans[g.i] = res
		}
		for _, s := range ans {
			Fprintf(out, "%s", s)
		}
		Fprintln(out)
	}
}

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

package main

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

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

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

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

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

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

func solve() {
	var n, m int64
	scan(&n, &m)
	var items = make([]item, 0, n+m)
	for i := int64(0); i < n; i++ {
		var x int64
		scan(&x)
		items = append(items, item{x, 1, 1, nil})
	}
	var studentNum int64
	for i := int64(0); i < m; i++ {
		var (
			x, s, k int64
			ss      [][2]int64
		)
		scan(&k)
		for j := int64(0); j < k; j++ {
			scan(&x)
			s += x
			ss = append(ss, [2]int64{x, studentNum})
			studentNum++
		}
		items = append(items, item{s, k, -1, ss})
	}
	sort.Slice(items, func(i, j int) bool { return itemless(items[i], items[j]) })
	var suffsum = make([]int64, len(items))
	for i := len(items) - 1; i >= 0; i-- {
		suffsum[i] = items[i].typ
		if i+1 < len(items) {
			suffsum[i] += suffsum[i+1]
		}
	}
	var (
		_, get, _ = NewSparseTable(suffsum, min)
		query     = func(l, r int) int64 {
			var res int64 = 1 << 30
			if 0 <= l && l <= r && r < len(items) {
				res = get(l, r)
			}
			return res
		}
		ans    = make([]byte, studentNum)
		getans = func(prevpos int, olditem item, student [2]int64) byte {
			newitem := item{
				ages: olditem.ages - student[0],
				cnt:  olditem.cnt - 1,
				typ:  olditem.typ,
			}
			l, r := -1, len(items)
			for r-l > 1 {
				m := l + (r-l)/2
				if itemless(items[m], newitem) {
					l = m
				} else {
					r = m
				}
			}
			// printf("%v %v\n", newitem, r)
			if r > prevpos {
				mn1, mn2, mn3 := query(0, prevpos-1), query(prevpos+1, l), query(r, len(items)-1)
				sum := int64(-2)
				if r < len(items) {
					sum = suffsum[r]
				}
				if mn1 >= 0 && mn2 >= 1 && mn3 >= 0 && sum >= 1 {
					return '1'
				}
				return '0'
			}
			if r < prevpos {
				mn1, mn2, mn3 := query(0, l), query(r, prevpos-1), query(prevpos+1, len(items)-1)
				sum := int64(-2)
				if r < len(items) {
					sum = suffsum[r]
				}
				if mn1 >= 0 && mn2 >= -1 && mn3 >= 0 && sum >= 1 {
					return '1'
				}
				return '0'
			}
			if get(0, len(items)-1) >= 0 {
				return '1'
			}
			return '0'
		}
	)
	// printf("%v\n", items)
	for i, it := range items {
		if it.typ == 1 { // item is teacher
			continue
		}
		for _, student := range it.students {
			ans[student[1]] = getans(i, it, student)
		}
	}
	printf("%v\n", string(ans))
}

type item struct {
	ages, cnt, typ int64
	students       [][2]int64
}

func itemless(a, b item) bool {
	x, y := a.ages*b.cnt, b.ages*a.cnt
	if x == y {
		return a.typ < b.typ
	}
	return x < y
}

func min(e1, e2 int64) int64 {
	if e1 < e2 {
		return e1
	}
	return e2
}

func NewSparseTable(s []int64, op func(e1, e2 int64) int64) (tab [][]int64, get func(l, r int) int64, log2 []int64) {
	var N = len(s)
	log2 = make([]int64, N+1)
	for i := 2; i <= N; i++ {
		log2[i] = log2[i>>1] + 1
	}
	tab = make([][]int64, log2[N]+1)
	for i := range tab {
		tab[i] = make([]int64, N)
	}
	for i := range tab[0] {
		tab[0][i] = s[i]
	}
	for i := 1; i <= int(log2[N]); i++ {
		for j := (1 << i) - 1; j < N; j++ {
			tab[i][j] = op(tab[i-1][j], tab[i-1][j-(1<<(i-1))])
		}
	}
	get = func(l, r int) int64 {
		log := log2[r-l+1]
		return op(tab[log][r], tab[log][l+(1<<log)-1])
	}
	return
}


You are given an undirected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). You have to find the minimum length of path between vertex 1 and vertex n.Note that graph can contain multiple edges and loops. It is guaranteed that the graph is connected.

The first line contains two numbers n and m (1 ≤ n ≤ 100000, n - 1 ≤ m ≤ 100000) — the number of vertices and the number of edges, respectively. Then m lines follow, each line containing three integer numbers x, y and w (1 ≤ x, y ≤ n, 0 ≤ w ≤ 108). These numbers denote an edge that connects vertices x and y and has weight w.

Print one number — the minimum length of path between vertices 1 and n.

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') {
			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)

	n, m := readTwoNums(reader)
	E := make([][]int, m)
	for i := 0; i < m; i++ {
		E[i] = readNNums(reader, 3)
	}

	solver := NewSolver(n, E)

	fmt.Println(solver.Ask(1, n))
}

type Solver struct {
	dp    []int64
	basis [][]int64
	vis   []int
}

func NewSolver(n int, E [][]int) Solver {
	degree := make([]int, n)
	for _, e := range E {
		degree[e[0]-1]++
		degree[e[1]-1]++
	}
	adj := make([][]Pair, n)
	for i := 0; i < n; i++ {
		adj[i] = make([]Pair, 0, degree[i])
	}

	for _, e := range E {
		u, v, w := e[0], e[1], e[2]
		u--
		v--
		adj[u] = append(adj[u], Pair{v, w})
		adj[v] = append(adj[v], Pair{u, w})
	}

	dp := make([]int64, n)
	for i := 0; i < n; i++ {
		dp[i] = -1
	}

	var dfs func(u int, color int, basis []int64)

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

	dfs = func(u int, color int, basis []int64) {
		vis[u] = color
		for _, e := range adj[u] {
			if dp[e.first] < 0 {
				dp[e.first] = dp[u] ^ int64(e.second)
				dfs(e.first, color, basis)
			} else {
				// a loop back
				t := dp[u] ^ dp[e.first] ^ int64(e.second)
				for t > 0 {
					x := clzll(t)
					if basis[x] > 0 {
						t ^= basis[x]
					} else {
						basis[x] = t
						break
					}
				}
			}
		}
	}

	var basis [][]int64

	for i := 0; i < n; i++ {
		if vis[i] < 0 {
			dp[i] = 0
			cur := make([]int64, 64)
			basis = append(basis, cur)
			dfs(i, len(basis), cur)
		}
	}

	return Solver{dp, basis, vis}
}

func (solver Solver) Ask(u, v int) int64 {
	u--
	v--
	if solver.vis[u] != solver.vis[v] {
		return -1
	}
	c := solver.vis[u] - 1
	res := solver.dp[u] ^ solver.dp[v]
	for i := 0; i < 64; i++ {
		if (res>>uint(63-i))&1 > 0 {
			res ^= solver.basis[c][i]
		}
	}
	return res
}

func clzll(num int64) int {
	var pos = 64
	for num > 0 {
		num >>= 1
		pos--
	}
	return pos
}

type Pair struct {
	first, second int
}


You are given a grid with $$$n$$$ rows and $$$m$$$ columns. Rows and columns are numbered from $$$1$$$ to $$$n$$$, and from $$$1$$$ to $$$m$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$. Initially, you are standing in the top left corner $$$(1, 1)$$$. Your goal is to reach the bottom right corner $$$(n, m)$$$.You can move in four directions from $$$(a, b)$$$: up to $$$(a-1, b)$$$, down to $$$(a+1, b)$$$, left to $$$(a, b-1)$$$ or right to $$$(a, b+1)$$$.You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach $$$(n, m)$$$?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of the test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the size of the grid.

For each test case, print a single integer: $$$-1$$$ if it is impossible to reach $$$(n, m)$$$ under the given conditions, otherwise the minimum number of moves.

NoteTest case $$$1$$$: $$$n=1$$$, $$$m=1$$$, and initially you are standing in $$$(1, 1)$$$ so $$$0$$$ move is required to reach $$$(n, m) = (1, 1)$$$.Test case $$$2$$$: you should go down to reach $$$(2, 1)$$$.Test case $$$3$$$: it is impossible to reach $$$(1, 3)$$$ without moving right two consecutive times, or without leaving the grid.Test case $$$4$$$: an optimal moving sequence could be: $$$(1, 1) \to (1, 2) \to (2, 2) \to (2, 1) \to (3, 1) \to (3, 2) \to (4, 2)$$$. It can be proved that this is the optimal solution. So the answer is $$$6$$$.

package main

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

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

func (in *CF1668A) 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 *CF1668A) load() {
	if len(in.split) <= in.index {
		in.split = strings.Split(in.GetLine(), in.separator)
		in.index = 0
	}
}

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

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

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

/**
Run solve the problem CF1668A
Date: 6/07/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1668/A
Problem: CF1668A
**/
func (in *CF1668A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		x, y := in.NextInt(), in.NextInt()

		a := 0
		b := 0
		if x < y {
			a = x
			b = y
		} else {
			a = y
			b = x
		}

		if a == 1 && b >= 3 {
			fmt.Println(-1)
		} else {
			fmt.Println(2*b - 2 - (b+a)%2)
		}
	}
}

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

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

package main

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

//6
//1 1
//2 1
//1 3
//4 2
//4 6
//10 5

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

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

	var T, x, y int64
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &x, &y)

		if x < y {
			x, y = y, x
		}
		if y == 1 && x > 2 {
			Fprintln(out, -1)
		} else if x-y <= 1 {
			Fprintln(out, x+y-2)
		} else {
			a := 2*y - 1
			lt := x - y - 1
			if lt%2 == 0 {
				a += 4 * lt / 2
			} else {
				a += 4*(lt/2) + 3
			}

			Fprintln(out, a)
		}
	}
}

package main

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

const (
	INF = 3e5 + 10
	L0  = int64(0)
	L1  = int64(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, m int
		Fscan(in, &n, &m)
		if n < m {
			n, m = m, n
		}

		if n == 1 {
			Fprintln(out, 0)
		} else if m == 1 && n == 2 {
			Fprintln(out, 1)
		} else if m == 1 && n > 2 {
			Fprintln(out, -1)
		} else {
			ans := 0
			if m > 2 {
				ans += (m - 2) << 1
				n -= m - 2
				m = 2
			}
			if n&1 == 1 {
				ans += n*m - 3
			} else {
				ans += n*m - 2
			}
			Fprintln(out, ans)
		}

	}

}

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

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

package main

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

func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

	for ii := 0; ii < t; ii++ {
		var n, m int
		fmt.Fscan(in, &n, &m)
		if m > n {
			n, m = m, n
		}
		total := m + m - 2

		if m == n {
			fmt.Fprintln(out, total)
		} else {
			if m == 1 && n > 2 {
				fmt.Fprintln(out, -1)
			} else {
				if (n-m)&1 == 1 {
					fmt.Fprintln(out, total+(n-m)*2-1)
				} else {
					fmt.Fprintln(out, total+(n-m)*2)
				}

			}
		}
	}
}

//4444444444
//4444444444
//4444444444
//4444444444
//4444444444

package main

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

/*
1
4 6
---
10
*/

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

	if (n == 1 || m == 1) && n+m > 3 {
		fmt.Fprintln(writer, -1)
		return
	}

	ans := 2 * min(n-1, m-1)

	diff := max(n, m) - min(n, m)

	ans += 2 * diff

	if diff%2 != 0 {
		ans--
	}

	fmt.Fprintln(writer, ans)
}

//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 abs(num int) int {
	if num < 0 {
		return -num
	}
	return num
}

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

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

	for i := 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 GoUnhandledErrorResult
func factorize(num int) []int {
	factors := []int{1}

	sqrtA := int(math.Sqrt(float64(num)))

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

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

	return factors
}

package main

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

func abs(n int64) int64 {
	if n < 0 {
		return n * -1
	}
	return n
}

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)

		if (n == 1 && m > 2) || (m == 1 && n > 2) {
			fmt.Fprintln(out, -1)
		} else {
			d := abs(n - m)
			if n%2 != m%2 {
				d--
			}
			fmt.Fprintln(out, (n-1)+(m-1)+d)
		}
	}
}