package main

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

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

func main() {
	defer writer.Flush()

	var T int
	fmt.Fscan(reader, &T)
	for ; T > 0; T-- {
		var n int
		fmt.Fscan(reader, &n)

		a := make([]int, n+1)
		pref := make([][]int, 2)

		pref[0] = make([]int, n+1)
		pref[1] = make([]int, n+1)

		var inv int64 = 0

		for i := 1; i <= n; i++ {
			fmt.Fscan(reader, &a[i])
			for j := 0; j < 2; j++ {
				val := 0
				if a[i] == j {
					val = 1
				}
				pref[j][i] = pref[j][i-1] + val
			}
			if a[i] == 0 {
				inv += int64(pref[1][i-1])
			}
		}

		var ans int64 = inv

		Max := func(lhs, rhs int64) int64 {
			if lhs > rhs {
				return lhs
			}
			return rhs
		}

		for i := 1; i <= n; i++ {
			if a[i] == 0 {
				ans = Max(ans, inv-int64(pref[1][i-1])+int64(pref[0][n])-int64(pref[0][i]))
			} else {
				ans = Max(ans, inv+int64(pref[1][i-1])-int64(pref[0][n])+int64(pref[0][i]))
			}
		}

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

package main

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

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

// source: _
func solve() {
	n, arr := _readArr()
	z, o := 0, n-1
	res := 0

	cz := 0
	for i := n - 1; i >= 0; i-- {
		if arr[i] == 0 {
			cz++
		} else {
			res += cz
		}
	}

	for z < n && arr[z] != 0 {
		z++
	}
	for o >= 0 && arr[o] != 1 {
		o--
	}

	co := n - cz

	sz := -z + cz - 1
	so := -(n - 1 - o) + co - 1
	if so < 0 && sz < 0 {
		_print(res)
	} else if so > sz {
		_print(res + so)
	} else {
		_print(res + sz)
	}
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		solve()
	}
}

// ====
func _readInt() int {
	var x int
	fmt.Fscan(in, &x)
	return x
}
func _readStr() string {
	var x string
	fmt.Fscan(in, &x)
	return x
}
func _readArr(x ...int) (int, []int) {
	var n int
	if len(x) == 0 {
		fmt.Fscan(in, &n)
	} else {
		n = x[0]
	}
	var v = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	return n, v
}
func _print(x ...any) {
	fmt.Fprintln(out, x...)
}
func _max(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] > x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _min(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] < x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _sum(x ...int) int {
	res := 0
	for _, i := range x {
		res += i
	}
	return res
}
func _abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func _sortStr(x string) string {
	r := []rune(x)
	sort.Slice(r, func(i, j int) bool {
		return r[i] < r[j]
	})
	return string(r)
}
func _reverseInts(x []int) {
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
}
func _reverseStr(s string) string {
	x := []rune(s)
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
	return string(x)
}
func _makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}

package main

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

const cf = true

func solve() {
	var n int
	fmt.Fscan(in, &n)
	arr := make([]int, n)
	for i := range arr {
		fmt.Fscan(in, &arr[i])
	}
	cur0, cur1 := 0, 0
	cnt0, cnt1 := make([]int, n), make([]int, n)
	for i := 0; i < n; i++ {
		cnt1[i] = cur1
		if arr[i] == 1 {
			cur1++
		}
	}
	ans := 0
	for i := n - 1; i >= 0; i-- {
		if arr[i] == 1 {
			ans += cur0
		}

		cnt0[i] = cur0
		if arr[i] == 0 {
			cur0++
		}
	}

	anss := ans

	for i := 0; i < n; i++ {
		if arr[i] == 0 {
			nextAns := ans
			nextAns -= cnt1[i]
			nextAns += cnt0[i]
			anss = max(anss, nextAns)

			break
		}
	}
	for i := n - 1; i >= 0; i-- {
		if arr[i] == 1 {
			nextAns := ans
			nextAns += cnt1[i]
			nextAns -= cnt0[i]
			anss = max(anss, nextAns)

			break
		}
	}
	fmt.Fprintln(out, anss)
}

func main() {
	defer out.Flush()
	t := 1
	fmt.Fscan(in, &t)
	for ; t > 0; t-- {
		solve()
	}
}

func LCM(a, b int) int {
	return a * b / GCD(a, b)
}

func GCD(a, b int) int {
	for b != 0 {
		a, b = b, a%b
	}

	return a
}

type SqrtInt interface {
	SignedSqrt | UnsignedSqrt
}

type SignedSqrt interface {
	~int | ~int32 | ~int64
}

type UnsignedSqrt interface {
	~uint | ~uint32 | ~uint64 | ~uintptr
}

func sqrt[T SqrtInt](x T) T {
	l, r := T(0), T(2000000123)
	for l < r {
		mid := (l + r) / 2
		if mid*mid > x {
			r = mid
		} else {
			l = mid + 1
		}
	}
	return l - 1
}

func ConvertInt(val string, base, toBase int) (string, error) {
	i, err := strconv.ParseInt(val, base, 64)
	if err != nil {
		return "", err
	}
	return strconv.FormatInt(i, toBase), nil
}

const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1

func reverseStr(s string) string {
	r := []byte(s)
	for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
		r[i], r[j] = r[j], r[i]
	}
	return string(r)
}

type Float interface {
	~float32 | ~float64
}

type Integer interface {
	Signed | Unsigned
}

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Ordered interface {
	Integer | Float | ~string
}

func abs[T Signed](x T) T {
	if x < 0 {
		return -x
	}
	return x
}

func min[T Ordered](x, y T) T {
	if x < y {
		return x
	}
	return y
}

func max[T Ordered](x, y T) T {
	if x > y {
		return x
	}
	return y
}

var (
	in  = getReader()
	out = getWriter()
)

func getReader() *bufio.Reader {
	if cf {
		return bufio.NewReader(os.Stdin)
	} else {
		in, _ := os.Open("input.txt")
		return bufio.NewReader(in)
	}
}

func getWriter() *bufio.Writer {
	if cf {
		return bufio.NewWriter(os.Stdout)
	} else {
		out, _ := os.Create("output.txt")
		return bufio.NewWriter(out)
	}
}

package main

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

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

	var T int
	for fmt.Fscan(r, &T); T > 0; T-- {

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

		a := make([]int, n)
		for i := range a {
			fmt.Fscan(r, &a[i])
		}

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

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

		// fmt.Fprintln(w, "%%%%%%%%%%")
		// fmt.Fprintln(w, "a", a)
		// fmt.Fprintln(w, "ps", ps)
		// fmt.Fprintln(w, "ss", ss)
		var i, res int
		for i = 0; i < n && a[i] == 1; i++ {}
		if i < n-1 && ss[i+1] > ps[i] {
			res = ss[i+1] - ps[i]
		}
		// fmt.Fprintln(w, "i", i)
		// fmt.Fprintln(w, "res", res)

		for i = n-1; i >= 0 && a[i] == 0; i-- {}
		if i > 0 && ps[i-1] - ss[i] > res {
			res = ps[i-1] - ss[i]
		}
		// fmt.Fprintln(w, "i", i)
		// fmt.Fprintln(w, "res", res)

		for i, v := range a {
			if v == 1 {
				res += ss[i]
			}
		}

		fmt.Fprintln(w, res)
	}

}

package main

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

func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	//输入t
	var t, n int
	fmt.Fscan(in, &t)
	for i := 0; i < t; i++ {
		fmt.Fscan(in, &n)
		nums := make([]int, n)
		ones := make([]int, n)
		zeros := make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Fscan(in, &nums[j])
		}
		for j := 0; j < n; j++ {
			if nums[j] == 1 {
				if j > 0 {
					ones[j] = ones[j-1] + 1
				} else {
					ones[j] = 1
				}
			} else {
				if j > 0 {
					ones[j] = ones[j-1]
				} else {
					ones[j] = 0
				}
			}
		}
		zeros[n-1] = 0
		if nums[n-1] == 0 {
			zeros[n-1] = 1
		}
		for j := n - 2; j >= 0; j-- {
			if nums[j] == 0 {
				zeros[j] = zeros[j+1] + 1
			} else {
				zeros[j] = zeros[j+1]
			}
		}
		ans := int64(0)
		zero := int64(0)
		for j := n - 1; j >= 0; j-- {
			if nums[j] == 0 {
				zero++
			} else {
				ans += zero
			}
		}
		res := ans
		for j := n - 1; j >= 0; j-- {
			if nums[j] == 0 {
				temp := (zeros[j] - 1) - ones[j]
				if int64(temp)+res > ans {
					ans = int64(temp) + res
				}
			} else {
				temp := ones[j] - 1 - zeros[j]
				if int64(temp)+res > ans {
					ans = int64(temp) + res
				}
			}
		}
		// 输出res
		fmt.Fprintln(out, ans)
	}
}

package main

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

func solve(reader *bufio.Reader, writer *bufio.Writer) {
	n := readInt(reader)
	a := readArrayInt(reader)

	maxx := inv(a, n)
	id := -1
	for i := 0; i < n; i++ {
		if a[i] == 0 {
			id = i
			break
		}
	}

	if id != -1 {
		a[id] = 1
		inver := inv(a, n)
		maxx = max(inver, maxx)
		a[id] = 0
	}

	id = -1
	for i := n - 1; i >= 0; i-- {
		if a[i] == 1 {
			id = i
			break
		}
	}
	if id != -1 {
		a[id] = 0
		inver := inv(a, n)
		maxx = max(inver, maxx)
		a[id] = 1
	}

	fmt.Fprintln(writer, maxx)
}

func inv(a []int, n int) int64 {
	var cntOnes, ans int64
	for i := 0; i < n; i++ {
		if a[i] == 0 {
			ans += cntOnes
		} else {
			cntOnes++
		}
	}

	return ans
}

func main() {
	reader := bReader(os.Stdin)
	writer := bWriter(os.Stdout)

	t := readInt(reader)

	for t > 0 {
		solve(reader, writer)
		t--
	}

	writer.Flush()
}

func min[T int | int64](a, b T) T {
	if a < b {
		return a
	}

	return b
}

func max[T int | int64](a, b T) T {
	if a > b {
		return a
	}

	return b
}

func abs[T int | int64](a T) T {
	if a < 0 {
		return a * -1
	} else {
		return a
	}
}

func gcd[T int | int64](x, y T) T {
	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func lcm[T int | int64](x, y T) T {
	return x * y / gcd(x, y)
}

func bReader(stdin *os.File) *bufio.Reader {
	return bufio.NewReaderSize(stdin, 16*1024*1024)
}

func bWriter(stdout *os.File) *bufio.Writer {
	return bufio.NewWriterSize(stdout, 16*1024*1024)
}

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

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

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

func readInt(reader *bufio.Reader) int {
	return int(readInt64(reader))
}

func readInt64(reader *bufio.Reader) int64 {
	value, err := strconv.ParseInt(readLine(reader), 10, 64)
	checkError(err)

	return value
}

func readString(reader *bufio.Reader) string {
	return readLine(reader)
}

func readArrayString(reader *bufio.Reader) []string {
	return strings.Split(strings.TrimSpace(readLine(reader)), " ")
}

func readArrayInt(reader *bufio.Reader) []int {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := int(arItemTemp)
		ar = append(ar, arItem)
	}

	return ar
}

