Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed $$$n$$$ cans in a row on a table. Cans are numbered from left to right from $$$1$$$ to $$$n$$$. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.Vasya knows that the durability of the $$$i$$$-th can is $$$a_i$$$. It means that if Vasya has already knocked $$$x$$$ cans down and is now about to start shooting the $$$i$$$-th one, he will need $$$(a_i \cdot x + 1)$$$ shots to knock it down. You can assume that if Vasya starts shooting the $$$i$$$-th can, he will be shooting it until he knocks it down.Your task is to choose such an order of shooting so that the number of shots required to knock each of the $$$n$$$ given cans down exactly once is minimum possible.

The first line of the input contains one integer $$$n$$$ $$$(2 \le n \le 1\,000)$$$ — the number of cans. The second line of the input contains the sequence $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1\,000)$$$, where $$$a_i$$$ is the durability of the $$$i$$$-th can.

In the first line print the minimum number of shots required to knock each of the $$$n$$$ given cans down exactly once. In the second line print the sequence consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.

NoteIn the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots $$$20 \cdot 1 + 1 = 21$$$ times. After that only second can remains. To knock it down Vasya shoots $$$10 \cdot 2 + 1 = 21$$$ times. So the total number of shots is $$$1 + 21 + 21 = 43$$$.In the second example the order of shooting does not matter because all cans have the same durability.

package main

import (
    "fmt"
    "bufio"
    "os"
)
var input *bufio.Reader

func solve() {
    var (
        N int64
        i int64
        j int64
        res int64
    )
    fmt.Fscanf(input, "%d\n", &N)
    arr := make([]int64, N)
    idx := make([]int64, N)
    for i=0 ; i<N ; i++ {
        fmt.Fscanf(input, "%d ", &arr[i])
        idx[i] = i
    }
    fmt.Fscanf(input, "\n")
    // sort
    for i=0 ; i<N ; i++ {
        for j=0 ; j<N-1 ; j++ {
            if arr[j] < arr[j+1] {
                arr[j], arr[j+1] = arr[j+1], arr[j]
                idx[j], idx[j+1] = idx[j+1], idx[j]
            }
        }
    }
    for i=0 ; i<N ; i++ {
        res += i*arr[i] + 1
    }
    fmt.Println(res)
    for i=0 ; i<N ; i++ {
        fmt.Printf("%d ",idx[i]+1)
    }
}

func main () {
    input = bufio.NewReader(os.Stdin)
    solve()
}

package main

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

var scan *bufio.Scanner
var reader io.Reader
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	reader = os.Stdin
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func main() {
	solve()
}

// Can is ...
type Can struct {
	num  int
	cost int
}

// Cans is ...
type Cans []Can

func (a Cans) Len() int {
	return len(a)
}

func (a Cans) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a Cans) Less(i, j int) bool {
	return a[i].cost > a[j].cost
}

func solve() {
	var (
		n int
	)
	cin(&n)
	var a Cans
	//a := make([]Can, n)
	for i := 0; i < n; i++ {
		var cost int
		cin(&cost)
		a = append(a, Can{i + 1, cost})
	}

	c := 0
	num := make([]int, n)
	sort.Sort(a)

	//println(a)
	for i := 0; i < n; i++ {
		c += a[i].cost*i + 1
		num[i] = a[i].num
	}

	println(c)
	for i := 0; i < n-1; i++ {
		print(num[i], " ")
	}
	print(num[n-1])
}

func cin(a ...interface{}) {
	for i := 0; i < len(a); i++ {
		doScan(a[i])
	}
	return
}
func doScan(a interface{}) {
	switch a.(type) {
	case *[]int:
		s := *a.(*[]int)
		for i := 0; i < len(s); i++ {
			fmt.Fscan(reader, &s[i])
		}
	case *[]string:
		s := *a.(*[]string)
		for i := 0; i < len(s); i++ {
			fmt.Fscan(reader, &s[i])
		}
	default:
		fmt.Fscan(reader, a)
	}
	return
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func max(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Max(res, float64(z))
	}
	return int(res)
}

func min(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Min(res, float64(z))
	}
	return int(res)
}

func abs(x int) int {
	return int(math.Abs(float64(x)))
}

func sqrt(x int) int {
	return int(math.Sqrt(float64(x)))
}

func int2Int(x int) big.Int {
	var res big.Int
	res.SetInt64(int64(x))
	return res
}

package main

import "fmt"

const N int = 2000
var ai [N]int
var idx [N]int

func main() {
	var n int
	fmt.Scan(&n)
	for i:=0; i < n; i++ {
		fmt.Scan(&ai[i])
		idx[i] = i
	}

	for i:=0; i < n; i++ {
		for j:=i+1; j < n; j++ {
			if ai[ idx[i] ] < ai[ idx[j] ] {
				idx[i], idx[j] = idx[j], idx[i]
			}
		}
	}

	ans := 0
	for i:=0; i < n; i++ {
		//fmt.Printf("%d\n", idx[i])
		ans += ai[ idx[i] ] * i + 1
	}
	fmt.Printf("%d\n", ans)
	for i:= 0; i < n; i++ {
		fmt.Printf("%d ", idx[i] + 1)
	}
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++{
		fmt.Scan(&a[i])
	}
	res := make([]int, 0)
	var ans int
	for i := 0; i < n; i++{
		pos := -1
		for j := 0; j < n; j++ {
			if pos == -1 || a[j] > a[pos]{
				pos = j
			}
		}
		res = append(res, pos + 1)
		ans += i * a[pos] + 1
		a[pos] = 0
	}
	fmt.Println(ans)
	for i := 0; i < len(res); i++ {
		fmt.Print(res[i], " ")
	}
}

//HOWDY! IT'S ME! A HARD BLACKISH DICK MOVE!
package main

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

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

//str := PrintlnInts(X...)

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

type Can struct {
	val, idx int
}

func main() {
	n := ReadInt()
	a := ReadIntSlice(n)
	cans := make([]Can, n)
	for i, v := range a {
		cans[i].val = v
		cans[i].idx = i + 1
	}
	sort.Slice(cans, func(i, j int) bool {
		return cans[i].val > cans[j].val
	})
	ans := 0
	for i, can := range cans {
		ans += i*can.val + 1
	}
	fmt.Println(ans)
	for i := 0; i < n; i++ {
		fmt.Print(cans[i].idx, " ")
	}
	fmt.Println("")
}

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

func min(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	min := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] < min {
			min = args[i]
		}
	}
	return min
}

func max(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	max := args[0]
	for i := 1; i < len(args); i++ {
		if args[i] > max {
			max = args[i]
		}
	}
	return max
}

func _gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return _gcd(b, a%b)
}

func gcd(args ...int) int {
	if len(args) == 0 {
		panic("empty!")
	}
	gcd := args[0]
	for i := 1; i < len(args); i++ {
		gcd = _gcd(gcd, args[i])
	}
	return gcd
}

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9))
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

	return func() string {
		if !r.Scan() {
			panic("Scan failed")
		}
		return r.Text()
	}
}

// ReadInt returns an integer.
func ReadInt() int {
	return readInt()
}
func ReadInt2() (int, int) {
	return readInt(), readInt()
}
func ReadInt3() (int, int, int) {
	return readInt(), readInt(), readInt()
}
func ReadInt4() (int, int, int, int) {
	return readInt(), readInt(), readInt(), readInt()
}

func readInt64() int64 {
	return readIntNbits(64)
}

func readInt() int {
	return int(readIntNbits(32))
}

func readIntNbits(n int) int64 {
	i, err := strconv.ParseInt(ReadString(), 0, n)
	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
}

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

// PrintIntsLine returns integers string delimited by a space.
func PrintlnInts(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)
}

package main

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

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

var (
	// ReadString returns a WORD string.
	ReadString func() string
	stdout     *bufio.Writer
)

func init() {
	ReadString = newReadString(os.Stdin)
	stdout = bufio.NewWriter(os.Stdout)
}

func newReadString(ior io.Reader) func() string {
	r := bufio.NewScanner(ior)
	// r.Buffer(make([]byte, 1024), int(1e+11)) // for AtCoder
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	// Split sets the split function for the Scanner. The default split function is ScanLines.
	// Split panics if it is called after scanning has started.
	r.Split(bufio.ScanWords)

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

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
}

// ReadFloat64 returns an float64.
func ReadFloat64() float64 {
	return float64(readFloat64())
}

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

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

// ReadRuneSlice returns a rune slice.
func ReadRuneSlice() []rune {
	return []rune(ReadString())
}

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

// ZeroPaddingRuneSlice returns binary expressions of integer n with zero padding.
// For debugging use.
func ZeroPaddingRuneSlice(n, digitsNum int) []rune {
	sn := fmt.Sprintf("%b", n)

	residualLength := digitsNum - len(sn)
	if residualLength <= 0 {
		return []rune(sn)
	}

	zeros := make([]rune, residualLength)
	for i := 0; i < len(zeros); i++ {
		zeros[i] = '0'
	}

	res := []rune{}
	res = append(res, zeros...)
	res = append(res, []rune(sn)...)

	return res
}

/*********** DP sub-functions ***********/

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

// NthBit returns nth bit value of an argument.
// n starts from 0.
func NthBit(num, nth int) int {
	return num >> uint(nth) & 1
}

// OnBit returns the integer that has nth ON bit.
// If an argument has nth ON bit, OnBit returns the argument.
func OnBit(num, nth int) int {
	return num | (1 << uint(nth))
}

// OffBit returns the integer that has nth OFF bit.
// If an argument has nth OFF bit, OffBit returns the argument.
func OffBit(num, nth int) int {
	return num & ^(1 << uint(nth))
}

// PopCount returns the number of ON bit of an argument.
func PopCount(num int) int {
	res := 0

	for i := 0; i < 70; i++ {
		if ((num >> uint(i)) & 1) == 1 {
			res++
		}
	}

	return res
}

/*********** Arithmetic ***********/

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

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

// DigitSum returns digit sum of a decimal number.
// DigitSum only accept a positive integer.
func DigitSum(n int) int {
	if n < 0 {
		return -1
	}

	res := 0

	for n > 0 {
		res += n % 10
		n /= 10
	}

	return res
}

// DigitNumOfDecimal returns digits number of n.
// n is non negative number.
func DigitNumOfDecimal(n int) int {
	res := 0

	for n > 0 {
		n /= 10
		res++
	}

	return res
}

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

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

	return s
}

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

// PowInt is integer version of math.Pow
// PowInt calculate a power by Binary Power (二分累乗法(O(log e))).
func PowInt(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 := PowInt(a, halfE)
		return half * half
	}

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

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

// Gcd returns the Greatest Common Divisor of two natural numbers.
// Gcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Gcd uses the Euclidean Algorithm.
func Gcd(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}
	if a < b {
		a, b = b, a
	}

	// Euclidean Algorithm
	for b > 0 {
		div := a % b
		a, b = b, div
	}

	return a
}

// Lcm returns the Least Common Multiple of two natural numbers.
// Lcd only accepts two natural numbers (a, b >= 1).
// 0 or negative number causes panic.
// Lcd uses the Euclidean Algorithm indirectly.
func Lcm(a, b int) int {
	if a <= 0 || b <= 0 {
		panic(errors.New("[argument error]: Gcd only accepts two NATURAL numbers"))
	}

	// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2
	// a' and b' are relatively prime numbers
	// gcd consists of prime numbers, that are included in a and b
	gcd := Gcd(a, b)

	// not (a * b / gcd), because of reducing a probability of overflow
	return (a / gcd) * b
}

// Strtoi is a wrapper of `strconv.Atoi()`.
// If `strconv.Atoi()` returns an error, Strtoi calls panic.
func Strtoi(s string) int {
	if i, err := strconv.Atoi(s); err != nil {
		panic(errors.New("[argument error]: Strtoi only accepts integer string"))
	} else {
		return i
	}
}

// PrintIntsLine returns integers string delimited by a space.
func PrintIntsLine(A ...int) string {
	res := []rune{}

	for i := 0; i < len(A); i++ {
		str := strconv.Itoa(A[i])
		res = append(res, []rune(str)...)

		if i != len(A)-1 {
			res = append(res, ' ')
		}
	}

	return string(res)
}

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

//str := ReadString()
//i := ReadInt()
//X := ReadIntSlice(n)
//S := ReadRuneSlice()
//a := ReadFloat64()
//A := ReadFloat64Slice(n)

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

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

const MOD = 1000000000 + 7
const ALPHABET_NUM = 26
const INF_INT64 = math.MaxInt64
const INF_BIT60 = 1 << 60

var n int
var A []int

type Item struct {
	key int
	idx int
}
type ItemList []*Item
type byKey struct {
	ItemList
}

func (l ItemList) Len() int {
	return len(l)
}
func (l ItemList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l byKey) Less(i, j int) bool {
	return l.ItemList[i].key < l.ItemList[j].key
}

// how to use
// L := make(ItemList, 0, 200000+5)
// L = append(L, &Item{key: intValue})
// sort.Stable(byKey{ L })                // Stable ASC
// sort.Stable(sort.Reverse(byKey{ L }))  // Stable DESC

func main() {
	n = ReadInt()
	A = ReadIntSlice(n)

	L := make(ItemList, 0, 200000)
	for i := 0; i < n; i++ {
		L = append(L, &Item{key: A[i], idx: i})
	}
	sort.Stable(sort.Reverse(byKey{L}))

	ans := 0
	for i := 0; i < n; i++ {
		ans += i*L[i].key + 1
	}

	row := []int{}
	for i := 0; i < n; i++ {
		row = append(row, L[i].idx+1)
	}

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

// MODはとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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

package main

import (
	"fmt"
	"sort"
)

type S struct {
	order int
	cost int
}

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

	sSli := make([]S, n)
	for i := 0;i < n; i++ {
		fmt.Scan(&sSli[i].cost)
		sSli[i].order = i+1
	}

	sort.Slice(sSli, func(i, j int) bool {
		return sSli[i].cost > sSli[j].cost
	})

	var result, cnt int
	for _, s := range sSli {
		result += cnt*s.cost
		cnt++
	}
	fmt.Println(result+n)
	for _, s := range sSli {
		fmt.Printf("%d ", s.order)
	}
}

package main

import (
	"fmt"
	"math/big"
)

func main() {
	var n int

	fmt.Scanf("%d\n", &n)

	power := make([]int64, n)
	indexes := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &power[i])
		indexes[i] = i
	}
	/*
	sort.Slice(power, func(i, j int) bool {
		return power[i] > power[j]
	})
	*/
	for i := 0; i < n; i++ {
		for j := 0; j < n - 1; j++ {
			if power[j] <= power[j+1] {
				power[j], power[j+1] = power[j+1], power[j]
				indexes[j], indexes[j+1] = indexes[j+1], indexes[j]
			}
		}
	}

	x := 0
	shots := big.NewInt(0)
	for x < n {
		tmp := big.NewInt(int64(0))
		tmp.Mul(big.NewInt(power[x]), big.NewInt(int64(x)))
		tmp.Add(tmp, big.NewInt(int64(1)))
		shots.Add(shots, tmp)
		x += 1
	}

	fmt.Println(shots)
	for i := 0; i < n; i++ {
		fmt.Print(indexes[i] + 1)
		if i + 1 == n {
			fmt.Println()
		} else {
			fmt.Print(" ")
		}
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	var n, tmp int
	durability := make([]int, 0)

	fmt.Fscanf(in, "%d\n", &n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(in, "%d", &tmp)
		durability = append(durability, tmp)
	}

	sum, ret := solution(n, durability)
	fmt.Println(sum)
	for i := 0; i < len(ret); i++ {
		fmt.Printf("%d ", ret[i])
	}
	fmt.Println()
}

func solution(n int, durability []int) (int, []int) {
	var sum int
	ret := make([]int, 0)

	durabilityIndexMapping := make(map[int][]int)
	for i, dur := range durability {
		durabilityIndexMapping[dur] = append(durabilityIndexMapping[dur], i+1)
	}

	durability = unique(durability)
	sort.Slice(durability, func(i, j int) bool {
		return durability[i] > durability[j]
	})

	count := 0
	for _, val := range durability {
		for _, indices := range durabilityIndexMapping[val] {
			ret = append(ret, indices)
			sum += count*val + 1
			count++
		}
	}

	return sum, ret
}

func unique(intSlice []int) []int {
	keys := make(map[int]bool)
	list := []int{}
	for _, entry := range intSlice {
		if _, value := keys[entry]; !value {
			keys[entry] = true
			list = append(list, entry)
		}
	}
	return list
}

package main

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

var scan *bufio.Scanner
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func nextWord() string {
	scan.Scan()
	str := scan.Text()
	return str
}

func nextInt() int {
	i, e := strconv.Atoi(nextWord())
	if e != nil {
		panic(e)
	}
	return i
}

type Cans struct {
	Id int
	Dura int
}

type CansSlice []Cans

func (c CansSlice) Len() int {
	return len(c)
}

func (c CansSlice) Swap(i, j int) {
	c[i], c[j] = c[j], c[i]
}

func (c CansSlice) Less(i, j int) bool {
	return c[i].Dura > c[j].Dura
}

func main() {
	n := nextInt()
	cansSlice := CansSlice{}
	for i := 1; i <= n; i++ {
		dura := nextInt()
		cansSlice = append(cansSlice, Cans{Id:i, Dura:dura})
	}
	sort.Stable(cansSlice)
	ret := 0
	for i, cans := range cansSlice {
		ret += cans.Dura * i + 1
	}
	fmt.Fprintln(writer, ret)
	for i, cans := range cansSlice {
		if i == 0 {
			fmt.Fprintf(writer, "%d", cans.Id)
		} else {
			fmt.Fprintf(writer, " %d", cans.Id)
		}
	}
	fmt.Fprintln(writer)
}

package main

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

type canDetails struct {
	Pos int64
	Dur int64
}

type ByDur []canDetails

func (a ByDur) Len() int {
	return len(a)
}

func (a ByDur) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a ByDur) Less(i, j int) bool {
	return a[i].Dur < a[j].Dur
}

func calcMinShotsAndSeq(cansDura []int64) (minShots int64, seq []int64) {
	var allCansDetails []canDetails

	for i, dura := range cansDura {
		allCansDetails = append(allCansDetails, canDetails{int64(i + 1), dura})
	}

	sort.Sort(sort.Reverse(ByDur(allCansDetails)))

	for x, oneCanDetails := range allCansDetails {
		minShots += (oneCanDetails.Dur * int64(x)) + 1
		seq = append(seq, oneCanDetails.Pos)
	}

	// fmt.Println(minShots)
	// fmt.Println(seq)

	return
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	var rawTotalCans string
	var totalCans int64

	for scanner.Scan() {
		if len(rawTotalCans) == 0 {
			rawTotalCans = scanner.Text()
			totalCans, _ = strconv.ParseInt(rawTotalCans, 10, 64)
			continue
		}

		allInput := scanner.Text()
		rawCanDura := strings.Split(allInput, " ")
		if totalCans != int64(len(rawCanDura)) {
			break
		}

		var cansDura []int64
		for _, d := range rawCanDura {
			n, _ := strconv.ParseInt(d, 10, 64)
			cansDura = append(cansDura, n)
		}

		minShots, seq := calcMinShotsAndSeq(cansDura)
		fmt.Println(minShots)
		for i, n := range seq {
			fmt.Print(n)
			if i < len(seq)-1 {
				fmt.Print(" ")
			}
		}
		fmt.Println()

		break
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
)

const INF  = 1000000001

type Pair struct {
	first, second int
}

func sort(arr []Pair) []Pair {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i].first > arr[right].first {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort(arr[:left])
	sort(arr[left+1:])
	return arr
}

func sort2(arr []int) []int {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i] < arr[right] {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort2(arr[:left])
	sort2(arr[left+1:])
	return arr
}

func solution(reader io.Reader, writer io.Writer) {
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]Pair, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i].first)
		a[i].second = i
	}
	a = sort(a)
	var r int
	for i := 0; i < n; i++ {
		r += a[i].first * i + 1
		a[i].first = i
		a[i].first, a[i].second = a[i].second, a[i].first
	}
	fmt.Println(r)
	for i := 0; i < n; i++ {
		fmt.Fprintf(writer, "%d ", a[i].first + 1)
	}
}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("file.out")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)
	defer writer.Flush()

	solution(reader, writer)
}

package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int

	fmt.Scan(&n)
	a := make([]struct {
		value int
		index int
	}, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i].value)
		a[i].index = i
	}
	sort.Slice(a, func(i, j int) bool {
		return a[i].value < a[j].value
	})
	res := 0

	for i := n - 1; i >= 0; i-- {
		res += (n-i-1)*a[i].value + 1
	}
	fmt.Println(res)
	for i := n - 1; i >= 0; i-- {
		fmt.Printf("%d ", a[i].index + 1)
	}
}

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

package main

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

type Solution struct {
	Shots int
	S     []int
}

type Can struct {
	Durability int
	Index      int
}

func Solve(n int, a []int) Solution {
	cans := make([]Can, n)
	for i, elem := range a {
		cans[i] = Can{Durability: elem, Index: i}
	}
	sort.Slice(cans, func(i, j int) bool { return cans[i].Durability > cans[j].Durability })
	s := make([]int, n)
	shots := 0
	for i := 0; i < n; i++ {
		s[i] = cans[i].Index + 1
		shots += cans[i].Durability*i + 1
	}
	return Solution{Shots: shots, S: s}
}

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

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

	solution := Solve(n, a)
	fmt.Fprintf(writer, "%d\n", solution.Shots)
	for i := 0; i < n; i++ {
		fmt.Fprintf(writer, "%d ", solution.S[i])
	}
	fmt.Fprintf(writer, "\n")
}

package main

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

var scan *bufio.Scanner
var reader io.Reader
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	reader = os.Stdin
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func main() {
	solve()
}

// Can is ...
type Can struct {
	num  int
	cost int
}

// Cans is ...
type Cans []Can

func (a Cans) Len() int {
	return len(a)
}