func readArrayInt64(reader *bufio.Reader) []int64 {
	arTemp := strings.Split(strings.TrimSpace(readLine(reader)), " ")
	n := len(arTemp)

	var ar []int64

	for i := 0; i < n; i++ {
		arItemTemp, err := strconv.ParseInt(arTemp[i], 10, 64)
		checkError(err)
		arItem := arItemTemp
		ar = append(ar, arItem)
	}

	return ar
}

func readTwoInt(reader *bufio.Reader) (int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1]
}

func readTwoInt64(reader *bufio.Reader) (int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1]
}

func readThreeInt(reader *bufio.Reader) (int, int, int) {
	ar := readArrayInt(reader)
	return ar[0], ar[1], ar[2]
}

func readThreeInt64(reader *bufio.Reader) (int64, int64, int64) {
	ar := readArrayInt64(reader)
	return ar[0], ar[1], ar[2]
}

package main

import (
	"fmt"
)

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

func solve() {
	var n int
	fmt.Scan(&n)
	f := make([]int, n + 10)
	for i := 1; i <= n; i++ {
		fmt.Scan(&f[i])
	}
	suf0 := make([]int, n + 10)
	pre1 := make([]int, n + 10)
	var sum int64 = 0
	var curr int64 = 0
	for i := n; i >= 1; i-- {
		if f[i] == 1 {
			sum += curr
		} else {
			curr += 1
		}
		if f[i] == 0 {
			suf0[i] = suf0[i + 1] + 1
		} else {
			suf0[i] = suf0[i + 1]
		}
	}
	for i := 1; i <= n; i++ {
		if f[i] == 1 {
			pre1[i] = pre1[i - 1] + 1
		} else {
			pre1[i] = pre1[i - 1]
		}
	}
	var ans int64 = sum
	for i := 1; i <= n; i++ {
		var now int64
		if f[i] == 1 {
			now = sum + int64(pre1[i - 1]) - int64(suf0[i + 1])
		} else {
			now = sum + int64(suf0[i + 1]) - int64(pre1[i - 1])
		}
		ans = max(now, ans)
	}
	fmt.Println(ans)
}

func main() {
	var t int
	fmt.Scan(&t)
	for i := 0; i < t; i++ {
		solve()
	}
}

package main

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

var sc = bufio.NewScanner(os.Stdin)

const mod int = 998244353
const N int = 5e5 + 5

func main() {
	sc.Buffer(make([]byte, 500000*1+1), 500000)
	sc.Split(bufio.ScanWords)

	T := nextInt()
	for T > 0 {
		T--
		n := nextInt()
		a := make([]int, n+1)
		for i := 1; i <= n; i++ {
			a[i] = nextInt()
		}
		one := make([]int, n+1)
		for i := 1; i <= n; i++ {
			one[i] = one[i-1] + a[i]
		}
		zero := make([]int, n+2)
		for i := n; i >= 1; i-- {
			if a[i] == 0 {
				zero[i] = zero[i+1] + 1
			} else {
				zero[i] = zero[i+1]
			}
		}
		ans := 0
		for i := 1; i <= n; i++ {
			if a[i] == 1 {
				ans += zero[i+1]
			}
		}
		tmp := 0
		for i := 1; i <= n; i++ {
			now, next := 0, 0
			if a[i] == 1 {
				now = zero[i+1]
			} else {
				now = one[i-1]
			}
			if a[i] == 1 {
				next = one[i-1]
			} else {
				next = zero[i+1]
			}
			tmp = max(tmp, next-now)
		}
		fmt.Println(ans + tmp)
	}
}

func max(args ...int) int {
	res := args[0]
	for _, v := range args {
		if v > res {
			res = v
		}
	}
	return res
}

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

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

package main

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

// https://space.bilibili.com/206214
func run(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()

	solve := func(curCase int) {
		var n int
		Fscan(in, &n)
		a := make([]int, n)
		ans := int64(0)
		for i := range a {
			Fscan(in, &a[i])
		}
		f := func() {
			inv := int64(0)
			c1 := int64(0)
			for i := range a {
				if a[i] == 0 {
					inv += c1
				} else {
					c1++
				}
			}
			ans = max(ans, inv)
		}

		f()
		for i, v := range a {
			if v == 0 {
				a[i] = 1
				f()
				a[i] = 0
				break
			}
		}
		for i := len(a) - 1; i >= 0; i-- {
			v := a[i]
			if v == 1 {
				a[i] = 0
				f()
				a[i] = 1
				break
			}
		}

		Fprintln(out, ans)
	}

	cases := 1
	Fscan(in, &cases)
	for curCase := 1; curCase <= cases; curCase++ {
		solve(curCase)
	}

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

}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		leftZero := -1
		rightOne := -1
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
			if arr[i] == 0 && leftZero == -1 {
				leftZero = i
			}

			if arr[i] == 1 {
				rightOne = i
			}
		}
		c := fu(&arr, n)

		a := int64(0)
		if leftZero != -1 {
			arr[leftZero] = 1
			a = fu(&arr, n)
			arr[leftZero] = 0
		}

		b := int64(0)
		if rightOne != -1 {
			arr[rightOne] = 0
			b = fu(&arr, n)
		}

		fmt.Println(int64(math.Max(float64(a), math.Max(float64(b), float64(c)))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n)
	for i := n - 1; i >= 0; i-- {
		if i < n-1 {
			dp[i] = dp[i+1]
		}
		if (*arr)[i] == 0 {
			dp[i]++
		}

	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			ans += int64(dp[i])
		}
	}
	return ans
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}
		c := fu(&arr, n)

		pos := -1
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				pos = i
				arr[i] = 1
				break
			}
		}

		a := int64(0)

		if pos != -1 {
			a = fu(&arr, n)
			arr[pos] = 0
		}

		pos = -1
		for i := n - 1; i >= 0; i-- {
			if arr[i] == 1 {
				arr[i] = 0
				pos = i
				break
			}
		}

		b := int64(0)
		if pos != -1 {
			b = fu(&arr, n)
		}

		fmt.Println(int64(math.Max(float64(a), math.Max(float64(b), float64(c)))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n)
	for i := n - 1; i >= 0; i-- {
		if i < n-1 {
			dp[i] = dp[i+1]
		}
		if (*arr)[i] == 0 {
			dp[i]++
		}

	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			ans += int64(dp[i])
		}
	}
	return ans
}

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

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

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"index/suffixarray"
	"log"
	"math"
	"net"
	"os"
	"path"
	"sort"
	"strconv"
	"strings"
	"time"
)

// For Codeforces
func main() {
	io := newStdIO()
	defer io.Flush()
	for T := io.ScanUInt16(); T > 0; T-- {
		solve(&io)
	}
}
func count(a []int32) int {
	c := 0
	tmp := 0
	for i := len(a) - 1; i >= 0; i-- {
		if a[i] == 0 {
			tmp++
		} else {
			c += tmp
		}
	}
	return c
}
func solve(io *IO) {
	n := io.ScanInt32()
	s := make([]int32, n)
	for i := int32(0); i < n; i++ {
		s[i] = io.ScanInt32()
	}

	a_c := 0
	for i := 0; i < len(s); i++ {
		if s[i] == 0 {
			for j := i + 1; j < len(s); j++ {
				if s[j] == 0 {
					a_c++
				}
			}
			for j := i - 1; j >= 0; j-- {
				if s[j] == 1 {
					a_c--
				}
			}
			break
		}
	}

	b_c := 0
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == 1 {
			for j := i - 1; j >= 0; j-- {
				if s[j] == 1 {
					b_c++
				}
			}
			for j := i + 1; j < len(s); j++ {
				if s[j] == 0 {
					b_c--
				}
			}
			break
		}
	}

	tmp := count(s)
	io.PrintLn(Max(tmp, Max(tmp+a_c, tmp+b_c)))
}

// #region INTERFACES

// From https://pkg.go.dev/golang.org/x/exp/constraints
type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
type Integer interface {
	Signed | Unsigned
}
type Float interface {
	~float32 | ~float64
}
type Complex interface {
	~complex64 | ~complex128
}
type Ordered interface {
	Integer | Float | ~string
}

type Prioritizable[T any] interface {
	PriorTo(x T) bool // If you take this as a relation: if (a,b) in R => (b,a) not in R
}

// #endregion
// #region TYPES WITH METHODS
// #region SingleLinkedList
type singleLinkedListNode[T comparable] struct {
	Value T
	Next  *singleLinkedListNode[T]
}

type SingleLinkedList[T comparable, IndexType Unsigned] struct {
	first  *singleLinkedListNode[T]
	last   *singleLinkedListNode[T]
	length IndexType
}

func NewSingleLinkedList[T comparable, IndexType Unsigned]() *SingleLinkedList[T, IndexType] {
	return &SingleLinkedList[T, IndexType]{
		first:  nil,
		last:   nil,
		length: 0,
	}
}
func (l *SingleLinkedList[T, I]) Len() I { return l.length }

// length > 0
func (l *SingleLinkedList[T, I]) First() T { return l.first.Value }

// length > 0
func (l *SingleLinkedList[T, I]) Last() T { return l.last.Value }

func (l *SingleLinkedList[T, I]) InsertFirst(value T) {
	if l.length == 0 {
		nodeToInsert := &singleLinkedListNode[T]{
			Value: value,
			Next:  l.first,
		}
		l.first = nodeToInsert
		l.last = nodeToInsert
	} else {
		l.first = &singleLinkedListNode[T]{
			Value: value,
			Next:  l.first,
		}
	}
	l.length++
}

func (l *SingleLinkedList[T, I]) InsertLast(value T) {
	if l.length == 0 {
		nodeToInsert := &singleLinkedListNode[T]{
			Value: value,
			Next:  l.first,
		}
		l.first = nodeToInsert
		l.last = nodeToInsert
	} else {
		l.last.Next = &singleLinkedListNode[T]{
			Value: value,
			Next:  nil,
		}
		l.last = l.last.Next
	}
	l.length++
}

// index <= length
func (l *SingleLinkedList[T, I]) InsertAt(index I, value T) {
	if index == 0 {
		l.InsertFirst(value)
		return
	}
	if index == l.length {
		l.InsertLast(value)
		return
	}

	n := l.first
	for index > 1 {
		n = n.Next
		index--
	}
	n.Next = &singleLinkedListNode[T]{
		Value: value,
		Next:  n.Next,
	}
	l.length++
}

func (l *SingleLinkedList[T, I]) Contains(value T) bool {
	tmp := l.first
	for i := I(0); i < l.length; i++ {
		if tmp.Value == value {
			return true
		}
		tmp = tmp.Next
	}
	return false
}
func (l *SingleLinkedList[T, I]) Clear() {
	l.first = nil
	l.last = nil
	l.length = 0
}

// index < length
func (l *SingleLinkedList[T, I]) GetElementAt(index I) T {
	n := l.first
	for index > 0 {
		n = n.Next
		index--
	}
	return n.Value
}

// index < length
func (l *SingleLinkedList[T, I]) SetElementAt(index I, value T) {
	n := l.first
	for index > 0 {
		n = n.Next
		index--
	}
	n.Value = value
}

func (l *SingleLinkedList[T, I]) RemoveFirst() T {
	tmp := l.first
	l.first = l.first.Next
	l.length--
	if l.length == 0 {
		l.last = nil
	}
	return tmp.Value
}
func (l *SingleLinkedList[T, I]) RemoveLast() (value T) {
	value = l.last.Value
	if l.length == 1 {
		l.first = nil
		l.last = nil
		l.length = 0
		return
	}

	tmp := l.first
	for i := I(2); i < l.length; i++ {
		tmp = tmp.Next
	}
	l.last = tmp
	return
}

func (l *SingleLinkedList[T, I]) RemoveAt(index I) T {
	if index == 0 {
		return l.RemoveFirst()
	}
	if index == l.length-1 {
		return l.RemoveLast()
	}

	tmp := l.first
	for i := I(1); i < index; i++ {
		tmp = tmp.Next
	}
	res := tmp.Next.Value
	tmp.Next = tmp.Next.Next
	return res
}

func (l *SingleLinkedList[T, I]) ToSlice() (res []T) {
	res = make([]T, 0, l.length)
	tmp := l.first
	for i := I(0); i < l.length; i++ {
		res = append(res, tmp.Value)
		tmp = tmp.Next
	}
	return
}
func (it *SingleLinkedList[T, I]) String() string {
	return "Qua:: " + fmt.Sprint(it.ToSlice())
}

// #endregion
// #region Queue

type Queue[T comparable, I Unsigned] struct {
	l SingleLinkedList[T, I]
}

func NewQueue[T comparable, I Unsigned]() *Queue[T, I] {
	return &Queue[T, I]{
		l: SingleLinkedList[T, I]{
			first:  nil,
			last:   nil,
			length: 0,
		},
	}
}
func (q *Queue[T, I]) Len() I          { return q.l.length }
func (q *Queue[T, I]) Enqueue(value T) { q.l.InsertLast(value) }
func (q *Queue[T, I]) Dequeue(T) T     { return q.l.RemoveFirst() }
func (q *Queue[T, I]) Preview() T      { return q.l.First() }
func (q *Queue[T, I]) String() string  { return q.l.String() }

// #endregion
// #region Stack

type Stack[T comparable, I Unsigned] struct {
	l SingleLinkedList[T, I]
}

func NewStack[T comparable, I Unsigned]() *Stack[T, I] {
	return &Stack[T, I]{
		l: SingleLinkedList[T, I]{
			first:  nil,
			last:   nil,
			length: 0,
		},
	}
}
func (s *Stack[T, I]) Len() I         { return s.l.length }
func (s *Stack[T, I]) Push(value T)   { s.l.InsertFirst(value) }
func (s *Stack[T, I]) Pop(T) T        { return s.l.RemoveFirst() }
func (s *Stack[T, I]) Preview() T     { return s.l.First() }
func (s *Stack[T, I]) String() string { return s.l.String() }

// #endregion
// #region Heap
type BinaryHeap[T Prioritizable[T], I Signed] struct {
	s []T
}

func NewBinaryHeap[T Prioritizable[T], I Signed](s []T) (h *BinaryHeap[T, I]) {
	h = &BinaryHeap[T, I]{
		s: s,
	}

	for i := (h.Len() - 2) / 2; i >= 0; i-- {
		h.heapifyDown(i)
	}
	return
}
func (h *BinaryHeap[T, I]) Len() I {
	return I(len(h.s))
}
func (h *BinaryHeap[T, I]) Push(value T) {
	h.s = append(h.s, value)
	h.heapifyUp(h.Len() - 1)
}
func (h *BinaryHeap[T, I]) Pop() (res T) {
	res = h.s[0]
	h.s[0] = h.s[h.Len()-1]
	h.s = h.s[:h.Len()-1]
	h.heapifyDown(0)
	return
}

func (h *BinaryHeap[T, I]) heapifyDown(index I) bool {
	origin := index
	for {
		j := index*2 + 2
		if j < h.Len() {
			if h.s[j-1].PriorTo(h.s[j]) {
				j--
			}
		} else {
			if j <= h.Len() && !h.s[j].PriorTo(h.s[index]) {
				h.s[j], h.s[index] = h.s[index], h.s[j]
			}
			break
		}
		if h.s[j].PriorTo(h.s[index]) {
			h.s[j], h.s[index] = h.s[index], h.s[j]
			index = j
		} else {
			break
		}
	}
	return origin != index
}
func (h *BinaryHeap[T, I]) heapifyUp(index I) {
	for {
		parent := (index - 1) / 2
		if parent == index || h.s[parent].PriorTo(h.s[index]) {
			break
		}
		h.s[index], h.s[parent] = h.s[parent], h.s[index]
		index = parent
	}
}

// #endregion

// #endregion

// #region FUNCTIONS
func Max[T Ordered](a, b T) T {
	if a >= b {
		return a
	}
	return b
}
func Min[T Ordered](a, b T) T {
	if a <= b {
		return a
	}
	return b
}
func Abs[T Integer | Float](a T) T {
	if a < 0 {
		return -a
	}
	return a
}
func Swap[T any](a, b *T) {
	*a, *b = *b, *a
}

// At least one != 0
func GCD[T Unsigned](a, b T) T {
	if b < a {
		Swap(&a, &b)
	}
	for {
		if a == 0 {
			return b
		}
		r := (b % a)
		b = a
		a = r
	}
}

// At least one != 0
func LCM[T Unsigned](a, b T) T {
	return (a * b) / GCD(a, b)
}

func First[T any](a T, _ any) T { return a }

// #endregion

// #region IO STUFF
type IO struct {
	r *bufio.Reader
	w *bufio.Writer
}

func newStdIO() IO {
	return IO{
		r: bufio.NewReader(os.Stdin),
		w: bufio.NewWriter(os.Stdout),
	}
}

// Is assumed that input.txt file exists
func newFileIO() IO {
	return IO{
		r: bufio.NewReader(First(os.Open("input.txt"))),
		w: bufio.NewWriter(First(os.OpenFile("output.txt", os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModePerm))),
	}
}

func (io *IO) ScanInt8() (x int8)   { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanInt16() (x int16) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanInt32() (x int32) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanInt64() (x int64) { fmt.Fscan(io.r, &x); return }

func (io *IO) ScanUInt8() (x uint8)   { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanUInt16() (x uint16) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanUInt32() (x uint32) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanUInt64() (x uint64) { fmt.Fscan(io.r, &x); return }

func (io *IO) ScanFloat32() (x float32) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanFloat64() (x float64) { fmt.Fscan(io.r, &x); return }

func (io *IO) ScanString() (x string) { fmt.Fscan(io.r, &x); return }

func (io *IO) Print(x ...any)   { fmt.Fprint(io.w, x...) }
func (io *IO) PrintLn(x ...any) { fmt.Fprintln(io.w, x...) }

func (io *IO) Flush() { io.w.Flush() }

// #endregion

// #region KEEP IMPORTS
func D() {
	_ = bufio.Reader{}
	_ = bytes.Buffer{}
	_ = suffixarray.Index{}
	_ = log.Default()
	_ = math.Abs(0)
	_ = net.Dialer{}
	_ = path.ErrBadPattern
	_ = sort.Float64sAreSorted(nil)
	_ = strconv.ErrRange
	_ = strings.Builder{}
	_ = time.ANSIC
	_ = newStdIO()
	_ = newFileIO()
}

// #endregion

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		pos := -1
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				pos = i
				arr[i] = 1
				break
			}
		}

		a := int64(0)

		if pos != -1 {
			a = fu(&arr, n)
			arr[pos] = 0
		}

		pos = -1
		for i := n - 1; i >= 0; i-- {
			if arr[i] == 1 {
				arr[i] = 0
				pos = i
				break
			}
		}

		b := int64(0)
		if pos != -1 {
			b = fu(&arr, n)
		}

		fmt.Println(int64(math.Max(float64(a), float64(b))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n)
	for i := n - 1; i >= 0; i-- {
		if i < n-1 {
			dp[i] = dp[i+1]
		}
		if (*arr)[i] == 0 {
			dp[i]++
		}

	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			c := dp[i]
			ans += int64(c)
		}
	}
	return ans
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		pos := -1
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				pos = i
				arr[i] = 1
				break
			}
		}

		a := fu(&arr, n)

		if pos != -1 {
			arr[pos] = 0
		}

		for i := n - 1; i >= 0; i-- {
			if arr[i] == 1 {
				arr[i] = 0
				break
			}
		}

		b := fu(&arr, n)

		fmt.Println(int64(math.Max(float64(a), float64(b))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n)
	for i := n - 1; i >= 0; i-- {
		if i < n-1 {
			dp[i] = dp[i+1]
		}
		if (*arr)[i] == 0 {
			dp[i]++
		}

	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			c := dp[i]
			ans += int64(c)
		}
	}
	return ans
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		pos := -1
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				pos = i
				arr[i] = 1
				break
			}
		}

		a := fu(&arr, n)

		if pos != -1 {
			arr[pos] = 0
		}

		for i := n - 1; i >= 0; i-- {
			if arr[i] == 1 {
				arr[i] = 0
				break
			}
		}

		b := fu(&arr, n)

		fmt.Println(int64(math.Max(float64(a), float64(b))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n+1)
	for i := 0; i < n; i++ {
		if i == 0 {
			if (*arr)[i] == 0 {
				dp[i+1] = 1
			}
		} else {
			dp[i+1] = dp[i]
			if (*arr)[i] == 0 {
				dp[i+1] += 1
			}
		}
	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			c := dp[n] - dp[i]
			ans += int64(c)
		}
	}
	return ans
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		pos := -1
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				pos = i
				arr[i] = 1
				break
			}
		}

		a := fu(&arr, n)

		if pos != -1 {
			arr[pos] = 0
		}

		for i := n - 1; i >= 0; i-- {
			if arr[i] == 1 {
				arr[i] = 0
				break
			}
		}

		b := fu(&arr, n)

		fmt.Println(int64(math.Max(float64(a), float64(b))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n+1)
	for i := 0; i < n; i++ {
		if i == 0 {
			if (*arr)[i] == 0 {
				dp[i] = 1
			}
		} else {
			dp[i] = dp[i-1]
			if (*arr)[i] == 0 {
				dp[i] += 1
			}
		}
	}
	dp[n] = dp[n-1]

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			c := dp[n] - dp[i]
			ans += int64(c)
		}
	}
	return ans
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		pos := -1
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				pos = i
				arr[i] = 1
				break
			}
		}

		a := fu(&arr, n)

		if pos != -1 {
			arr[pos] = 0
		}

		for i := n - 1; i >= 0; i-- {
			if arr[i] == 1 {
				arr[i] = 0
				break
			}
		}

		b := fu(&arr, n)

		fmt.Println(int64(math.Max(float64(a), float64(b))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n+1)
	for i := 0; i < n; i++ {
		if i == 0 {
			if (*arr)[i] == 0 {
				dp[i] = 1
			}
		} else {
			dp[i] = dp[i-1]
			if (*arr)[i] == 0 {
				dp[i] += 1
			}
		}
	}
	dp[n] = dp[n-1]
	fmt.Println(dp)

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			c := dp[n] - dp[i]
			ans += int64(c)
		}
	}
	return ans
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)

		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()
		}

		pos := -1
		for i := 0; i < n; i++ {
			if arr[i] == 0 {
				pos = i
				arr[i] = 1
				break
			}
		}

		a := fu(&arr, n)

		if pos != -1 {
			arr[pos] = 0
		}

		for i := n - 1; i >= 0; i-- {
			if arr[i] == 1 {
				arr[i] = 0
				break
			}
		}

		b := fu(&arr, n)

		fmt.Println(int64(math.Max(float64(a), float64(b))))

	}
}