func (a Cans) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a Cans) Less(i, j int) bool {
	return a[i].cost > a[j].cost
}

func solve() {
	var (
		n int
	)
	cin(&n)
	var a Cans
	//a := make([]Can, n)
	for i := 0; i < n; i++ {
		var cost int
		cin(&cost)
		a = append(a, Can{i + 1, cost})
	}

	c := 0
	num := make([]int, n)
	sort.Sort(a)

	println(a)
	for i := 0; i < n; i++ {
		c += a[i].cost*i + 1
		num[i] = a[i].num
	}

	println(c)
	for i := 0; i < n; i++ {
		print(num[i], " ")
	}
}

func cin(a ...interface{}) {
	for i := 0; i < len(a); i++ {
		doScan(a[i])
	}
	return
}
func doScan(a interface{}) {
	switch a.(type) {
	case *[]int:
		s := *a.(*[]int)
		for i := 0; i < len(s); i++ {
			fmt.Fscan(reader, &s[i])
		}
	case *[]string:
		s := *a.(*[]string)
		for i := 0; i < len(s); i++ {
			fmt.Fscan(reader, &s[i])
		}
	default:
		fmt.Fscan(reader, a)
	}
	return
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func max(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Max(res, float64(z))
	}
	return int(res)
}

func min(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Min(res, float64(z))
	}
	return int(res)
}

func abs(x int) int {
	return int(math.Abs(float64(x)))
}

func sqrt(x int) int {
	return int(math.Sqrt(float64(x)))
}

func int2Int(x int) big.Int {
	var res big.Int
	res.SetInt64(int64(x))
	return res
}

package main

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

var scan *bufio.Scanner
var reader io.Reader
var writer io.Writer

func init() {
	scan = bufio.NewScanner(os.Stdin)
	reader = os.Stdin
	writer = os.Stdout
	scan.Split(bufio.ScanWords)
}

func main() {
	solve()
}

// Can is ...
type Can struct {
	num  int
	cost int
}

// Cans is ...
type Cans []Can

func (a Cans) Len() int {
	return len(a)
}

func (a Cans) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a Cans) Less(i, j int) bool {
	return a[i].cost > a[j].cost
}

func solve() {
	var (
		n int
	)
	cin(&n)
	var a Cans
	//a := make([]Can, n)
	for i := 0; i < n; i++ {
		var cost int
		cin(&cost)
		a = append(a, Can{i + 1, cost})
	}

	c := 0
	num := make([]int, n)
	sort.Sort(a)

	println(a)
	for i := 0; i < n; i++ {
		c += a[i].cost*i + 1
		num[i] = a[i].num
	}

	println(c)
	for i := 0; i < n-1; i++ {
		print(num[i], " ")
	}
	print(num[n-1])
}

func cin(a ...interface{}) {
	for i := 0; i < len(a); i++ {
		doScan(a[i])
	}
	return
}
func doScan(a interface{}) {
	switch a.(type) {
	case *[]int:
		s := *a.(*[]int)
		for i := 0; i < len(s); i++ {
			fmt.Fscan(reader, &s[i])
		}
	case *[]string:
		s := *a.(*[]string)
		for i := 0; i < len(s); i++ {
			fmt.Fscan(reader, &s[i])
		}
	default:
		fmt.Fscan(reader, a)
	}
	return
}

func print(a ...interface{}) {
	fmt.Fprint(writer, a...)
}

func println(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func max(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Max(res, float64(z))
	}
	return int(res)
}

func min(x int, y ...int) int {
	res := float64(x)
	for _, z := range y {
		res = math.Min(res, float64(z))
	}
	return int(res)
}

func abs(x int) int {
	return int(math.Abs(float64(x)))
}

func sqrt(x int) int {
	return int(math.Sqrt(float64(x)))
}

func int2Int(x int) big.Int {
	var res big.Int
	res.SetInt64(int64(x))
	return res
}

package main

import "fmt"

const N int = 2000
var ai [N]int
var idx [N]int

func main() {
	var n int
	fmt.Scanf("%d", &n)
	for i:=0; i < n; i++ {
		fmt.Scanf("%d", &ai[i])
		idx[i] = i
	}

	for i:=0; i < n; i++ {
		for j:=i+1; j < n; j++ {
			if ai[ idx[i] ] < ai[ idx[j] ] {
				idx[i], idx[j] = idx[j], idx[i]
			}
		}
	}

	ans := 0
	for i:=0; i < n; i++ {
		//fmt.Printf("%d\n", idx[i])
		ans += ai[ idx[i] ] * i + 1
	}
	fmt.Printf("%d\n", ans)
	for i:= 0; i < n; i++ {
		fmt.Printf("%d ", idx[i] + 1)
	}
}

package main

import "fmt"

const N int = 2000
var ai [N]int
var idx [N]int

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

	for i:=0; i < n; i++ {
		for j:=i+1; j < n; j++ {
			if ai[ idx[i] ] < ai[ idx[j] ] {
				idx[i], idx[j] = idx[j], idx[i]
			}
		}
	}

	ans := 0
	for i:=0; i < n; i++ {
		//fmt.Printf("%d\n", idx[i])
		ans += ai[ idx[i] ] * i + 1
	}
	fmt.Printf("%d\n", ans)
	for i:= 0; i < n; i++ {
		fmt.Printf("%d ", idx[i] + 1)
	}
}

package main

import "fmt"

const N int = 2000
var ai [N]int
var idx [N]int

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

	for i:=0; i < n; i++ {
		for j:=i+1; j < n; j++ {
			if ai[ idx[i] ] < ai[ idx[j] ] {
				idx[i], idx[j] = idx[j], idx[i]
			}
		}
	}

	ans := 0
	for i:=0; i < n; i++ {
		//fmt.Printf("%d\n", idx[i])
		ans += ai[ idx[i] ] * i + 1
	}
	fmt.Printf("%d\n", ans)
	for i:= 0; i < n; i++ {
		fmt.Printf("%d ", idx[i] + 1)
	}
}

package main

import "fmt"

const N int = 2000
var ai [N]int
var idx [N]int

func main() {
	var n int
	fmt.Scan(&n)
	for i:=0; i < n; i++ {
		fmt.Scan(&ai[i])
		fmt.Printf("%d\n", ai[i])
		idx[i] = i
	}
	fmt.Printf("%d\n", n)

	for i:=0; i < n; i++ {
		for j:=i+1; j < n; j++ {
			if ai[ idx[i] ] < ai[ idx[j] ] {
				idx[i], idx[j] = idx[j], idx[i]
			}
		}
	}

	ans := 0
	for i:=0; i < n; i++ {
		//fmt.Printf("%d\n", idx[i])
		ans += ai[ idx[i] ] * i + 1
	}
	fmt.Printf("%d\n", ans)
	for i:= 0; i < n; i++ {
		fmt.Printf("%d ", idx[i] + 1)
	}
}

package main

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

type canDetails struct {
	Pos int64
	Dur int64
}

type ByDur []canDetails

func (a ByDur) Len() int {
	return len(a)
}

func (a ByDur) Swap(i, j int) {
	a[i], a[j] = a[j], a[i]
}

func (a ByDur) Less(i, j int) bool {
	return a[i].Dur < a[j].Dur
}

func calcMinShotsAndSeq(cansDura []int64) (minShots int64, seq []int64) {
	var allCansDetails []canDetails

	for i, dura := range cansDura {
		allCansDetails = append(allCansDetails, canDetails{int64(i + 1), dura})
	}

	sort.Sort(sort.Reverse(ByDur(allCansDetails)))

	for x, oneCanDetails := range allCansDetails {
		minShots += (oneCanDetails.Dur * int64(x)) + 1
		seq = append(seq, oneCanDetails.Pos)
	}

	// fmt.Println(minShots)
	// fmt.Println(seq)

	return
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	var rawTotalCans string
	var totalCans int64

	for scanner.Scan() {
		if len(rawTotalCans) == 0 {
			rawTotalCans = scanner.Text()
			totalCans, _ = strconv.ParseInt(rawTotalCans, 10, 64)
			continue
		}

		allInput := scanner.Text()
		rawCanDura := strings.Split(allInput, " ")
		if totalCans != int64(len(rawCanDura)) {
			break
		}

		var cansDura []int64
		for _, d := range rawCanDura {
			n, _ := strconv.ParseInt(d, 10, 64)
			cansDura = append(cansDura, n)
		}

		minShots, seq := calcMinShotsAndSeq(cansDura)
		fmt.Println(minShots)
		fmt.Println(seq)
		break
	}
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
)

const INF  = 1000000001

type Pair struct {
	first, second int
}

func sort(arr []Pair) []Pair {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i].first > arr[right].first {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort(arr[:left])
	sort(arr[left+1:])
	return arr
}

func sort2(arr []int) []int {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i] < arr[right] {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort2(arr[:left])
	sort2(arr[left+1:])
	return arr
}

func solution(reader io.Reader, writer io.Writer) {
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]Pair, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i].first)
		a[i].second = i
	}
	a = sort(a)
	var r int
	for i := 0; i < n; i++ {
		r += a[i].first * i + 1
		a[i].first = i
		a[i].first, a[i].second = a[i].second, a[i].first
	}
	a = sort(a)
	fmt.Println(r)
	for i := n - 1; i >= 0; i-- {
		fmt.Fprintf(writer, "%d ", a[i].second + 1)
	}
}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	//stdout, err := os.Create("file.out")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdout.Close()
	stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)
	defer writer.Flush()

	solution(reader, writer)
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"os"
)

const INF  = 1000000001

type Pair struct {
	first, second int
}

func sort(arr []Pair) []Pair {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i].first > arr[right].first {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort(arr[:left])
	sort(arr[left+1:])
	return arr
}

func sort2(arr []int) []int {
	if len(arr) < 2 {
		return arr
	}
	left := 0
	right := len(arr) - 1
	pivot := rand.Int() % len(arr)

	arr[pivot], arr[right] = arr[right], arr[pivot]

	for i := 0; i < len(arr); i++ {
		if arr[i] < arr[right] {
			arr[i], arr[left] = arr[left], arr[i]
			left++
		}
	}

	arr[left], arr[right] = arr[right], arr[left]

	sort2(arr[:left])
	sort2(arr[left+1:])
	return arr
}

func solution(reader io.Reader, writer io.Writer) {
	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]Pair, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i].first)
		a[i].second = i
	}
	a = sort(a)
	var r int
	for i := 0; i < n; i++ {
		r += a[i].first * i + 1
		a[i].first = i
		a[i].first, a[i].second = a[i].second, a[i].first
	}
	a = sort(a)
	fmt.Println(r)
	for i := n - 1; i >= 0; i-- {
		fmt.Fprintf(writer, "%d ", a[i].second + 1)
	}
}

func main() {

	//stdin, err := os.Open("file.in")
	//if err != nil {
	//	panic(err)
	//}
	//defer stdin.Close()
	stdin := os.Stdin
	reader := bufio.NewReaderSize(stdin, 1024*1024)

	stdout, err := os.Create("file.out")
	if err != nil {
		panic(err)
	}
	defer stdout.Close()
	//stdout := os.Stdout
	writer := bufio.NewWriterSize(stdout, 1024*1024)
	defer writer.Flush()

	solution(reader, writer)
}