func fu(arr *[]int, n int) int64 {
	dp := make([]int, n)
	for i := 0; i < n; i++ {
		if i == 0 {
			if (*arr)[i] == 0 {
				dp[i] = 1
			}
		} else {
			dp[i] = dp[i-1]
			if (*arr)[i] == 0 {
				dp[i] += 1
			}
		}
	}

	ans := int64(0)
	for i := 0; i < n; i++ {
		if (*arr)[i] == 1 {
			c := dp[n-1] - dp[i]
			ans += int64(c)
		}
	}
	return ans
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		dp := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()

		}

		ch := false
		if arr[0] == 0 {
			arr[0] = 1
			ch = true
		} else if arr[n-1] == 1 {
			arr[n-1] = 0
			ch = true

		}

		for i := 0; i < n && !ch; i++ {
			if arr[i] == 0 {
				arr[i] = 1
				ch = true
				break
			}
		}

		for i := 0; i < n; i++ {
			if i == 0 {
				if arr[i] == 0 {
					dp[i] = 1
				}
			} else {
				dp[i] = dp[i-1]
				if arr[i] == 0 {
					dp[i] += 1
				}
			}
		}

		ans := int64(0)
		for i := 0; i < n; i++ {
			if arr[i] == 1 {
				c := dp[n-1] - dp[i]
				ans += int64(c)
			}
		}
		fmt.Println(ans)

	}
}

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

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

package main

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

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

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

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

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

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

/**
Run solve the problem CF1760E
Date: 11/21/2022
User: wotan
URL: https://codeforces.com/problemset/problem/1760/E
Problem: CF1760E
**/
func (in *CF1760E) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		arr := make([]int, n)
		dp := make([]int, n)
		for i := 0; i < n; i++ {
			arr[i] = in.NextInt()

		}

		if arr[0] == 0 {
			arr[0] = 1
		} else if arr[n-1] == 1 {
			arr[n-1] = 0
		}

		for i := 0; i < n; i++ {
			if i == 0 {
				if arr[i] == 0 {
					dp[i] = 1
				}
			} else {
				dp[i] = dp[i-1]
				if arr[i] == 0 {
					dp[i] += 1
				}
			}
		}

		ans := int64(0)
		for i := 0; i < n; i++ {
			if arr[i] == 1 {
				c := dp[n-1] - dp[i]
				ans += int64(c)
			}
		}
		fmt.Println(ans)

	}
}

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

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

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"index/suffixarray"
	"log"
	"math"
	"net"
	"os"
	"path"
	"sort"
	"strconv"
	"strings"
	"time"
)

// For Codeforces
func main() {
	io := newStdIO()
	defer io.Flush()
	for T := io.ScanUInt16(); T > 0; T-- {
		solve(&io)
	}
}
func count(a []int32) int {
	c := 0
	for i, _ := range a {
		for j := i; j < len(a); j++ {
			if a[j] < a[i] {
				c++
			}
		}
	}
	return c
}
func solve(io *IO) {
	n := io.ScanInt32()
	s := make([]int32, n)
	for i := int32(0); i < n; i++ {
		s[i] = io.ScanInt32()
	}

	a_c := 0
	for i := 0; i < len(s); i++ {
		if s[i] == 0 {
			for j := i + 1; j < len(s); j++ {
				if s[j] == 0 {
					a_c++
				}
			}
			break
		}
	}

	b_c := 0
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == 1 {
			for j := i - 1; j >= 0; j-- {
				if s[j] == 1 {
					b_c++
				}
			}
			break
		}
	}

	tmp := count(s)
	io.PrintLn(Max(tmp, Max(tmp+a_c, tmp+b_c)))
}

// #region INTERFACES

// From https://pkg.go.dev/golang.org/x/exp/constraints
type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}
type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
type Integer interface {
	Signed | Unsigned
}
type Float interface {
	~float32 | ~float64
}
type Complex interface {
	~complex64 | ~complex128
}
type Ordered interface {
	Integer | Float | ~string
}

type Prioritizable[T any] interface {
	PriorTo(x T) bool // If you take this as a relation: if (a,b) in R => (b,a) not in R
}

// #endregion
// #region TYPES WITH METHODS
// #region SingleLinkedList
type singleLinkedListNode[T comparable] struct {
	Value T
	Next  *singleLinkedListNode[T]
}

type SingleLinkedList[T comparable, IndexType Unsigned] struct {
	first  *singleLinkedListNode[T]
	last   *singleLinkedListNode[T]
	length IndexType
}

func NewSingleLinkedList[T comparable, IndexType Unsigned]() *SingleLinkedList[T, IndexType] {
	return &SingleLinkedList[T, IndexType]{
		first:  nil,
		last:   nil,
		length: 0,
	}
}
func (l *SingleLinkedList[T, I]) Len() I { return l.length }

// length > 0
func (l *SingleLinkedList[T, I]) First() T { return l.first.Value }

// length > 0
func (l *SingleLinkedList[T, I]) Last() T { return l.last.Value }

func (l *SingleLinkedList[T, I]) InsertFirst(value T) {
	if l.length == 0 {
		nodeToInsert := &singleLinkedListNode[T]{
			Value: value,
			Next:  l.first,
		}
		l.first = nodeToInsert
		l.last = nodeToInsert
	} else {
		l.first = &singleLinkedListNode[T]{
			Value: value,
			Next:  l.first,
		}
	}
	l.length++
}

func (l *SingleLinkedList[T, I]) InsertLast(value T) {
	if l.length == 0 {
		nodeToInsert := &singleLinkedListNode[T]{
			Value: value,
			Next:  l.first,
		}
		l.first = nodeToInsert
		l.last = nodeToInsert
	} else {
		l.last.Next = &singleLinkedListNode[T]{
			Value: value,
			Next:  nil,
		}
		l.last = l.last.Next
	}
	l.length++
}

// index <= length
func (l *SingleLinkedList[T, I]) InsertAt(index I, value T) {
	if index == 0 {
		l.InsertFirst(value)
		return
	}
	if index == l.length {
		l.InsertLast(value)
		return
	}

	n := l.first
	for index > 1 {
		n = n.Next
		index--
	}
	n.Next = &singleLinkedListNode[T]{
		Value: value,
		Next:  n.Next,
	}
	l.length++
}

func (l *SingleLinkedList[T, I]) Contains(value T) bool {
	tmp := l.first
	for i := I(0); i < l.length; i++ {
		if tmp.Value == value {
			return true
		}
		tmp = tmp.Next
	}
	return false
}
func (l *SingleLinkedList[T, I]) Clear() {
	l.first = nil
	l.last = nil
	l.length = 0
}

// index < length
func (l *SingleLinkedList[T, I]) GetElementAt(index I) T {
	n := l.first
	for index > 0 {
		n = n.Next
		index--
	}
	return n.Value
}

// index < length
func (l *SingleLinkedList[T, I]) SetElementAt(index I, value T) {
	n := l.first
	for index > 0 {
		n = n.Next
		index--
	}
	n.Value = value
}

func (l *SingleLinkedList[T, I]) RemoveFirst() T {
	tmp := l.first
	l.first = l.first.Next
	l.length--
	if l.length == 0 {
		l.last = nil
	}
	return tmp.Value
}
func (l *SingleLinkedList[T, I]) RemoveLast() (value T) {
	value = l.last.Value
	if l.length == 1 {
		l.first = nil
		l.last = nil
		l.length = 0
		return
	}

	tmp := l.first
	for i := I(2); i < l.length; i++ {
		tmp = tmp.Next
	}
	l.last = tmp
	return
}

func (l *SingleLinkedList[T, I]) RemoveAt(index I) T {
	if index == 0 {
		return l.RemoveFirst()
	}
	if index == l.length-1 {
		return l.RemoveLast()
	}

	tmp := l.first
	for i := I(1); i < index; i++ {
		tmp = tmp.Next
	}
	res := tmp.Next.Value
	tmp.Next = tmp.Next.Next
	return res
}

func (l *SingleLinkedList[T, I]) ToSlice() (res []T) {
	res = make([]T, 0, l.length)
	tmp := l.first
	for i := I(0); i < l.length; i++ {
		res = append(res, tmp.Value)
		tmp = tmp.Next
	}
	return
}
func (it *SingleLinkedList[T, I]) String() string {
	return "Qua:: " + fmt.Sprint(it.ToSlice())
}

// #endregion
// #region Queue

type Queue[T comparable, I Unsigned] struct {
	l SingleLinkedList[T, I]
}

func NewQueue[T comparable, I Unsigned]() *Queue[T, I] {
	return &Queue[T, I]{
		l: SingleLinkedList[T, I]{
			first:  nil,
			last:   nil,
			length: 0,
		},
	}
}
func (q *Queue[T, I]) Len() I          { return q.l.length }
func (q *Queue[T, I]) Enqueue(value T) { q.l.InsertLast(value) }
func (q *Queue[T, I]) Dequeue(T) T     { return q.l.RemoveFirst() }
func (q *Queue[T, I]) Preview() T      { return q.l.First() }
func (q *Queue[T, I]) String() string  { return q.l.String() }

// #endregion
// #region Stack

type Stack[T comparable, I Unsigned] struct {
	l SingleLinkedList[T, I]
}

func NewStack[T comparable, I Unsigned]() *Stack[T, I] {
	return &Stack[T, I]{
		l: SingleLinkedList[T, I]{
			first:  nil,
			last:   nil,
			length: 0,
		},
	}
}
func (s *Stack[T, I]) Len() I         { return s.l.length }
func (s *Stack[T, I]) Push(value T)   { s.l.InsertFirst(value) }
func (s *Stack[T, I]) Pop(T) T        { return s.l.RemoveFirst() }
func (s *Stack[T, I]) Preview() T     { return s.l.First() }
func (s *Stack[T, I]) String() string { return s.l.String() }

// #endregion
// #region Heap
type BinaryHeap[T Prioritizable[T], I Signed] struct {
	s []T
}

func NewBinaryHeap[T Prioritizable[T], I Signed](s []T) (h *BinaryHeap[T, I]) {
	h = &BinaryHeap[T, I]{
		s: s,
	}

	for i := (h.Len() - 2) / 2; i >= 0; i-- {
		h.heapifyDown(i)
	}
	return
}
func (h *BinaryHeap[T, I]) Len() I {
	return I(len(h.s))
}
func (h *BinaryHeap[T, I]) Push(value T) {
	h.s = append(h.s, value)
	h.heapifyUp(h.Len() - 1)
}
func (h *BinaryHeap[T, I]) Pop() (res T) {
	res = h.s[0]
	h.s[0] = h.s[h.Len()-1]
	h.s = h.s[:h.Len()-1]
	h.heapifyDown(0)
	return
}

func (h *BinaryHeap[T, I]) heapifyDown(index I) bool {
	origin := index
	for {
		j := index*2 + 2
		if j < h.Len() {
			if h.s[j-1].PriorTo(h.s[j]) {
				j--
			}
		} else {
			if j <= h.Len() && !h.s[j].PriorTo(h.s[index]) {
				h.s[j], h.s[index] = h.s[index], h.s[j]
			}
			break
		}
		if h.s[j].PriorTo(h.s[index]) {
			h.s[j], h.s[index] = h.s[index], h.s[j]
			index = j
		} else {
			break
		}
	}
	return origin != index
}
func (h *BinaryHeap[T, I]) heapifyUp(index I) {
	for {
		parent := (index - 1) / 2
		if parent == index || h.s[parent].PriorTo(h.s[index]) {
			break
		}
		h.s[index], h.s[parent] = h.s[parent], h.s[index]
		index = parent
	}
}

// #endregion

// #endregion

// #region FUNCTIONS
func Max[T Ordered](a, b T) T {
	if a >= b {
		return a
	}
	return b
}
func Min[T Ordered](a, b T) T {
	if a <= b {
		return a
	}
	return b
}
func Abs[T Integer | Float](a T) T {
	if a < 0 {
		return -a
	}
	return a
}
func Swap[T any](a, b *T) {
	*a, *b = *b, *a
}

// At least one != 0
func GCD[T Unsigned](a, b T) T {
	if b < a {
		Swap(&a, &b)
	}
	for {
		if a == 0 {
			return b
		}
		r := (b % a)
		b = a
		a = r
	}
}

// At least one != 0
func LCM[T Unsigned](a, b T) T {
	return (a * b) / GCD(a, b)
}

func First[T any](a T, _ any) T { return a }

// #endregion

// #region IO STUFF
type IO struct {
	r *bufio.Reader
	w *bufio.Writer
}

func newStdIO() IO {
	return IO{
		r: bufio.NewReader(os.Stdin),
		w: bufio.NewWriter(os.Stdout),
	}
}

// Is assumed that input.txt file exists
func newFileIO() IO {
	return IO{
		r: bufio.NewReader(First(os.Open("input.txt"))),
		w: bufio.NewWriter(First(os.OpenFile("output.txt", os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModePerm))),
	}
}

func (io *IO) ScanInt8() (x int8)   { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanInt16() (x int16) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanInt32() (x int32) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanInt64() (x int64) { fmt.Fscan(io.r, &x); return }

func (io *IO) ScanUInt8() (x uint8)   { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanUInt16() (x uint16) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanUInt32() (x uint32) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanUInt64() (x uint64) { fmt.Fscan(io.r, &x); return }

func (io *IO) ScanFloat32() (x float32) { fmt.Fscan(io.r, &x); return }
func (io *IO) ScanFloat64() (x float64) { fmt.Fscan(io.r, &x); return }

func (io *IO) ScanString() (x string) { fmt.Fscan(io.r, &x); return }

func (io *IO) Print(x ...any)   { fmt.Fprint(io.w, x...) }
func (io *IO) PrintLn(x ...any) { fmt.Fprintln(io.w, x...) }

func (io *IO) Flush() { io.w.Flush() }

// #endregion

// #region KEEP IMPORTS
func D() {
	_ = bufio.Reader{}
	_ = bytes.Buffer{}
	_ = suffixarray.Index{}
	_ = log.Default()
	_ = math.Abs(0)
	_ = net.Dialer{}
	_ = path.ErrBadPattern
	_ = sort.Float64sAreSorted(nil)
	_ = strconv.ErrRange
	_ = strings.Builder{}
	_ = time.ANSIC
	_ = newStdIO()
	_ = newFileIO()
}

// #endregion

package main

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

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

func main() {
	defer writer.Flush()

	var T int
	fmt.Fscan(reader, &T)
	for ; T > 0; T-- {
		var n int
		fmt.Fscan(reader, &n)

		a := make([]int, n+1)
		pref := make([][]int, 2)

		pref[0] = make([]int, n+1)
		pref[1] = make([]int, n+1)

		var inv int64 = 0

		for i := 1; i <= n; i++ {
			fmt.Fscan(reader, &a[i])
			for j := 0; j < 2; j++ {
				val := 0
				if a[i] == j {
					val = 1
				}
				pref[j][i] = pref[j][i-1] + val
			}
			if a[i] == 0 {
				inv += int64(pref[1][i-1])
			}
		}

		var ans int64 = 0

		Max := func(lhs, rhs int64) int64 {
			if lhs > rhs {
				return lhs
			}
			return rhs
		}

		for i := 1; i <= n; i++ {
			if a[i] == 0 {
				ans = Max(ans, inv-int64(pref[1][i-1])+int64(pref[0][n])-int64(pref[0][i]))
			} else {
				ans = Max(ans, inv+int64(pref[1][i-1])-int64(pref[0][n])+int64(pref[0][i]))
			}
		}

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

package main

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

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

// source: _
func solve() {
	n, arr := _readArr()
	z, o := 0, n-1
	res := 0

	cz := 0
	for i := n - 1; i >= 0; i-- {
		if arr[i] == 0 {
			cz++
		} else {
			res += cz
		}
	}

	for z < n && arr[z] != 0 {
		z++
	}
	for o >= 0 && arr[o] != 1 {
		o--
	}

	co := n - cz

	sz := -z + cz - 1
	so := -(n - 1 - o) + co - 1
	if so > sz {
		_print(res + so)
	} else {
		_print(res + sz)
	}
}

func main() {
	defer out.Flush()
	var t int
	for fmt.Fscanln(in, &t); t > 0; t-- {
		solve()
	}
}

// ====
func _readInt() int {
	var x int
	fmt.Fscan(in, &x)
	return x
}
func _readStr() string {
	var x string
	fmt.Fscan(in, &x)
	return x
}
func _readArr(x ...int) (int, []int) {
	var n int
	if len(x) == 0 {
		fmt.Fscan(in, &n)
	} else {
		n = x[0]
	}
	var v = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &v[i])
	}
	return n, v
}
func _print(x ...any) {
	fmt.Fprintln(out, x...)
}
func _max(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] > x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _min(x ...int) int {
	mi := 0
	for i := 1; i < len(x); i++ {
		if x[i] < x[mi] {
			mi = i
		}
	}
	return x[mi]
}
func _sum(x ...int) int {
	res := 0
	for _, i := range x {
		res += i
	}
	return res
}
func _abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}
func _sortStr(x string) string {
	r := []rune(x)
	sort.Slice(r, func(i, j int) bool {
		return r[i] < r[j]
	})
	return string(r)
}
func _reverseInts(x []int) {
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
}
func _reverseStr(s string) string {
	x := []rune(s)
	n := len(x)
	for i := 0; i < n/2; i++ {
		x[i], x[n-1-i] = x[n-1-i], x[i]
	}
	return string(x)
}
func _makeMatrix(n, m int) [][]int {
	x := make([][]int, n)
	for i := range x {
		x[i] = make([]int, m)
	}
	return x
}


package main

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

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

	var a int
	var s string
	Fscan(in, &a, &s)
	n := len(s)
	cnt := map[int]int{0: 1}
	sum := make([]int, n+1)
	for i := 1; i <= n; i++ {
		sum[i] = sum[i-1] + int(s[i-1]-'0')
		cnt[sum[i]]++
	}

	ans := int64(0)
	if a == 0 {
		cnt0 := int64(0)
		for _, c := range cnt {
			if c > 1 {
				cnt0 += int64(c * (c - 1) / 2)
			}
		}
		for _, c := range cnt {
			if c > 1 {
				cc := int64(c * (c - 1) / 2)
				ans += 2 * cc * int64(n*(n+1)/2)
				ans -= cc * cnt0
			}
		}
		Fprint(out, ans)
		return
	}
	for d := 1; d*d <= a; d++ {
		if a%d != 0 {
			continue
		}
		cnt1 := int64(0)
		for k, c := range cnt {
			if c > 0 && k >= d {
				cnt1 += int64(c) * int64(cnt[k-d])
			}
		}
		d2 := a / d
		cnt2 := int64(0)
		for k, c := range cnt {
			if c > 0 && k >= d2 {
				cnt2 += int64(c) * int64(cnt[k-d2])
			}
		}
		if d*d == a {
			ans += cnt1 * cnt2
		} else {
			ans += 2 * cnt1 * cnt2
		}
	}
	Fprint(out, ans)
}

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

// http://codeforces.com/problemset/problem/364/A
// A. Matrix
// sum(i,j)*sum(k,l) == a megoldasainak a szama
// spec eseteket le kell kezelni:
// a == 0
// rte, tobbszor is

package main

import (
	"fmt"
)

func main() {
	var (
		a, ns, i, j, sum, maxi int32
		ans                    int64
		s                      string
		all, psum              []int32
	)

	fmt.Scan(&a)
	fmt.Scan(&s)

	//	fmt.Println(a)

	ns = int32(len(s))
	psum = make([]int32, ns+1, ns+1)
	psum[0] = 0
	sum = 0
	for i = 0; i < ns; i++ {
		sum += int32(s[i] - '0')
		psum[i+1] = sum
	}

	if sum*sum < a {
		goto OK
	}

	all =
		make([]int32, sum+1, sum+1)

	for i = 1; i <= ns; i++ {
		for j = i; j <= ns; j++ {
			all[psum[j]-psum[i-1]]++
		}
	}

	//all = all[:sum+1]
	//fmt.Println(sum, all)

	if a == 0 {
		ans = int64(all[0]) * int64((ns*(ns+1) - all[0]))
		goto OK
	}

	i = a / sum
	if a%sum > 0 {
		i++
	}
	if i == 0 {
		i = 1
	}
	maxi = sum
	if a < sum {
		maxi = a
	}
	for ; i <= maxi; i++ {
		//		fmt.Println("i,a/i,maxi sum", i, a/i, maxi, sum)

		if i*i >= a {
			break
		}
		if a%i == 0 {
			ans += 2 * int64(all[i]) * int64(all[a/i])
		}
	}

	if i*i == a {
		ans += int64(all[i]) * int64(all[i])
		//		println("*")

	}

OK:
	fmt.Println(ans)

}

package main

import "fmt"

func main() {
    var (
        a uint64
        inp string
    )
    fmt.Scan(&a)
    fmt.Scan(&inp)

    sums := buildSumTable(inp)

    cnt := uint64(0)

    if a == 0 {
        l := len(inp)
        s := sums[0]
        cnt = s*uint64(l*l+l) - s*s
    } else {
        for i:=uint64(1); i<=a && i<40000; i++ {
            if a%i == 0 && a/i < 40000 {
                cnt += sums[int(i)]*sums[int(a/i)]
            }
        }
    }
    fmt.Println(cnt)
}

func buildSumTable(inp string) []uint64 {
    sums := make([]uint64, 40000)
    for i:=0; i<len(inp); i++ {
        sum := 0
        for j:=i; j<len(inp); j++ {
            sum += int(inp[j]) - '0'
            sums[sum] += 1
        }
    }
    return sums
}

// http://codeforces.com/problemset/problem/364/A
// A. Matrix
// sum(i,j)*sum(k,l) == a megoldasainak a szama
// spec eseteket le kell kezelni:
// a == 0

package main

import (
	"fmt"
)

func main() {
	var (
		a, ns, ans, i, j, sum int32
		s                     string
		all, psum             []int32
	)

	fmt.Scan(&a)
	fmt.Scan(&s)

	ns = int32(len(s))
	psum = make([]int32, ns+1, ns+1)
	psum[0] = 0
	sum = 0
	for i = 0; i < ns; i++ {
		sum += int32(s[i] - '0')
		psum[i+1] = sum
	}

	if sum*sum < a {
		goto OK
	}

	all =
		make([]int32, sum+1, sum+1)

	for i = 1; i <= ns; i++ {
		for j = i; j <= ns; j++ {
			all[psum[j]-psum[i-1]]++
		}
	}

	all = all[:sum+1]

	//	fmt.Println(sum, all)

	if a == 0 {
		ans = all[0] * all[0]
		goto OK
	}

	for i = 1; i <= sum; i++ {
		if i*i >= a {
			break
		}
		if a%i == 0 {
			ans += 2 * all[i] * all[a/i]
		}
	}

	if i*i == a {
		ans += all[i] * all[i]
	}

OK:
	fmt.Println(ans)

}