Little pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of $$$n$$$ rows and $$$m$$$ columns, whose cells contain each number from $$$1$$$ to $$$n \cdot m$$$ exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number $$$i$$$, denote the position of the first occurrence of this cell in the sequence as $$$t_i$$$. The sequence solves the puzzle, if $$$t_1 < t_2 < \dots < t_{nm}$$$. In other words, the cell with number $$$x$$$ should be first visited before the cell with number $$$x + 1$$$ for each $$$x$$$.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is $$$0$$$, $$$1$$$, or at least $$$2$$$. In the case, where $$$1$$$ move is required, please also find the number of suitable cell pairs to swap.

In the first line there are two whole positive numbers $$$n, m$$$ ($$$1 \leq n\cdot m \leq 400\,000$$$) — table dimensions. In the next $$$n$$$ lines there are $$$m$$$ integer numbers $$$a_{i1}, a_{i2}, \dots, a_{im}$$$ ($$$1 \le a_{ij} \le nm$$$).  It is guaranteed that every number from $$$1$$$ to $$$nm$$$ occurs exactly once in the table.

Let $$$a$$$ be the minimum number of moves to make the puzzle solvable. If $$$a = 0$$$, print $$$0$$$. If $$$a = 1$$$, print $$$1$$$ and the number of valid swaps. If $$$a \ge 2$$$, print $$$2$$$.

NoteIn the first example the sequence $$$(1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3)$$$, $$$(2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1)$$$ solves the puzzle, so the answer is $$$0$$$.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values $$$(1, 5), (1, 6), (2, 6)$$$. The puzzle from the third example requires at least two swaps, so the answer is $$$2$$$.

package main

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

type Pos struct { x, y int }

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

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

	dx := [4]int{1, 0, -1, 0}
	dy := [4]int{0, -1, 0, 1}

	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscan(in, &a[i][j])
			a[i][j]--
		}
	}

	cl := func(x int, y int) int {
		for l := 0; l < 4; l++ {
			xn := x + dx[l]
			yn := y + dy[l]
			if xn < 0 || xn >= n || yn < 0 || yn >= m {
				continue
			}
			if a[xn][yn] < a[x][y] {
				return 1
			}
		}
		return 0
	}

	mi := n * m
	xx := 0
	yy := 0
	res := 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			cur := cl(i, j)
			if cur == 0 && a[i][j] > 0 && a[i][j] < mi {
				mi = a[i][j]
				xx = i
				yy = j
			}
			res += cur
		}
	}

	if (res == n * m - 1) {
		fmt.Fprintln(out, "0")
	} else {
		cnt := 0

		u := make([][]bool, n)
		for i := 0; i < n; i++ {
			u[i] = make([]bool, m)
		}

		g := func(ps [10]Pos, k int) int {
			res := 0

			for i := 0; i < k; i++ {
				x := ps[i].x
				y := ps[i].y
				if cl(x, y) > 0 {
					res++
				}
			}

			return res
		}

		f := func(ps [2]Pos) int {
			var pu [10]Pos
			k := 0

			for i := 0; i < 2; i++ {
				x := ps[i].x
				y := ps[i].y

				if !u[x][y] {
					u[x][y] = true
					pu[k] = Pos{x, y}
					k++
				}

				for l := 0; l < 4; l++ {
					xn := x + dx[l]
					yn := y + dy[l]
					if xn < 0 || xn >= n || yn < 0 || yn >= m {
						continue
					}

					if !u[xn][yn] {
						u[xn][yn] = true
						pu[k] = Pos{xn, yn}
						k++
					}
				}
			}

			for i := 0; i < k; i++ {
				u[pu[i].x][pu[i].y] = false
			}

			return g(pu, k)
		}

		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if a[i][j] == a[xx][yy] {
					continue
				}
				if a[i][j] > a[xx][yy] {
					ps := [2]Pos{Pos{xx, yy}, Pos{i, j}}
					cur := res - f(ps)

					a[i][j], a[xx][yy] = a[xx][yy], a[i][j]
					cur += f(ps)

					if cur == n * m - 1 {
						cnt++
					}

					a[i][j], a[xx][yy] = a[xx][yy], a[i][j]
				} else {
					for l := 0; l < 4; l++ {
						xn := xx + dx[l]
						yn := yy + dy[l]
						if xn < 0 || xn >= n || yn < 0 || yn >= m {
							continue
						}

						ps := [2]Pos{Pos{xn, yn}, Pos{i, j}}
						cur := res - f(ps)

						a[i][j], a[xn][yn] = a[xn][yn], a[i][j]
						cur += f(ps)

						if cur == n * m - 1 {
							cnt++
						}

						a[i][j], a[xn][yn] = a[xn][yn], a[i][j]
					}
				}
			}
		}

		if cnt > 0 {
			fmt.Fprintf(out, "1 %d\n", cnt)
		} else {
			fmt.Fprintln(out, "2")
		}
	}
}

package main

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

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

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

	check := func(v int) bool {
		if v == 1 { return true }
		ii,jj := ll[v].i,ll[v].j
		if (ii > 0 && bd[ii-1][jj] < v) || (ii+1 < N && bd[ii+1][jj] < v) { return true }
		if (jj > 0 && bd[ii][jj-1] < v) || (jj+1 < M && bd[ii][jj+1] < v) { return true }
		return false
	}

	badarr := make([]int,0)
	for i:=1;i<=N*M;i++ { if !check(i) { badarr = append(badarr,i) } }
	if len(badarr) == 0 { fmt.Println(0); return }

	swaps := 0
	adjbad := []int{badarr[0]}
	ii,jj := ll[badarr[0]].i, ll[badarr[0]].j;
	if ii > 0 { adjbad = append(adjbad,bd[ii-1][jj]) }
	if jj > 0 { adjbad = append(adjbad,bd[ii][jj-1]) }
	if ii+1 < N { adjbad = append(adjbad,bd[ii+1][jj]) }
	if jj+1 < M { adjbad = append(adjbad,bd[ii][jj+1]) }

	visited := make(map[pair]bool)
	for _,v1 := range adjbad {
		for v2:=1;v2<=N*M;v2++ {
			t1,t2 := min(v1,v2),max(v1,v2); if visited[pair{t1,t2}] { continue }; visited[pair{t1,t2}] = true
			// check that all of the bad numbers are within a manhattan distance of 1 of at least one of the swaps
			ii1,jj1,ii2,jj2 := ll[v1].i,ll[v1].j,ll[v2].i,ll[v2].j
			good := true
			for _,v := range badarr {
				ii3,jj3 := ll[v].i,ll[v].j
				if abs(ii3-ii1)+abs(jj3-jj1) > 1 && abs(ii3-ii2)+abs(jj3-jj2) > 1 { good = false; break }
			}
			if !good { continue }
			// Do the swap
			bd[ii1][jj1],bd[ii2][jj2] = bd[ii2][jj2],bd[ii1][jj1]; ll[v1],ll[v2] = ll[v2],ll[v1]
			//Inventory the 10 points we need to check
			if !check(v1) || !check(v2) { good = false }
			if ii1 > 0   && !check(bd[ii1-1][jj1]) { good = false }
			if ii2 > 0   && !check(bd[ii2-1][jj2]) { good = false }
			if ii1+1 < N && !check(bd[ii1+1][jj1]) { good = false }
			if ii2+1 < N && !check(bd[ii2+1][jj2]) { good = false }
			if jj1 > 0   && !check(bd[ii1][jj1-1]) { good = false }
			if jj2 > 0   && !check(bd[ii2][jj2-1]) { good = false }
			if jj1+1 < M && !check(bd[ii1][jj1+1]) { good = false }
			if jj2+1 < M && !check(bd[ii2][jj2+1]) { good = false }
			bd[ii1][jj1],bd[ii2][jj2] = bd[ii2][jj2],bd[ii1][jj1]; ll[v1],ll[v2] = ll[v2],ll[v1]
			if good { swaps++ }
		}
	}

	if swaps == 0 { fmt.Fprintln(wrtr,2) } else { fmt.Fprintf(wrtr,"%v %v\n",1,swaps) }
}

package main

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

type Pos struct { x, y int }

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

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

	dx := [4]int{1, 0, -1, 0}
	dy := [4]int{0, -1, 0, 1}

	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, m)
		for j := 0; j < m; j++ {
			fmt.Fscan(in, &a[i][j])
			a[i][j]--
		}
	}

	cl := func(x int, y int) int {
		for l := 0; l < 4; l++ {
			xn := x + dx[l]
			yn := y + dy[l]
			if xn < 0 || xn >= n || yn < 0 || yn >= m {
				continue
			}
			if a[xn][yn] < a[x][y] {
				return 1
			}
		}
		return 0
	}

	mi := n * m
	xx := 0
	yy := 0
	res := 0
	for i := 0; i < n; i++ {
		for j := 0; j < m; j++ {
			cur := cl(i, j)
			if cur == 0 && a[i][j] > 0 && a[i][j] < mi {
				mi = a[i][j]
				xx = i
				yy = j
			}
			res += cur
		}
	}

	if (res == n * m - 1) {
		fmt.Fprintln(out, "0")
	} else {
		cnt := 0

		f := func(ps [2]Pos) int {
			res := 0

			for i := 0; i < 2; i++ {
				x := ps[i].x
				y := ps[i].y

				if cl(x, y) > 0 {
					res++
				}

				for l := 0; l < 4; l++ {
					xn := x + dx[l]
					yn := y + dy[l]
					if xn < 0 || xn >= n || yn < 0 || yn >= m {
						continue
					}

					if cl(xn, yn) > 0 {
						res++
					}
				}
			}

			return res
		}

		for i := 0; i < n; i++ {
			for j := 0; j < m; j++ {
				if a[i][j] == a[xx][yy] {
					continue
				}
				if a[i][j] > a[xx][yy] {
					ps := [2]Pos{Pos{xx, yy}, Pos{i, j}}
					cur := res - f(ps)

					a[i][j], a[xx][yy] = a[xx][yy], a[i][j]
					cur += f(ps)

					if cur == n * m - 1 {
						cnt++
					}

					a[i][j], a[xx][yy] = a[xx][yy], a[i][j]
				} else {
					for l := 0; l < 4; l++ {
						xn := xx + dx[l]
						yn := yy + dy[l]
						if xn < 0 || xn >= n || yn < 0 || yn >= m {
							continue
						}

						ps := [2]Pos{Pos{xn, yn}, Pos{i, j}}
						cur := res - f(ps)

						a[i][j], a[xn][yn] = a[xn][yn], a[i][j]
						cur += f(ps)

						if cur == n * m - 1 {
							cnt++
						}

						a[i][j], a[xn][yn] = a[xn][yn], a[i][j]
					}
				}
			}
		}

		if cnt > 0 {
			fmt.Fprintf(out, "1 %d\n", cnt)
		} else {
			fmt.Fprintln(out, "2")
		}
	}
}