// http://codeforces.com/problemset/problem/364/A
// A. Matrix
// sum(i,j)*sum(k,l) == a megoldasainak a szama
// spec eseteket le kell kezelni:
// a == 0
// rte, tobbszor is

package main

import (
	"fmt"
)

func main() {
	var (
		a, ns, ans, i, j, sum, maxi int32
		s                           string
		all, psum                   []int32
	)

	fmt.Scan(&a)
	fmt.Scan(&s)

	//	fmt.Println(a)

	ns = int32(len(s))
	psum = make([]int32, ns+1, ns+1)
	psum[0] = 0
	sum = 0
	for i = 0; i < ns; i++ {
		sum += int32(s[i] - '0')
		psum[i+1] = sum
	}

	if sum*sum < a {
		goto OK
	}

	all =
		make([]int32, sum+1, sum+1)

	for i = 1; i <= ns; i++ {
		for j = i; j <= ns; j++ {
			all[psum[j]-psum[i-1]]++
		}
	}

	//all = all[:sum+1]
	//fmt.Println(sum, all)

	if a == 0 {
		ans = all[0] * (ns*(ns+1) - all[0])
		goto OK
	}

	i = a / sum
	if a%sum > 0 {
		i++
	}
	if i == 0 {
		i = 1
	}
	maxi = sum
	if a < sum {
		maxi = a
	}
	for ; i <= maxi; i++ {
		//		fmt.Println("i,a/i,maxi sum", i, a/i, maxi, sum)

		if i*i >= a {
			break
		}
		if a%i == 0 {
			ans += 2 * all[i] * all[a/i]
		}
	}

	if i*i == a {
		ans += all[i] * all[i]
		//		println("*")

	}

OK:
	fmt.Println(ans)

}

package main

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

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

	var a int
	var s string
	Fscan(in, &a, &s)
	n := len(s)
	cnt := map[int]int{0: 1}
	sum := make([]int, n+1)
	for i := 1; i <= n; i++ {
		sum[i] = sum[i-1] + int(s[i-1]-'0')
		cnt[sum[i]]++
	}

	ans := int64(0)
	if a == 0 {
		groupCnt := int64(0)
		for _, c := range cnt {
			if c > 1 {
				groupCnt++
			}
		}
		for _, c := range cnt {
			if c > 1 {
				cc := int64(c * (c - 1) / 2)
				ans += 2 * cc * int64(n*(n+1)/2)
				ans -= groupCnt * cc * cc
			}
		}
		Fprint(out, ans)
		return
	}
	for d := 1; d*d <= a; d++ {
		if a%d != 0 {
			continue
		}
		cnt1 := int64(0)
		for k, c := range cnt {
			if c > 0 && k >= d {
				cnt1 += int64(c) * int64(cnt[k-d])
			}
		}
		d2 := a / d
		cnt2 := int64(0)
		for k, c := range cnt {
			if c > 0 && k >= d2 {
				cnt2 += int64(c) * int64(cnt[k-d2])
			}
		}
		if d*d == a {
			ans += cnt1 * cnt2
		} else {
			ans += 2 * cnt1 * cnt2
		}
	}
	Fprint(out, ans)
}

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

package main

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

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

	var a int
	var s string
	Fscan(in, &a, &s)
	n := len(s)
	cnt := map[int]int{0: 1}
	sum := make([]int, n+1)
	for i := 1; i <= n; i++ {
		sum[i] = sum[i-1] + int(s[i-1]-'0')
		cnt[sum[i]]++
	}

	ans := int64(0)
	if a == 0 {
		for _, c := range cnt {
			if c > 1 {
				cc := int64(c * (c - 1) / 2)
				ans += cc * cc
			}
		}
		Fprint(out, ans)
		return
	}
	for d := 1; d*d <= a; d++ {
		if a%d != 0 {
			continue
		}
		cnt1 := int64(0)
		for k, c := range cnt {
			if c > 0 && k >= d {
				cnt1 += int64(c) * int64(cnt[k-d])
			}
		}
		d2 := a / d
		cnt2 := int64(0)
		for k, c := range cnt {
			if c > 0 && k >= d2 {
				cnt2 += int64(c) * int64(cnt[k-d2])
			}
		}
		if d*d == a {
			ans += cnt1 * cnt2
		} else {
			ans += 2 * cnt1 * cnt2
		}
	}
	Fprint(out, ans)
}

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

package main

import "fmt"

func main() {
    var (
        a int
        inp string
    )
    fmt.Scanf("%d", &a)
    fmt.Scanf("%s", &inp)

    sums := buildSumTable(inp)

    cnt := 0
    for i:=1; i<=a; i++ {
        if a%i == 0 {
            cnt += sums[i]*sums[a/i]
        }
    }
    fmt.Println(cnt)
}

func buildSumTable(inp string) map[int]int {
    sums := make(map[int]int)
    for i:=0; i<len(inp); i++ {
        sum := 0
        for j:=i; j<len(inp); j++ {
            sum += int(inp[j]) - '0'
            sums[sum] += 1
        }
    }
    return sums
}

package main

import "fmt"

func main() {
    var (
        a uint64
        inp string
    )
    fmt.Scan(&a)
    fmt.Scan(&inp)

    sums := buildSumTable(inp)

    cnt := uint64(0)

    if a == 0 {
        l := len(inp)
        cnt = sums[0]*uint64(l*l+l-1)
    } else {
        for i:=uint64(1); i<=a && i<40000; i++ {
            if a%i == 0 && a/i < 40000 {
                cnt += sums[int(i)]*sums[int(a/i)]
            }
        }
    }
    fmt.Println(cnt)
}

func buildSumTable(inp string) []uint64 {
    sums := make([]uint64, 40000)
    for i:=0; i<len(inp); i++ {
        sum := 0
        for j:=i; j<len(inp); j++ {
            sum += int(inp[j]) - '0'
            sums[sum] += 1
        }
    }
    return sums
}

package main

import "fmt"

func main() {
    var (
        a uint64
        inp string
    )
    fmt.Scan(&a)
    fmt.Scan(&inp)

    sums := buildSumTable(inp)

    cnt := uint64(0)
    for i:=uint64(1); i<=a && i<40000; i++ {
        if a%i == 0 && a/i < 40000 {
            cnt += sums[int(i)]*sums[int(a/i)]
        }
    }
    fmt.Println(cnt)
}

func buildSumTable(inp string) []uint64 {
    sums := make([]uint64, 40000)
    for i:=0; i<len(inp); i++ {
        sum := 0
        for j:=i; j<len(inp); j++ {
            sum += int(inp[j]) - '0'
            sums[sum] += 1
        }
    }
    return sums
}


package main

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

func getInts() []int64 {
    //assumes POSITIVE INTEGERS. Check v for '-' if you have negative.
    var buf []byte
    buf, _ = ioutil.ReadAll(os.Stdin)
    var ints []int64
    num := int64(0)
    found := false
    for _, v := range buf {
        if '0' <= v && v <= '9' {
            num = 10*num + int64(v - '0') //could use bitshifting here.
            found = true
        } else if found {
            ints = append(ints, num)
            found = false
            num = 0
        }
    }
    if found {
        ints = append(ints, num)
        found = false
        num = 0
    }
    return ints
}

func putInts(a int){
   v:=a
   var t []byte
   for v>0{
       t=append(t, 0)
       copy(t[1:], t)
       t[0]=byte(int('0')+v%10)
       v/=10
   }
   t=append(t, byte(32))
   os.Stdout.Write(t)
}

var l, r, n int
var anext, aprev[300000]int
var a [300001]int
var x []byte

func main() {
	fmt.Scanf("%d\n", &n);
    aa:=getInts()
    for i:=1; i<=n; i++{
        a[i]=int(aa[i-1])
        anext[i]=i+1
        aprev[i]=i-1
    }
    l:=0
    coun:=n
    anext[0]=1
    for l<n+1{
        l++
        for ((aprev[l]!=0) && (a[l]==a[aprev[l]])){
            a[l]++
            aprev[l]=aprev[aprev[l]]
            anext[aprev[l]]=l
            coun--
        }
    }
    i:=anext[0]
    fmt.Printf("%d\n", coun);
    for i<n+1{
        v:=a[i]
        var t []byte
        for v>0{
           t=append(t, 0)
           copy(t[1:], t)
           t[0]=byte(int('0')+v%10)
           v/=10
        }
        t=append(t, byte(32))
        for j:=0; j<len(t); j++{
            x=append(x, t[j])
        }
        i=anext[i]
    }
    os.Stdout.Write(x)
}

package main

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

func main(){
	var n int
	var arr[200005] int
	var arr2[200005] int
	var ind int
	input := bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &n)
	for i := 0; i < n; i++ {
	fmt.Fscan(input, &arr[i])
	}
	ind = 0
	for i := 0; i < n; i++ {
	    arr2[ind] = arr[i]
	    ind++
	    for j := ind-1; j > 0; j-- {
	        if(arr2[j] == arr2[j-1]) {
	            arr2[j-1]++
	            ind--
	        } else {
	            break
	        }
	    }
	}
	var buf bytes.Buffer
	fmt.Fprint(&buf, ind)
	fmt.Fprint(&buf,"\n")
	for i := 0; i < ind; i++ {
	    fmt.Fprint(&buf,arr2[i]);
	    fmt.Fprint(&buf," ")
	}
	fmt.Println(buf.String())
}

package main

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

var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }

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

func main() {

	defer writer.Flush()

	var n int
	var a[200050] int
	var stk[] int

	scanf("%d\n",&n)
	for i:=1;i<=n;i++ {
	    scanf("%d",&a[i])
	    for len(stk)>0 && stk[len(stk)-1]==a[i] {
	        a[i]++
	        stk=stk[:len(stk)-1]
	    }
	    stk=append(stk,a[i])
	}

	printf("%d\n",len(stk))
	for i:=0;i<len(stk);i++ {
	    printf("%d ",stk[i])
	}
}

package main

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

func getInts() []int64 {
    //assumes POSITIVE INTEGERS. Check v for '-' if you have negative.
    var buf []byte
    buf, _ = ioutil.ReadAll(os.Stdin)
    var ints []int64
    num := int64(0)
    found := false
    for _, v := range buf {
        if '0' <= v && v <= '9' {
            num = 10*num + int64(v - '0') //could use bitshifting here.
            found = true
        } else if found {
            ints = append(ints, num)
            found = false
            num = 0
        }
    }
    if found {
        ints = append(ints, num)
        found = false
        num = 0
    }
    return ints
}

func putInts(a int){
   v:=a
   var t []byte
   for v>0{
       t=append(t, 0)
       copy(t[1:], t)
       t[0]=byte(int('0')+v%10)
       v/=10
   }
   t=append(t, byte(32))
   os.Stdout.Write(t)
}

var l, r, n int
var anext, aprev[300000]int
var a [300001]int
func main() {
	fmt.Scanf("%d\n", &n);
    aa:=getInts()
    for i:=1; i<=n; i++{
        a[i]=int(aa[i-1])
        anext[i]=i+1
        aprev[i]=i-1
    }
    l:=0
    coun:=n
    anext[0]=1
    for l<n+1{
        l++
        for ((aprev[l]!=0) && (a[l]==a[aprev[l]])){
            a[l]++
            aprev[l]=aprev[aprev[l]]
            anext[aprev[l]]=l
            coun--
        }
    }
    i:=anext[0]
    fmt.Printf("%d\n", coun);
    for i<n+1{
        putInts(a[i])
        i=anext[i]
    }
}

package main

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

func getInts() []int64 {
    //assumes POSITIVE INTEGERS. Check v for '-' if you have negative.
    var buf []byte
    buf, _ = ioutil.ReadAll(os.Stdin)
    var ints []int64
    num := int64(0)
    found := false
    for _, v := range buf {
        if '0' <= v && v <= '9' {
            num = 10*num + int64(v - '0') //could use bitshifting here.
            found = true
        } else if found {
            ints = append(ints, num)
            found = false
            num = 0
        }
    }
    if found {
        ints = append(ints, num)
        found = false
        num = 0
    }
    return ints
}

var l, r, n int
var anext, aprev[300000]int
var a [300001]int

func main() {
	fmt.Scanf("%d\n", &n);
    aa:=getInts()
    for i:=1; i<=n; i++{
        a[i]=int(aa[i-1])
        anext[i]=i+1
        aprev[i]=i-1
    }
    l:=0
    coun:=n
    anext[0]=1
    for l<n+1{
        l++
        for ((aprev[l]!=0) && (a[l]==a[aprev[l]])){
            a[l]++
            aprev[l]=aprev[aprev[l]]
            anext[aprev[l]]=l
            coun--
        }
    }
    i:=anext[0]
    fmt.Printf("%d\n", coun);
    for i<n+1{
        fmt.Printf("%d ", a[i])
        i=anext[i]
    }
}

package main

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

func solve() {
	n := readInt()
	arr := make([]int, n, n)
	for i := 0; i < n; i++ {
	    arr[i] = readInt()
	}
	l := make([]int, n, n)
 	for i:=0; i<n;i++{
	    l[i] = i-1;
	}

	ind:= 0;

	for ;ind<n;{
	   if(ind>0){
	        for;l[ind]!=-1&&arr[ind]==arr[l[ind]];{
	            arr[ind]++
	            l[ind]=l[l[ind]]
	        }
	   }
	   ind++;
	}
	ans := make([]int, n,n)
	for i:=0;i<n;i++{
	    ans[i]=-1;
	}
	ind = n-1
	flag:=0
	for ;ind>=0;{
	    ans[n-1-flag]=arr[ind]
	    ind = l[ind]
	    flag++
	}
	fmt.Println(flag);
	var buffer bytes.Buffer
	for i:=0;i<n;i++{
	    if(ans[i]>=0){
	       buffer.WriteString(strconv.Itoa(ans[i])+" ")
	    }

	}
	fmt.Println(buffer.String());

}

var scanner *bufio.Scanner

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

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

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

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

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

func main(){
  var n int
  input := bufio.NewReader(os.Stdin)
  fmt.Fscan(input, &n)
  var a[200005] int

  ptr := 0

  for i := 0; i < n; i++ {
    ptr++
    fmt.Fscan(input, &a[ptr])
    for j := 0; ptr >= 2 && a[ptr] == a[ptr-1]; j++ {
      ptr--
      a[ptr]++
    }

  }

  out := bufio.NewWriter(os.Stdout)

  out.WriteString(strconv.Itoa(ptr) + "\n")

  for i := 1; i <= ptr; i++ {

    out.WriteString(strconv.Itoa(a[i]) + "\n")

  }
  out.Flush()

}

package main

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

func solve() {
	n := readInt()
	arr := make([]int, n, n)
	for i := 0; i < n; i++ {
	    arr[i] = readInt()
	}
	l := make([]int, n, n)
 	for i:=0; i<n;i++{
	    l[i] = i-1;
	}

	ind:= 0;

	for ;ind<n;{
	   if(ind>0){
	        for;l[ind]!=-1&&arr[ind]==arr[l[ind]];{
	            arr[ind]++
	            l[ind]=l[l[ind]]
	        }
	   }
	   ind++;
	}
	ans := make([]int, n,n)
	for i:=0;i<n;i++{
	    ans[i]=-1;
	}
	ind = n-1
	flag:=0
	for ;ind>=0;{
	    ans[n-1-flag]=arr[ind]
	    ind = l[ind]
	    flag++
	}
	fmt.Println(flag);
	for i:=0;i<n;i++{
	    if(ans[i]>=0){
	        fmt.Print(strconv.Itoa(ans[i])+" ");
	    }

	}

}

var scanner *bufio.Scanner

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

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

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

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

package main

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

func main() {
    out := bufio.NewWriter(os.Stdout)
    var n int
    ints := getInts()
    n, ints = ints[0], ints[1:]
    ret := make([]int, n, n)
    ridx := 0
    for i := 0; i < n; i++ {
        for ridx > 0 && ret[ridx-1] == ints[i] {
            ints[i]++
            ridx--
        }
        ret[ridx] = ints[i]
        ridx += 1
    }

    out.WriteString(strconv.Itoa(ridx) + "\n")
    for i := 0; i < ridx; i++ {
        out.WriteString(strconv.Itoa(ret[i]) + "\n")
    }
    out.Flush()
}

func getInts() []int {
    var buf []byte
    buf, _ = ioutil.ReadAll(os.Stdin)
    var ints []int
    num := int(0)
    found := false
    for _, v := range buf {
        if '0' <= v && v <= '9' {
            num = 10*num + int(v - '0')
            found = true
        } else if found {
            ints = append(ints, num)
            found = false
            num = 0
        }
    }
    if found {
        ints = append(ints, num)
        found = false
        num = 0
    }
    return ints
}

package main

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

const N = 200100

func main() {
	var n, x, k int
	var q [N]int

	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &n)

	k = 0
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &x)

		q[k] = x
		k++

		for k > 1 && q[k-2] == q[k-1] {
			q[k-2]++
			k--
		}
	}

	out := bufio.NewWriter(os.Stdout)

	fmt.Fprintln(out, k)
	for i := 0; i < k; i++ {
		fmt.Fprintf(out, "%d ", q[i])
	}
	fmt.Fprint(out, "\n")
	out.Flush()
}

package main

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

const N = 200100

func main() {
	var n, x, k int
	var q [N]int

	in := bufio.NewReader(os.Stdin)
	fmt.Fscan(in, &n)

	k = 0
	for i := 0; i < n; i++ {
		fmt.Fscan(in, &x)

		q[k] = x
		k++

		for k > 1 && q[k-2] == q[k-1] {
			q[k-2]++
			k--
		}
	}

	fmt.Println(k)
	for i := 0; i < k; i++ {
		fmt.Printf("%d ", q[i])
	}
	fmt.Print("\n")
}

package main

import (
        "fmt"
        )

var a [300000]int
var l, r, n int
var anext, aprev[300000]int

func main() {
	fmt.Scanf("%d\n", &n);
    for i:=1; i<=n; i++{
        fmt.Scanf("%d", &a[i]);
        anext[i]=i+1
        aprev[i]=i-1
    }
    l:=0
    coun:=n
    anext[0]=1
    for l<n+1{
        l++
        for ((aprev[l]!=0) && (a[l]==a[aprev[l]])){
            a[l]++
            aprev[l]=aprev[aprev[l]]
            anext[aprev[l]]=l
            coun--
        }
    }
    i:=anext[0]
    for i<n+1{
        fmt.Printf("%d ", a[i])
        i=anext[i]
    }
}


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

package main

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

var (
	t int

	n, k int
	C    []int
)

func main() {
	defer stdout.Flush()

	t = readi()
	for tc := 0; tc < t; tc++ {
		n, k = readi2()
		C = readis(n)

		solve()
	}
}

func solve() {
	ans := INF_B30

	for c := 1; c <= 100; c++ {
		// A := make([]int, len(C))
		// copy(A, C)

		res := 0

		i := 0
		for i < n {
			if C[i] == c {
				i++
				continue
			}

			// k個塗りつぶす
			res++
			i += k
		}

		chmin(&ans, res)
	}

	printf("%d\n", ans)
}

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

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

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

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

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

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

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

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

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

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

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

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

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

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

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

func newReadString(ior io.Reader, sf bufio.SplitFunc) func() string {
	r := bufio.NewScanner(ior)
	r.Buffer(make([]byte, 1024), int(1e+9)) // for Codeforces
	r.Split(sf)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return string(res)
}

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

	for i := 0; i < len(A); i++ {
		str := strconv.FormatInt(A[i], 10) // 64bit int version
		res = append(res, []rune(str)...)

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

	return string(res)
}

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

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

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

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

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

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

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

	return res
}

package main

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

func main() {
	defer _w.Flush()
	t := ReadInt()
	for i := 0; i < t; i++ {
		n, k := ReadInt(), ReadInt()
		c := ReadInts(n)
		println(solve(n, k, c))
	}
}

const Inf = 1 << 29

func solve(n, k int, c []int) int {
	ans := Inf
	for t := 1; t <= 100; t++ {
		i := 0
		cnt := 0
		for i < n {
			if c[i] != t {
				cnt++
				i += k
			} else {
				i++
			}
		}
		ans = Min(ans, cnt)
	}
	return ans
}

func Min(xs ...int) int {
	min := xs[0]
	for _, x := range xs[1:] {
		if min > x {
			min = x
		}
	}
	return min
}

var _r, _w = bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)

func print(a ...interface{})            { fmt.Fprint(_w, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(_w, f, a...) }
func println(a ...interface{})          { fmt.Fprintln(_w, a...) }
func printInts(a ...int)                { s := fmt.Sprint(a); println(s[1 : len(s)-1]) }
func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(_r, a...); err != nil {
		panic(err)
	}
}
func ReadString() (s string) { Scan(&s); return }
func ReadInt() (i int)       { Scan(&i); return }
func ReadInts(n int) (a []int) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt())
	}
	return
}
func ReadInt64() (i int64) { Scan(&i); return }
func ReadInt64s(n int) (a []int64) {
	for i := 0; i < n; i++ {
		a = append(a, ReadInt64())
	}
	return
}

package main

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

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

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

	for ; t > 0; t-- {
		fmt.Fscan(in, &n, &k)
		c := make([]int, n)
		colorMap := make([]int, 100)
		colorResult := make([]int, 100)
		for i := 0; i < n; i++ {
			fmt.Fscan(in, &c[i])
			c[i]--
			colorMap[c[i]]++
		}
		for color := range colorMap {
			if colorMap[color] == 0 {
				continue
			}
			for i := 0; i < n; {
				if c[i] == color {
					i++
				} else {
					i += k
					colorResult[color]++
				}
			}
		}

		sort.Ints(colorResult)
		min := colorResult[99]
		for i := range colorResult {
			if colorResult[i] != 0 && colorResult[i] < min {
				min = colorResult[i]
			}
		}
		fmt.Println(min)
	}
}


package main

import "fmt"