We will consider the numbers $$$a$$$ and $$$b$$$ as adjacent if they differ by exactly one, that is, $$$|a-b|=1$$$.We will consider cells of a square matrix $$$n \times n$$$ as adjacent if they have a common side, that is, for cell $$$(r, c)$$$ cells $$$(r, c-1)$$$, $$$(r, c+1)$$$, $$$(r-1, c)$$$ and $$$(r+1, c)$$$ are adjacent to it.For a given number $$$n$$$, construct a square matrix $$$n \times n$$$ such that:   Each integer from $$$1$$$ to $$$n^2$$$ occurs in this matrix exactly once;  If $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are adjacent cells, then the numbers written in them must not be adjacent.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 100$$$).

For each test case, output:    -1, if the required matrix does not exist;  the required matrix, otherwise (any such matrix if many of them exist).  The matrix should be outputted as $$$n$$$ lines, where each line contains $$$n$$$ integers.

package main

import (
	"bufio"
	"fmt"
	"os"
	"math/rand"
	"time"
)

func main() {

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

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

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

		ans,res := solve(n)

		if !res {
			fmt.Println(-1)
		} else {

			for i := 0; i < len(ans); i++ {
				for j := 0; j < len(ans[0]); j++ {
					fmt.Fprint(w, ans[i][j])
					fmt.Fprint(w, " ")
				}
				fmt.Fprint(w, "\n")
			}
			fmt.Fprint(w, "\n")
			w.Flush()
		}
	}
}

func solve(n int) ([][]int, bool) {
	if n == 1 {
		return [][]int{{1}}, true
	}
	if n == 2 {
		return [][]int{}, false
	}

	mp := make([][]bool, n)

	for i := 0; i < n ; i++ {
		mp[i] = make([]bool, n)
	}

	ans := make([][]int, n)
	for j := 0; j < len(ans); j++ {
		ans[j] = make([]int, n)
	}

	rand.Seed(time.Now().Unix())

	dfs(&ans, &mp, n, 1, 0)

	return ans, true
}

func dfs(ans *[][]int, mp *[][]bool, n int, next int, total int) bool {

	for c := 0; c < 10000; c++ {

		if total >= n * n {
			return true
		}

		i := rand.Intn(n)
		j := rand.Intn(n)

		if (*mp)[i][j] {
			continue
		}

		if checkNeighbourgs(ans, i, j, next, n) {
			(*mp)[i][j] = true

			(*ans)[i][j] = next

			res := dfs(ans, mp, n, next + 1, total + 1)

			if res {
				return true
			}

			(*mp)[i][j] = false

			(*ans)[i][j] = 0

			continue

		} else {
			continue
		}
	}

	return false
}

func checkNeighbourgs(ans *[][]int, i, j int, next int, n int) bool {
	if (*ans)[i][j] != 0 {
		return false
	}

	v := getValue(i + 1, j, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	v = getValue(i - 1, j, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	v = getValue(i, j + 1, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	v = getValue(i, j - 1, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	return true
}

func getValue(i, j int, ans *[][]int, n int) int {
	if i < 0 || i >= n || j < 0 || j >= n {
		return 0
	}
	return (*ans)[i][j]
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func ri() int {
	var x int
	c, _ := reader.ReadByte()
	for c < '0' || c > '9' {
		c, _ = reader.ReadByte()
	}
	for '0' <= c && c <= '9' {
		x = (x << 3) + (x << 1) + int(c) - '0'
		c, _ = reader.ReadByte()
	}
	return x
}

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

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

const MAXN = 1e2 + 5

var mp [MAXN][MAXN]int

func Solve() {
	n := ri()
	if n == 2 {
		fmt.Println(-1)
		return
	}
	cnt := 1
	for j := 1; j <= n; j++ {
		for i := 0; i < n; i++ {
			mp[i+1][(i+j-1)%n+1] = cnt
			cnt++
		}
	}
	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			fmt.Printf("%d ", mp[i][j])
		}
		fmt.Printf("\n")
	}
}

func main() {
	var T = 0
	if T == 0 {
		fmt.Scan(&T)
	}
	for t := 1; t <= T; t++ {
		Solve()
	}
}

package main

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

func print(matrix [][]int) {
	var sb strings.Builder
	for _, line := range matrix {
		for i, v := range line {
			if i != 0 {
				sb.WriteRune(' ')
			}
			sb.WriteString(strconv.Itoa(v))
		}
		sb.WriteRune('\n')
	}
	fmt.Print(sb.String())
}

func makeMatrix(n int) [][]int {
	m := make([][]int, n)
	for i, _ := range m {
		m[i] = make([]int, n)
	}
	return m
}

func diff(a, b int) int {
	d := a - b
	if d < 0 {
		d = d * -1
	}
	return d
}

func isValid(i, j int, m [][]int) bool {
	val := m[i][j]
	if i == 0 && j == 0 {
		return true
	}
	if i > 0 && diff(m[i-1][j], val) < 2 {
		return false
	}
	if j > 0 && diff(m[i][j-1], val) < 2 {
		return false
	}
	if i < len(m)-1 && diff(m[i+1][j], val) < 2 {
		return false
	}
	if j < len(m)-1 && diff(m[i][j+1], val) < 2 {
		return false
	}
	return true
}

func fill(m [][]int) bool {
	if len(m) == 2 {
		return false
	}
	max := int(math.Pow(float64(len(m)), 2.0))
	currX, currY := 1, 0
	isXStart := false
	for i := 1; i <= max; {
		var x, y int
		if isXStart {
			x = currX
			y = 0
			currX++
		} else {
			x = 0
			y = currY
			currY++
		}
		for ; x < len(m) && y < len(m); x, y = x+1, y+1 {
			m[y][x] = i
			i++
		}
		isXStart = !isXStart
	}
	return true
}

func main() {
	var nTests int
	fmt.Scanf("%d\n", &nTests)
	for i := 0; i < nTests; i++ {
		var n int
		fmt.Scanf("%d\n", &n)
		m := makeMatrix(n)
		fill(m)

		if n != 2 {
			print(m)
		} else {
			fmt.Println("-1")
		}

	}
}

/*
func checkMatrix(m [][]int) (int, int) {
	for i := 0; i < len(m); i++ {
		for j := 0; j < len(m); j++ {
			if !isValid(i, j, m) {
				return j, i
			}
		}
	}
	return -1, -1
} */

/* func main() {
	for i := 3; i < 10; i++ {
		m := makeMatrix(i)
		fill(m)
		x, y := checkMatrix(m)
		if x != -1 {
			print(m)
			fmt.Printf("x: %d, y: %d\n", x, y)
		}
	}
} */

package main

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

// TEMPLATE
type BufferIO struct {
	reader *bufio.Reader
	writer *bufio.Writer
}
var bufferIO BufferIO = BufferIO{
	bufio.NewReader(os.Stdin),
	bufio.NewWriter(os.Stdout),
}
func scanf(format string, params ...interface{}) {
	fmt.Fscanf(bufferIO.reader, format, params...)
}
func printf(format string, params ...interface{}) {
	fmt.Fprintf(bufferIO.writer, format, params...)
}
func flush() {
	bufferIO.writer.Flush()
}
func main() {
	mainn()
	flush()
}
// END OF TEMPLATE

func main1() {
	var N int
	scanf("%d\n", &N)

	if N == 2 {
		printf("-1\n")
		return
	}

	evenCnt := 0
	oddCnt := (N * N + 1) / 2
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if (i + j) % 2 == 0 {
				evenCnt++
				printf("%d ", evenCnt)
			} else {
				oddCnt++
				printf("%d ", oddCnt)
			}
		}
		printf("\n")
	}
}

func mainn() {
	var T int

	scanf("%d\n", &T)

	for i := 0; i < T; i++ {
		main1()
	}
}

package main

import (
	"fmt"
)

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

	if N == 2 {
		fmt.Println(-1)
		return
	}

	evenCnt := 0
	oddCnt := (N * N + 1) / 2
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if (i + j) % 2 == 0 {
				evenCnt++
				fmt.Print(evenCnt, " ")
			} else {
				oddCnt++
				fmt.Print(oddCnt, " ")
			}
		}
		fmt.Println()
	}
}

func main() {
	var T int

	fmt.Scanf("%d\n", &T)

	for i := 0; i < T; i++ {
		main1()
	}
}

package main

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

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

func solve(n int) string {
	if n == 2 {
		return "-1"
	}
	m := make([][]string, n)
	for i := range m {
		m[i] = make([]string, n)
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			x := i*n + j + 1
			m[j][(i+j)%n] = fmt.Sprintf("%d", x)
		}
	}
	y := make([]string, n)
	for i := range m {
		y[i] = strings.Join(m[i], " ")
	}
	return strings.Join(y, "\n")
}

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

package main

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

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

	truth := make(map[bool]int)
	truth[false] = 0; truth[true] = 1
	var t int
	for Fscan(in, &t); t > 0; t-- {
		var n int
		Fscan(in, &n)
		matrix := make([][]int, n)

		for i, _ := range matrix {
			matrix[i] = make([]int, n)
			for j := 1; j <= n; j++ {
				matrix[i][j-1] = j + n * i
			}
		}

		if n == 2 {
			Fprintln(out, -1)
			continue
		}

		for j := 1; j <= n / 2; j++ {
			col := j * 2 - 1
			tmp := matrix[n-1][col]
			for i := n-1; i >= 1; i-- {
				matrix[i][col] = matrix[i-1][col]
			}
			matrix[0][col] = tmp
		}
		for _, row := range matrix {
			for _, val := range row {
				Fprint(out, val, " ")
			}
			Fprintln(out)
		}
	}
}

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

package main

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

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

	var t int
	for	Fscan(in, &t); t > 0; t-- {
		var n int
		Fscan(in, &n)

		if n == 1 {
			Fprintln(out, 1)

		} else if n == 2 {
			Fprintln(out, -1)

		} else {
			for i := 0; i < n; i++ {
				for j := 0; j < n; j++ {
					x := (j - i + n) % n
					Fprint(out, x * n + i + 1, " ")
				}
				Fprintln(out)
			}
		}

	}
}

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

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

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

package main

import "fmt"

func print_matrix(n int) {
    n_mod0 := (n + 1) / 2
    n_mod1 := n - n_mod0
    shift := n_mod0 * n
    for y := 0; y < n; y++ {
        for x := 0; x < n; x++ {
            var val int
            if x % 2 == 0 {
                true_x := x / 2
                val = 1 + true_x + y * n_mod0
            } else {
                true_x := (x - 1) / 2
                val = 1 + shift + true_x + y * n_mod1
            }
            fmt.Print(val, " ")
        }
        fmt.Println()
    }
}

func main() {
    var n_tasks int
    fmt.Scanf("%d\n", &n_tasks)
    for i := 0; i < n_tasks; i++ {
        var n int
        fmt.Scanln(&n)
        if n == 2 {
            fmt.Println(-1)
        } else if n == 3 {
            fmt.Println("2 9 7")
            fmt.Println("4 6 3")
            fmt.Println("1 8 5")
        } else {
            print_matrix(n)
        }
    }
}

package main

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