func main() {
	var t, n int
	var s string

	fmt.Scanln(&t)
	for ; t > 0; t-- {
		fmt.Scanln(&n)
		fmt.Scanln(&s)

		r := 0
		for i := 0; i < n-1; i++ {
			if s[i] > '0' {
				r += int(s[i]-'0') + 1
			}
		}
		r += int(s[n-1] - '0')
		fmt.Println(r)
	}
	return
}

package main

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

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

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

func main() {
	var t int
	scanf("%d\n", &t)
	s := make([]byte, 103)
	for ; t > 0; t-- {
		var n int
		scanf("%d\n", &n)
		scanf("%s\n", &s)

		ans := 0
		for i := n - 1; i >= 0; i-- {
			d := int(s[i] - '0')
			if d != 0 {
				if i != n-1 {
					ans++
				}
				ans += d
			}
		}
		printf("%d\n", ans)
	}
	writer.Flush()
}

package main
import (
	"fmt"
	"bufio"
	"os"
)
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }
func scanf(f string, a ...interface{}) { fmt.Fscanf(reader, f, a...) }
func main(){
	defer writer.Flush()
	var t int
	scanf("%d\n",&t)

	for t>0{
		var (
			n,ans int
		)

		scanf("%d\n",&n)
		var s string
		scanf("%s\n",&s)

		for i:=0;i<len(s)-1;i++{
			if s[i]!=48{
				ans+=int(s[i])-48+1
			}
		}
		if s[len(s)-1]!=48{
			ans+=int(s[len(s)-1])-48
		}
		printf("%d\n",ans)

		t--
	}

}

package main

import "fmt"

func main() {
	var t int
	fmt.Scan(&t)
	var n, ops int
	var s string
	for ; t > 0; t-- {
		fmt.Scan(&n, &s)
		ops = 0
		for index, c := range s {
			ops += int(c - 48)
			if c != '0' && index != n-1 {
				ops++
			}
		}

		fmt.Println(ops)
	}
}

package main

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

type Scanner struct {
	*bufio.Scanner
}

func NewWordScanner(reader io.Reader) *Scanner {
	scanner := bufio.NewScanner(reader)
	scanner.Split(bufio.ScanWords)
	return &Scanner{scanner}
}

func (s *Scanner) Word() string {
	s.Scan()
	return s.Text()
}

func (s *Scanner) Int() int {
	s.Scan()
	n, _ := strconv.Atoi(s.Text())
	return n
}

func (s *Scanner) Int64() int64 {
	s.Scan()
	n, _ := strconv.ParseInt(s.Text(), 10, 64)
	return n
}

func (s *Scanner) Words(count int) []string {
	words := make([]string, count)
	for i := range words {
		words[i] = s.Word()
	}
	return words
}

func (s *Scanner) Ints(count int) []int {
	ints := make([]int, count)
	for i := range ints {
		ints[i] = s.Int()
	}
	return ints
}

func (s *Scanner) Int64s(count int) []int64 {
	int64s := make([]int64, count)
	for i := range int64s {
		int64s[i] = s.Int64()
	}
	return int64s
}

func solve(s []byte) int64 {
	res := int64(0)
	for _, ch := range s {
		digit := int64(ch - '0')
		if digit > 0 {
			res += digit + 1
		}
	}
	if s[len(s)-1] != '0' {
		res--
	}
	return res
}

func main() {
	stdin := NewWordScanner(os.Stdin)
	tests := stdin.Int()

	for i := 0; i < tests; i++ {
		_, s := stdin.Int(), []byte(stdin.Word())
		fmt.Println(solve(s))
	}
}

package main

import "fmt"

func solve() int {

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

	count := 0

	var s string
	fmt.Scanf("%s\n", &s)

	for _, ch := range s {
		if ch != '0' {
			var x int = int(ch) - '0'
			count += x + 1
		}
	}

	if s[n-1] != '0' {
		count--
	}

	return count
}

func main() {

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

	for t>0 {
		count := solve()
		fmt.Println(count)
		t--
	}
}

package main

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

func main() {
	var t int64
	r := bufio.NewReader(os.Stdin)
	fmt.Fscan(r, &t)
	for i := int64(0); i < t; i++ {
		var dNum int64
		var str string
		fmt.Fscan(r,&dNum)
		fmt.Fscan(r,&str)
		res:=int64(str[len(str)-1]-'0')
		for j:=int64(len(str))-2;j>=0;j--{
			if str[j]!='0'{
				res+=int64(str[j]-'0'+1)
				//fmt.Println(j, str[j], str[j]-'0', str[j]-'0'+1, res)
			}
		}
		fmt.Println(res)
	}
}

/* Author: likely
 * Time: 2021-09-22 22:27:45
**/
package main

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

func main(){
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	var t,n,i,ii,su int
	var sr string
	fmt.Fscan(in,&t);
	for ii=1;ii<=t;ii++{
		fmt.Fscan(in,&n)
		fmt.Fscan(in,&sr)
		su=0
		for i=0;i<=n-1;i++{
			if sr[i]!='0'{
				su+=(int)(sr[i])-(int)('0')
				if i!=n-1{
					su++
				}
			}
		}
		fmt.Fprintln(out,su)
	}
}

package main
import(
    "fmt"
    "bufio"
    "os"
    "strconv"
)
func main() {
	in:= bufio.NewReader(os.Stdin)
	out:= bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in,&t)
	for i:=0;i<t;i++{
		var n int
		fmt.Fscan(in,&n)
		var word string
		fmt.Fscan(in,&word)
		list:= make([]int,n)
		tally:=0
		if string(word[n-1]) == "0" {
			tally=0
		} else {
			tally=-1
		}
		for j:=0;j<n;j++{
			x,_:=strconv.Atoi(string(word[j]))
			if x == 0 {
				x=10
			}
			list[j]=x
			if x != 10 {
				tally+=(x+1)
			}
		}
		fmt.Fprintln(out,tally)
	}
}

package main

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

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

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

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

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

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

/**
Run solve the problem CF1573A
Date: 30/01/22
User: pepradere
URL: https://codeforces.com/problemset/problem/1573/A
Problem: CF1573A
**/
func (in *CF1573A) Run() {
	for t := in.NextInt(); t > 0; t-- {
		n := in.NextInt()
		str := in.NextString()
		ans := 0
		for i := 0; i < n; i++ {
			if str[i]-'0' > 0 {
				ans += int(str[i] - '0')
				if i+1 < n {
					ans++
				}
			}
		}
		fmt.Println(ans)
	}
}

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

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

package main

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

func solve() {
	f := bufio.NewReader(os.Stdin)
	w := bufio.NewWriter(os.Stdout)
	N, n, s := 0, 0, ""
	fmt.Fscan(f, &N)
	for i := 0; i < N; i++ {
		fmt.Fscan(f, &n, &s)
		swap, tot := int64(0), int64(0)
		for j := 0; j < n; j++ {
			p, _ := strconv.Atoi(string(s[j]))
			if p > 0 {
				tot, swap = tot+int64(p), swap+1
				if j == n-1 {
					swap--
				}
			}
		}
		fmt.Fprintln(w, tot+swap)
	}
	w.Flush()
}

func main() {
	solve()
}

package main

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

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

func main() {
	fmt.Fscan(reader, &t)
	for ; t > 0; t-- {
		fmt.Fscan(reader, &n)
		fmt.Fscan(reader, &s)
		var r int
		for i := range s {
			if s[i] != '0' {
				r += int(s[i] - '0')
				if i != n-1 {
					r++
				}
			}
		}
		fmt.Println(r)
	}
}

package main

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

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

	t := 0
	fmt.Fscanln(in, &t)
	for tcNo := 1; tcNo <= t; tcNo++ {
		n := 0
		fmt.Fscanln(in, &n)

		s := ""
		fmt.Fscanln(in, &s)

		ops := 0
		for i, r := range s {
			if r == '0' {
				continue
			}
			ops = ops + int(r-'0')
			if i < len(s)-1 {
				ops++
			}
		}
		fmt.Fprintln(out, ops)
	}
}

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

// template for codeforces problems in format:
// input:
// - number of tests (gotNumberOfTests = true!) - optional
// - tests: one or more lines per test (inputLinesPerTest)
//          with one or more integers on each line, separated by intSeparator
// output:
// - one line per solution, with one or more integers
package main

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

var numTests int // number of tests

const (
	gotNumberOfTests  bool = true // first line holds number of tests
	inputLinesPerTest      = 2
	intSeparator           = " "
)

func getInts(s string) (out []int, err error) {
	for _, a := range strings.Split(s, intSeparator) {
		var i int
		i, err = strconv.Atoi(a)
		if err != nil {
			break
		}
		out = append(out, i)
	}
	return
}

func getDigit(b rune) (int, error) {
	return strconv.Atoi(string(b))
}

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

	if gotNumberOfTests {
		s.Scan()
		if i, err := getInts(s.Text()); len(i) != 1 || err != nil {
			fmt.Println("can't process first line")
			return
		} else {
			numTests = i[0]
		}
	}

	for t := 0; ; t++ {
		// process 1 input (one or more lines)
		in := []string{}
		i := 0
		for ; i < inputLinesPerTest && s.Scan(); i++ {
			in = append(in, s.Text())
		}
		if i != inputLinesPerTest {
			// Scan() failed, probably EOF - add check?
			break
		}

		// print output, go routine?
		if len(in) != inputLinesPerTest {
			panic(fmt.Sprintf("expected %d lines per input, got %d", inputLinesPerTest, len(in)))
		}
		for _, o := range solution(in) {
			fmt.Println(o)
		}
	}
}

func solution(in []string) (out []string) {
	s := in[1]

	i := 0
	for _, b := range s[:len(s)-1] {
		if b != '0' {
			i++
		}
	}
	for _, b := range s {
		d, _ := getDigit(b)
		i += d
	}

	out = append(out, fmt.Sprintf("%d", i))

	return
}

package main

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

func main() {
	var t int64
	r := bufio.NewReader(os.Stdin)
	fmt.Fscan(r, &t)
	for i := int64(0); i < t; i++ {
		var dNum int64
		var str string
		fmt.Fscan(r,&dNum)
		fmt.Fscan(r,&str)
		res:=str[len(str)-1]-'0'
		for j:=int64(len(str))-2;j>=0;j--{
			if str[j]!='0'{
				res+=str[j]-'0'+1
			}
		}
		if t < 1000 {
			fmt.Println(res)
		}
		if i > 900 {
			fmt.Println(str)
		}
		//fmt.Println(res)
	}
}

package main

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

func main() {
	var t int64
	r := bufio.NewReader(os.Stdin)
	fmt.Fscan(r, &t)
	for i := int64(0); i < t; i++ {
		var dNum int64
		var str string
		fmt.Fscan(r,&dNum)
		fmt.Fscan(r,&str)
		res:=str[len(str)-1]-'0'
		for j:=int64(len(str))-2;j>=0;j--{
			if str[j]!='0'{
				res+=str[j]-'0'+1
			}
		}
		fmt.Println(res)
	}
}

package main

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

func main() {
	var t int64
	r := bufio.NewReader(os.Stdin)
	fmt.Fscan(r, &t)
	for i := int64(0); i < t; i++ {
		var dNum int64
		var str string
		fmt.Fscan(r,&dNum)
		fmt.Fscan(r,&str)
		digit:=str[len(str)-1]-'0'
		for j:=int64(len(str))-2;j>=0;j--{
			if str[j]!='0'{
				digit+=str[j]-'0'+1
			}
		}
		fmt.Println(digit)
	}
}