type matrix struct {
	n int
}

func (m *matrix) isOk() bool {
	return m.n != 2
}

func (m *matrix) String() {
	n := m.n
	data := make([][]int, n)
	for i := 0; i < n; i++ {
		data[i] = make([]int, n)
	}

	num := 1
	for i := 0; i < n; i++ {
		data[i][i] = num
		num++
	}

	for j := 1; j < n; j++ {
		for i := 0; i <= j && i < n; i++ {
			if data[i][j-i] > 0 {
				continue
			}

			data[i][j-i] = num
			num++
		}
	}

	for i := 1; i < n; i++ {
		for j := n - 1; i+(n-1-j) < n && j >= 0; j-- {
			if data[i+(n-1-j)][j] > 0 {
				continue
			}

			data[i+(n-1-j)][j] = num
			num++
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n-1; j++ {
			fmt.Printf("%d ", data[i][j])
		}

		fmt.Printf("%d\n", data[i][n-1])
	}
	os.Stdout.Sync()
}

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

	var t, n int

	fmt.Fscanf(reader, "%d\n", &t)
	for ; t > 0; t-- {
		fmt.Fscanf(reader, "%d\n", &n)
		m := matrix{n}

		if m.isOk() {
			m.String()
		} else {
			fmt.Println(-1)
		}
	}
}

package main

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

type matrix struct {
	n int
}

func (m *matrix) isOk() bool {
	return m.n != 2
}

func (m *matrix) String() {
	n := m.n
	data := make([][]int, n)
	for i := 0; i < n; i++ {
		data[i] = make([]int, n)
	}

	num := 1
	for i := 0; i < n; i++ {
		data[i][i] = num
		num++
	}

	for j := 1; j < n; j++ {
		for i := 0; i <= j && i < n; i++ {
			if data[i][j-i] > 0 {
				continue
			}

			data[i][j-i] = num
			num++
		}
	}

	for i := 1; i < n; i++ {
		for j := n - 1; i+(n-1-j) < n && j >= 0; j-- {
			if data[i+(n-1-j)][j] > 0 {
				continue
			}

			data[i+(n-1-j)][j] = num
			num++
		}
	}

	for i := 0; i < n; i++ {
		for j := 0; j < n-1; j++ {
			fmt.Printf("%d ", data[i][j])
		}

		fmt.Printf("%d\n", data[i][n-1])
	}
}

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

	var t, n int

	fmt.Fscanf(reader, "%d\n", &t)
	for ; t > 0; t-- {
		fmt.Fscanf(reader, "%d\n", &n)
		m := matrix{n}

		if m.isOk() {
			m.String()
		} else {
			fmt.Println(-1)
		}
	}
}

package main

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

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

func main() {
	defer writer.Flush()
	var testcases int
	fmt.Fscan(reader, &testcases)

	for testcase := 0; testcase < testcases; testcase++ {
		var n int
		fmt.Fscan(reader, &n)

		board := make([][]int, n)
		for i := range board {
			board[i] = make([]int, n)
		}

		switch {
		case n == 2:
			fmt.Fprintln(writer, -1)
		case n%2 == 0 && n != 2:
			for i := 1; i <= n*n/2; i++ {
				board[(i-1)/(n/2)][(i-1)%(n/2)*2+1-(i-1)/(n/2)&1] = i
				board[(i-1)/(n/2)][(i-1)%(n/2)*2+(i-1)/(n/2)&1] = i + n*n/2
			}
			printBoard(board)
		case n%2 == 1:
			for i := 1; i <= n*n; i++ {
				pos := 2*i - 2
				board[(pos/n)%n][pos%n] = i
			}
			printBoard(board)
		}

	}
}

func printBoard(b [][]int) {
	for _, v := range b {
		fmt.Fprintln(writer, strings.TrimPrefix(strings.TrimSuffix(fmt.Sprint(v), "]"), "["))
	}
}

package main

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

func check(b bool) {
	if !b {
		_, _, line, _ := runtime.Caller(1)
		fmt.Printf("check failed line %d\n", line)
		os.Exit(-1)
	}
}

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

func max(x, y int) int {
	if y > x {
		return y
	}
	return x
}

func lowerBound(arr []int, t int) int {
	lo := 0
	hi := len(arr)
	for lo < hi {
		mid := lo + (hi-lo)/2
		if arr[mid] >= t {
			hi = mid
		} else {
			lo = mid + 1
		}
	}
	return hi
}

const (
	INIT = -1
	INF  = int(1e9)
)

var (
	exists = struct{}{} // for use with map[...]struct{}
	n      int
)

func solve(w *bufio.Writer) bool {
	if n == 2 {
		return false
	}
	c := 1
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			fmt.Fprintf(w, "%d ", c)
			if c == n*n || c+1 == n*n {
				c = 0
			}
			c += 2
		}
		fmt.Fprintf(w, "\n")
	}
	return true
}

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

	var tc int
	fmt.Fscan(r, &tc)

	for ; tc > 0; tc-- {
		fmt.Fscan(r, &n)
		if !solve(w) {
			fmt.Fprintf(w, "-1\n")
		}
	}
}

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n := 0, 0
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n)
		if n == 1 {
			fmt.Fprintln(w, 1)
		} else {
			if n == 2 {
				fmt.Fprintln(w, -1)
			} else {
				p := 1
				for j := 0; j < n; j++ {
					for k := 0; k < n; k++ {
						fmt.Fprint(w, p, " ")
						p += 2
						if p > n*n {
							p = 2
						}
					}
					fmt.Fprintln(w, "")
				}
			}
		}
	}
	w.Flush()
}

func main() {
	solve()
}

/*
* Filename: not-adjacent/main.go
* Timestamp: 12-09-2021 21:00:44
* Author: Fadhil Musaad
*/

package main

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

var (
	reader *bufio.Reader
	writer *bufio.Writer
	matrix[105][105]int
)

func scan(a ...interface{})    { fmt.Fscan(reader, a...) }
func scanln(a ...interface{})  { fmt.Fscanln(reader, a...) }
func print(a ...interface{})   { fmt.Fprint(writer, a...) }
func println(a ...interface{}) { fmt.Fprintln(writer, a...) }

func solve(_r io.Reader, _w io.Writer) {
	reader = bufio.NewReader(_r)
	writer = bufio.NewWriter(_w)
	defer writer.Flush()
	var t int
	scanln(&t)
	for ; t > 0; t-- {
		var n int
		scanln(&n)
		if n == 2 {
			println(-1)
			continue
		}
		now := 1
		for i := 0; i < n * n; i += 2 {
			row := i / n
			col := i % n
			matrix[row][col] = now
			now++
		}
		for i := 1; i < n * n; i += 2 {
			row := i / n
			col := i % n
			matrix[row][col] = now
			now++
		}
		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				if j > 0 {
					print(" ")
				}
				print(matrix[i][j])
			}
			println()
		}
	}
}

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

package main

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

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

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

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

	for te := 0; te < t; te++ {
		var n int
		fmt.Fscan(_r, &n)
		if n == 2 {
			fmt.Fprintf(_w, "%d\n", -1)
			continue
		}

		ans := make([]int, n*n)

		a, b := 1, (n*n+3)/2

		for i := 0; i < n*n; i++ {
			if i%2 == 0 {
				ans[i] = a
				a++
			} else {
				ans[i] = b
				b++
			}
		}

		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				fmt.Fprintf(_w, "%d ", ans[i*n+j])
			}
			fmt.Fprintln(_w, "")
		}
	}

}

package main

import "fmt"

func main() {
	var t int
	fmt.Scanln(&t)

	for k := 0; k < t; k++ {
		var n int
		fmt.Scanln(&n)

		if n == 2 {
			fmt.Println(-1)
			continue
		}

		number := 1

		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				fmt.Printf("%d ", number)
				number += 2
				if number > n * n {
					number = 2
				}
			}
			fmt.Print("\n")
		}
	}
}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var T, N int

	Fscan(in, &T)
	for t := 0; t < T; t++ {
		Fscan(in, &N)
		solve(out, N)
	}
}

func solve(out io.Writer, N int) {
	if N == 1 {
		Fprintln(out, 1)
		return
	}
	if N == 2 {
		Fprintln(out, -1)
		return
	}
	mat := [][]int{}
	for i := 0; i < N; i++ {
		mat = append(mat, make([]int, N))
	}

	n := 1
	y, x := 0, 0
	for i := 1; i <= N; i++ {
		mat[y][x] = n
		n++
		x++
		y++
	}
	y = 0
	x = 1
	s := N
	for n <= N*N {
		sy, sx := y, x
		for i := s - 1; i > 0; i-- {
			mat[y][x] = n
			n++
			y++
			x++
		}

		y = N - y
		x = N - x

		for i := s - 1; i > 0; i-- {
			mat[y][x] = n
			n++
			y++
			x++
		}

		s--

		y = sy
		x = sx + 1
	}

	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			Fprint(out, mat[i][j], " ")
		}
		Fprintln(out)
	}
}

package main

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

var fields []string

func init() {
	f, err := os.Open("in.txt")

	if err == nil {
		defer f.Close()
	} else {
		f = os.Stdin
	}

	bytes, err := ioutil.ReadAll(bufio.NewReader(f))

	if err != nil {
		panic(err)
	}

	fields = strings.Fields(string(bytes))
}

func ScanString() string {
	for {
		field := fields[0]
		fields = fields[1:]

		if field != "" {
			return field
		}
	}
}

func ScanInt() int {
	n, err := strconv.Atoi(ScanString())

	if err != nil {
		panic(err)
	}

	return n
}

func ScanInt64() int64 {
	n, err := strconv.ParseInt(ScanString(), 10, 64)

	if err != nil {
		panic(err)
	}

	return n
}

func main() {
	for t := ScanInt(); t > 0; t-- {
		n := ScanInt()

		if n == 2 {
			fmt.Println(-1)
			continue
		}

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

		for r := range m {
			m[r] = make([]int, n)
		}

		for i := 0; i < n*n; i++ {
			r := i % n
			c := (i%n + i/n) % n
			m[r][c] = i + 1
		}

		fmt.Println(strings.Trim(strings.ReplaceAll(fmt.Sprint(m), "] [", "\r\n"), "[]"))
	}
}

package main

import (
	"fmt"
)

func main() {

	var t int
	fmt.Scan(&t)
	for t > 0{
		t -= 1
		var n int
		fmt.Scan(&n)
		if n == 2{
			fmt.Println(-1)
		}else{
			num := 1
			for i :=1; i <= n; i++{
				for j := 1; j <= n ;j++{
					fmt.Printf("%d ", num)
					num += 2
					if num > n*n{
						num = 2
					}
				}
				fmt.Println()
			}
		}

	}
}

package main

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

// var m []int
// err = json.Unmarshal([]byte(r.FormValue("example")), &m)

// for i := 0; i < len(m); i++ {
// 	fmt.Println(m[i])
// }

// sort.Slice(arr, func(i, j int) bool {
// 	return arr[i] > arr[j]
// })

func MIN(x, y int64) int64 {
	if x > y {
		return y
	} else {
		return x
	}
}

func MKO(x, y int64) int64 {
	if x < y {
		return 0
	} else {
		return x - y + 1
	}
}

func MAX(x, y int64) int64 {
	if x > y {
		return x
	} else {
		return y
	}
}

func LCM(x, y int) int {
	if x >= y {
		initial := x
		for i := 1; i < y+2; i++ {
			if initial%y == 0 {
				break
			} else {
				initial = initial + x
			}

		}
		return initial
	} else {
		initial := y
		for i := 1; i < x+2; i++ {
			if initial%x == 0 {
				break
			} else {
				initial = initial + y
			}

		}
		return initial
	}
}

func GCD(x, y int64) int64 {
	var l, q int64
	l = MAX(x, y)
	q = MIN(x, y)
	var m int64
	for l*q > 0 {
		a := l % q
		b := l - a
		cc := int64(b / q)
		remain := l - cc*q
		l = MAX(remain, q)
		q = MIN(remain, q)
		if l*q == 0 {
			m = l + q
			break
		}

	}
	return m

}

func IsItPrime(x int) bool {
	if x < 10 {
		if x == 2 || x == 3 || x == 5 || x == 7 {
			return true
		} else {
			return false
		}
	} else {
		j := 0
		k := math.Sqrt(float64(x))
		for m := 3; m <= int(k); {
			if x%m == 0 {
				j = 1
				break
			}
			m = m + 2
		}
		if j == 1 {
			return false
		} else {
			return true
		}
	}

}

var t int

func main() {
	var input io.Reader = bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &t)
	for o := 0; o < t; o++ {
		var n int
		fmt.Fscan(input, &n)
		if n == 1 {
			fmt.Println(1)
		}
		if n == 2 {
			fmt.Println(-1)
		}
		if n == 3 {
			fmt.Println(2)
			fmt.Println(9)
			fmt.Println(7)
			fmt.Println(4)
			fmt.Println(6)
			fmt.Println(3)
			fmt.Println(1)
			fmt.Println(8)
			fmt.Println(5)

		}
		if n > 3 {
			q := n * n

			ODD := make([]int, 0)
			for i := 1; i < q+1; i++ {
				if i%2 == 0 {
					fmt.Println(i)
				} else {
					ODD = append(ODD, i)
				}
			}
			ww := len(ODD)
			for l := 0; l < ww; l++ {
				fmt.Println(ODD[l])
			}
		}

	}
}

package main

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

const maxN = 1023

func main() {
  in := bufio.NewReader(os.Stdin)
  out := bufio.NewWriter(os.Stdout)
  defer out.Flush()
  var tt int
  fmt.Fscan(in, &tt)
  for tc := 1; tc <= tt; tc++ {
    var n int
    fmt.Fscan(in, &n)
    if n == 2 {
      fmt.Fprintln(out, -1)
      continue
    }
    var m[maxN][maxN] int
    cnt := 1
    box := 1
    for i := 1; i <= n; i++ {
      for j := 1; j <= n; j++ {
        if box % 2 == 1 {
          m[i][j] = cnt
          cnt++
        }
        box++
      }
    }
    box = 1
    for i := 1; i <= n; i++ {
      for j := 1; j <= n; j++ {
        if box % 2 == 0 {
          m[i][j] = cnt
          cnt++
        }
        box++
        fmt.Fprint(out, m[i][j], " ")
      }
      fmt.Fprintln(out)
    }
  }
}

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 println(a ...interface{})          { fmt.Fprintln(writer, a...) }
func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func scanString(s *string) { fmt.Fscanln(reader, s) }

var mat [107][107]int

func test_case() {
	var n int

	scanf("%d\n", &n)

	if n == 2 {
		println(-1)
		return
	} else if n == 3 {
		printf("2 9 7\n4 6 3\n1 8 5\n")
		return
	}

	cur := 1
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			printf("%d ", cur)
			cur += 2
			if cur > n * n {
				cur = 2
			}
		}
		println()
	}
}

func main() {
	defer writer.Flush()
	var t int

	scanf("%d\n", &t)
	for t > 0 {
		test_case()
		t--
	}

}

package main

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

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

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

	for ; t > 0; t-- {
		fmt.Fscan(in, &n)
		if n == 2 {
			fmt.Println(-1)
			continue
		}
		a := make([]int, n*n)
		for i := 1; i <= n*n; i += 2 {
			a[(i-1)/2] = i
		}
		for i := 2; i <= n*n; i += 2 {
			a[(n*n+1)/2+i/2-1] = i
		}

		for i := 0; i < n; i++ {
			for j := 0; j < n; j++ {
				fmt.Fprint(out, a[i*n+j], " ")
			}
			fmt.Fprintln(out)
		}
		out.Flush()
	}
}

package main

import (
	"bufio"
	. "fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

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

	solve := func(Case int) {
		var n int
		Fscan(in, &n)
		if n ==2 {
			Fprintln(out, -1)
			return
		}
		a := make([][]int, n)
		for i := range a {
			a[i] = make([]int, n)
		}
		c:=1
		for s := 0; s < n+n-1; s+=2 {
			l := max(0, s-n+1)
			r := min(n-1, s)
			for j := l; j <= r; j++ {
				i := s - j
				a[i][j] = c
				c++
			}
		}
		for s := 1; s < n+n-1; s+=2 {
			l := max(0, s-n+1)
			r := min(n-1, s)
			for j := l; j <= r; j++ {
				i := s - j
				a[i][j] = c
				c++
			}
		}
		for _, r := range a {
			for _, v := range r {
				Fprint(out, v, " ")
			}
			Fprintln(out)
		}
	}

	T := 1
	Fscan(in, &T) //
	for Case := 1; Case <= T; Case++ {
		solve(Case)
	}

	_leftData, _ := ioutil.ReadAll(in)
	if _s := strings.TrimSpace(string(_leftData)); _s != "" {
		panic("有未读入的数据：\n" + _s)
	}
}

func main() { run(os.Stdin, os.Stdout) }
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

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

package main

import (
	"bufio"
	"fmt"
	"os"
	"math/rand"
	"time"
)

func main() {

	r := bufio.NewReader(os.Stdin)

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

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

		ans,res := solve(n)

		if !res {
			fmt.Println(-1)
		} else {

			for i := 0; i < len(ans); i++ {
				for j := 0; j < len(ans[0]); j++ {
					fmt.Print(ans[i][j])
					fmt.Print(" ")
				}
				fmt.Println()
			}
			fmt.Println()
		}

	}
}

func solve(n int) ([][]int, bool) {
	if n <= 2 {
		return [][]int{}, false
	}

	mp := make([][]bool, n)

	for i := 0; i < n ; i++ {
		mp[i] = make([]bool, n)
	}

	ans := make([][]int, n)
	for j := 0; j < len(ans); j++ {
		ans[j] = make([]int, n)
	}

	rand.Seed(time.Now().Unix())

	dfs(&ans, &mp, n, 1, 0)

	return ans, true
}

func dfs(ans *[][]int, mp *[][]bool, n int, next int, total int) bool {

	for c := 0; c < 1000; c++ {

		if total >= n * n {
			return true
		}

		i := rand.Intn(n)
		j := rand.Intn(n)

		if (*mp)[i][j] {
			continue
		}

		if checkNeighbourgs(ans, i, j, next, n) {
			(*mp)[i][j] = true

			(*ans)[i][j] = next

			res := dfs(ans, mp, n, next + 1, total + 1)

			if res {
				return true
			}

			(*mp)[i][j] = false

			(*ans)[i][j] = 0

			continue

		} else {
			continue
		}
	}

	return false
}

func checkNeighbourgs(ans *[][]int, i, j int, next int, n int) bool {
	if (*ans)[i][j] != 0 {
		return false
	}

	v := getValue(i + 1, j, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	v = getValue(i - 1, j, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	v = getValue(i, j + 1, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	v = getValue(i, j - 1, ans, n)

	if v != 0 && abs(v - next) <= 1 {
		return false
	}

	return true
}

func getValue(i, j int, ans *[][]int, n int) int {
	if i < 0 || i >= n || j < 0 || j >= n {
		return 0
	}
	return (*ans)[i][j]
}

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

package main

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

var reader = bufio.NewReader(os.Stdin)

func ri() int {
	var x int
	c, _ := reader.ReadByte()
	for c < '0' || c > '9' {
		c, _ = reader.ReadByte()
	}
	for '0' <= c && c <= '9' {
		x = (x << 3) + (x << 1) + int(c) - '0'
		c, _ = reader.ReadByte()
	}
	return x
}

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

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

const MAXN = 1e2 + 5

var mp [MAXN][MAXN]int

func Solve() {
	n := ri()
	if n == 2 {
		fmt.Println(-1)
		return
	}
	cnt := 1
	for j := 1; j <= n; j++ {
		for i := 0; i < n; i++ {
			mp[i+1][(i+j-1)%n+1] = cnt
			cnt++
		}
	}
	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			fmt.Printf("%d ", mp[i][j])
		}
		fmt.Printf("\n")
	}
}

func main() {
	fmt.Println(1 % 1)
	var T = 0
	if T == 0 {
		fmt.Scan(&T)
	}
	for t := 1; t <= T; t++ {
		Solve()
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func ri() int {
	var x int
	c, _ := reader.ReadByte()
	for c < '0' || c > '9' {
		c, _ = reader.ReadByte()
	}
	for '0' <= c && c <= '9' {
		x = (x << 3) + (x << 1) + int(c) - '0'
		c, _ = reader.ReadByte()
	}
	return x
}

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

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

const MAXN = 1e2 + 5

var mp [MAXN][MAXN]int

func Solve() {
	n := ri()
	if n == 2 {
		fmt.Println(-1)
		return
	}
	cnt := 1
	for j := 1; j <= n; j++ {
		for i := 0; i < n; i++ {
			mp[i+1][(i+j-1)%n+1] = cnt
			cnt++
		}
	}
	fmt.Println(cnt)
	for i := 1; i <= n; i++ {
		for j := 1; j <= n; j++ {
			fmt.Printf("%d ", mp[i][j])
		}
		fmt.Printf("\n")
	}
}

func main() {
	var T = 0
	if T == 0 {
		fmt.Scan(&T)
	}
	for t := 1; t <= T; t++ {
		Solve()
	}
}

package main

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

var reader = bufio.NewReader(os.Stdin)

func ri() int {
	var x int
	c, _ := reader.ReadByte()
	for c < '0' || c > '9' {
		c, _ = reader.ReadByte()
	}
	for '0' <= c && c <= '9' {
		x = (x << 3) + (x << 1) + int(c) - '0'
		c, _ = reader.ReadByte()
	}
	return x
}

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

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

const MAXN = 1e3 + 5

func Solve() {
	n := ri()
	ans := 0
	for i := 1; i <= 9; i++ {
		x := int64(i)
		for x <= int64(n) {
			ans++
			x = x*10 + int64(i)
		}
	}
	fmt.Println(ans)
}

func main() {
	var T = 0
	if T == 0 {
		fmt.Scan(&T)
	}
	for t := 1; t <= T; t++ {
		Solve()
	}
}

package main

import (
	"fmt"
	"math"
)

func print(matrix [][]int) {
	for _, line := range matrix {
		for _, v := range line {
			fmt.Print(v)
		}
		fmt.Print("\n")
	}
}

func makeMatrix(n int) [][]int {
	m := make([][]int, n)
	for i, _ := range m {
		m[i] = make([]int, n)
	}
	return m
}

func diff(a, b int) int {
	d := a - b
	if d < 0 {
		d = d * -1
	}
	return d
}

func isValid(i, j int, m [][]int) bool {
	val := m[i][j]
	if i == 0 && j == 0 {
		return true
	}
	if i > 0 && diff(m[i-1][j], val) < 2 {
		return false
	}
	if j > 0 && diff(m[i][j-1], val) < 2 {
		return false
	}
	if i < len(m)-1 && diff(m[i+1][j], val) < 2 {
		return false
	}
	if j < len(m)-1 && diff(m[i][j+1], val) < 2 {
		return false
	}
	return true
}

func fill(m [][]int) bool {
	if len(m) == 2 {
		return false
	}
	max := int(math.Pow(float64(len(m)), 2.0))
	currX, currY := 1, 0
	isXStart := false
	for i := 1; i <= max; {
		var x, y int
		if isXStart {
			x = currX
			y = 0
			currX++
		} else {
			x = 0
			y = currY
			currY++
		}
		for ; x < len(m) && y < len(m); x, y = x+1, y+1 {
			m[y][x] = i
			i++
		}
		isXStart = !isXStart
	}
	return true
}

func main() {
	var nTests int
	fmt.Scanf("%d\n", &nTests)
	for i := 0; i < nTests; i++ {
		var n int
		fmt.Scanf("%d\n", &n)
		m := makeMatrix(n)
		if ok := fill(m); ok {
			print(m)
		} else {
			fmt.Println("-1")
		}

	}
}

/* func main() {
	m := makeMatrix(50)
	fill(m)
	print(m)
} */

package main

import (
	"fmt"
)

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

	if N == 2 {
		fmt.Println(-1)
		return
	}

	evenCnt := 0
	oddCnt := (N * N) / 2 + 1
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if (i + j) % 2 == 0 {
				evenCnt++
				fmt.Print(evenCnt, " ")
			} else {
				oddCnt++
				fmt.Print(oddCnt, " ")
			}
		}
		fmt.Println()
	}
}

func main() {
	var T int

	fmt.Scanf("%d\n", &T)

	for i := 0; i < T; i++ {
		main1()
	}
}

package main

import "fmt"

func print_matrix(n int) {
    n_mod0 := n / 2
    n_mod1 := n - n_mod0
    shift := n_mod0 * n
    for y := 0; y < n; y++ {
        for x := 0; x < n; x++ {
            var val int
            if x % 2 == 0 {
                true_x := x / 2
                val = 1 + true_x + y * n_mod0
            } else {
                true_x := (x - 1) / 2
                val = 1 + shift + true_x + y * n_mod1
            }
            fmt.Print(val, " ")
        }
        fmt.Println()
    }
}

func main() {
    var n_tasks int
    fmt.Scanf("%d\n", &n_tasks)
    for i := 0; i < n_tasks; i++ {
        var n int
        fmt.Scanln(&n)
        if n == 2 {
            fmt.Println(-1)
        } else if n == 3 {
            fmt.Println("2 9 7")
            fmt.Println("4 6 3")
            fmt.Println("1 8 5")
        } else {
            print_matrix(n)
        }
    }
}

package main

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

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

func main() {
	defer writer.Flush()
	var testcases int
	fmt.Fscan(reader, &testcases)

	for testcase := 0; testcase < testcases; testcase++ {
		var n int
		fmt.Fscan(reader, &n)

		board := make([][]int, n)
		for i := range board {
			board[i] = make([]int, n)
		}

		switch {
		case n == 2:
			fmt.Fprintln(writer, -1)
		case n%2 == 0 && n != 2:
			for i := 1; i <= n*n/2; i++ {
				board[(i-1)/(n/2)][(i-1)%(n/2)*2+1-(i-1)/(n/2)&1] = i
				board[(i-1)/(n/2)][(i-1)%(n/2)*2+(i-1)/(n/2)&1] = i + n*n/2
			}
		case n%2 == 1:
			for i := 1; i <= n*n; i++ {
				pos := 2*i - 2
				board[(pos/n)%n][pos%n] = i
			}
		}

		printBoard(board)
	}
}

func printBoard(b [][]int) {
	for _, v := range b {
		fmt.Fprintln(writer, strings.TrimPrefix(strings.TrimSuffix(fmt.Sprint(v), "]"), "["))
	}
}


Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the second test case:   The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$.  The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$  The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$.  The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$.  The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$.  The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.

package main

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

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

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

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

		var tally int64
		for win := len(arr); win >= 1; win-- {
			for i := 0; i+win <= n; i++ {
				arr2 := arr[i : i+win]
				for j := 0; j < len(arr2); j++ {
					if arr2[j] == 0 {
						tally++
					}
				}

				tally += int64(len(arr2))
			}
		}
		fmt.Fprintln(out, tally)
	}
}

//nolint
package main

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

//{
var reader = bufio.NewReader(os.Stdin)
var 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 print(a ...interface{})            { fmt.Fprint(writer, a...) }
func println(a ...interface{})          { fmt.Fprintln(writer, a...) }
func scan(a ...interface{})             { fmt.Fscan(reader, a...) }

func main() {
	defer writer.Flush()

	Main()
}

//}

func Main() {
	var t int
	scan(&t)
	for ; t > 0; t-- {
		Solve()
	}
}

func Solve() {
	var n, tp int
	scan(&n)
	sum := 0
	for i := 1; i <= n; i++ {
		scan(&tp)
		if tp == 0 {
			sum += 2 * i * (n - i + 1)
		} else {
			sum += i * (n - i + 1)
		}
	}
	println(sum)
}

// I nid to know particular number appear in a partition how many time!!!

package main

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

func getMex(arr []int) int {
	m := make([]bool, 101)
	for i := range arr {
		if arr[i] >= 0 && arr[i] <= 100 {
			m[arr[i]] = true
		}
	}
	for i := range m {
		if !m[i] {
			return i
		}
	}
	return -1
}
func alg(arr []int) int {
	n := len(arr)
	mexs := make([][]int, n)
	for i := range mexs {
		mexs[i] = make([]int, n)
	}
	for i := 0; i < n; i++ {
		for j := i; j < n; j++ {
			mexs[i][j] = getMex(arr[i : j+1])
		}
	}
	// Println("mexs:", mexs)
	dp := make([][]int, n+1)
	for i := range dp {
		dp[i] = make([]int, n+1)
	}
	for i := 0; i < n; i++ {
		dp[i][i] = 1 + mexs[i][i]
	}

	for r := 2; r <= n; r++ {
		for i := 0; i <= n-r; i++ {
			j := i + r - 1
			res := math.MinInt32
			for k := i; k < j; k++ {
				res = max(res, dp[i][k]+dp[k+1][j])
			}
			dp[i][j] = max(1+mexs[i][j], res)
		}
	}
	var ans int
	for i := 0; i < n; i++ {
		for j := i; j < n; j++ {
			ans += dp[i][j]
		}
	}
	return ans
}
func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

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

	arr := make([]int, 110)
	var t, n int
	for Fscan(in, &t); t > 0; t-- {
		Fscan(in, &n)
		for i := 0; i < n; i++ {
			Fscan(in, &arr[i])
		}
		Fprintln(out, alg(arr[:n]))
		out.Flush()
	}
}

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

package main

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

var x int

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 {
		var n int
		fmt.Fscan(in, &n)
		nums := make([]int, n)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &nums[i])
		}
		res := 0
		for i := 0; i < n; i++ {
			if nums[i] != 0 {
				res += (i + 1) * (n - i)
			} else {
				res += (i + 1) * (n - i) * 2
			}
		}
		fmt.Fprintln(out, res)
		t--
	}
}

package main

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

/*

 */

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

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

	for ; t > 0; t-- {
		var n int64
		scanf("%d\n", &n)

		a := make([]int64, n)

		for i := range a {
			scanf("%d", &a[i])
		}
		scanf("\n")

		sumOfValues := int64(0)

		for i := int64(0); i < n; i++ {
			for j := i; j < n; j++ {
				subSeg := a[i : j+1]

				zeroCnt := 0
				for _, num := range subSeg {
					if num == 0 {
						zeroCnt++
					}
				}

				cost := int64(len(subSeg) + zeroCnt)
				maxCost := cost // aka value

				sumOfValues += maxCost
			}
		}

		fmt.Fprintln(writer, sumOfValues)
	}
}

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 int) int {
	quot := num / div
	if num%div != 0 {
		quot++
	}
	return quot
}

//goland:noinspection GoUnusedFunction
func min(nums ...int) int {
	minimum := nums[0]
	for _, num := range nums {
		if num < minimum {
			minimum = num
		}
	}
	return minimum
}

//goland:noinspection GoUnusedFunction
func max(nums ...int) int {
	maximum := nums[0]
	for _, num := range nums {
		if num > maximum {
			maximum = num
		}
	}
	return maximum
}

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

package main

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

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

func flush()                            { out.Flush() }
func scan(a ...interface{})             { fmt.Fscan(in, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(out, f, a...) }
func assert(f bool) {
	if !f {
		panic("gg")
	}
}

// ----------------------------- TEMPLATE END ----------------------------------

func main() {
	defer flush()

	var ntc int
	scan(&ntc)
	for t := 0; t < ntc; t++ {
		var n int
		scan(&n)
		a := make([]int, n)
		for i := 0; i < n; i++ {
			scan(&a[i])
		}
		ans := 0
		for i := 0; i < n; i++ {
			cnt0 := 0
			for j := i; j < n; j++ {
				if a[j] == 0 {
					cnt0++
				}
				ans += (j - i + 1 + cnt0)
			}
		}
		printf("%d\n", ans)
	}
}

package main

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

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

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

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

		var tally int64
		for win := len(arr); win >= 1; win-- {
			for i := 0; i+win <= n; i++ {
				arr2 := arr[i : i+win]
				var mex int64
				for j := 0; j < len(arr2); j++ {
					if arr2[j] == mex {
						mex++
					} else if mex > 0 {
						tally += mex + 1 + 1
						mex = 0
					} else {
						tally++
					}
				}

				if mex-1 == arr2[len(arr2)-1] {
					tally += mex + 1
				}

			}
		}
		fmt.Fprintln(out, tally)
	}
}

package main

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

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

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

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

		var tally int
		for win := len(arr); win >= 1; win-- {
			for i := 0; i+win <= n; i++ {
				arr2 := arr[i : i+win]
				var mex int
				for j := 0; j < len(arr2); j++ {
					if arr2[j] == mex {
						mex++
					} else if mex > 0 {
						tally += mex + 1 + 1
						mex = 0
					} else {
						tally++
					}
				}

				if mex-1 == arr2[len(arr2)-1] {
					tally += mex + 1
				}
			}
		}
		fmt.Fprintln(out, tally)
	}
}