You are given a binary array$$$^{\dagger}$$$ of length $$$n$$$. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a $$$0$$$ into a $$$1$$$ or vice-versa.What is the maximum number of inversions$$$^{\ddagger}$$$ the array can have after performing at most one operation?$$$^\dagger$$$ A binary array is an array that contains only zeroes and ones.$$$^\ddagger$$$ The number of inversions in an array is the number of pairs of indices $$$i,j$$$ such that $$$i<j$$$ and $$$a_i > a_j$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$a_1$$$, $$$a_2$$$,..., $$$a_n$$$ ($$$0 \leq a_i \leq 1$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output a single integer  — the maximum number of inversions the array can have after performing at most one operation.

NoteFor the first test case, the inversions are initially formed by the pairs of indices ($$$1, 2$$$), ($$$1, 4$$$), ($$$3, 4$$$), being a total of $$$3$$$, which already is the maximum possible.For the second test case, the inversions are initially formed by the pairs of indices ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$), being a total of four. But, by flipping the first element, the array becomes $$${1, 1, 0, 0, 1, 0}$$$, which has the inversions formed by the pairs of indices ($$$1, 3$$$), ($$$1, 4$$$), ($$$1, 6$$$), ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$) which total to $$$7$$$ inversions which is the maximum possible.

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"
	"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)

		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
}


You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j) such that x ≤ i ≤ y, z ≤ j ≤ t.

The first line contains integer a (0 ≤ a ≤ 109), the second line contains a string of decimal integers s (1 ≤ |s| ≤ 4000).

Print a single integer — the answer to a problem. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

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
}


Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|.In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5, 1, 3, 2, 4] and the array b is [3, 3, 2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2, 1, 3, 2, 4] and the new array b [3, 3, 5].Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.

The first line contains integer n (1 ≤ n ≤ 2000) — the number of elements in the array a. The second line contains n integers ai ( - 109 ≤ ai ≤ 109) — the elements of the array a. The third line contains integer m (1 ≤ m ≤ 2000) — the number of elements in the array b. The fourth line contains m integers bj ( - 109 ≤ bj ≤ 109) — the elements of the array b.

In the first line print the minimal value v = |sa - sb| that can be got with no more than two swaps. The second line should contain the number of swaps k (0 ≤ k ≤ 2). Each of the next k lines should contain two integers xp, yp (1 ≤ xp ≤ n, 1 ≤ yp ≤ m) — the index of the element in the array a and the index of the element in the array b in the p-th swap. If there are several optimal solutions print any of them. Print the swaps in order the professor did them.

package main

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

type intPair struct {
    first int
    second int
}

func abs64(x int64) int64 {
    switch {
    case x < 0:
        return -x
    case x == 0:
        return 0 // return correctly abs(-0)
    }
    return x
}

var z map[int64]intPair

type i64Array []int64

func (q i64Array) Len() int {
    return len(q)
}

func (q i64Array) Swap(i, j int) {
    q[i], q[j] = q[j], q[i]
}

func (q i64Array) Less(i, j int) bool {
    if q[i] < q[j] {
        return true
    } else {
        return false
    }
}

//array zk should be sorted
func findNearestKey(zk i64Array, val *int64) int64 {
    n := len(zk)
    //fmt.Printf("%v\n", zk)
    if n == 1 {
        return zk[0]
    }
    if n == 2 {
        if abs64(zk[0] - *val) > abs64(zk[1] - *val) {
            return zk[1]
        } else {
            return zk[0]
        }
    }
    i := len(zk)/2
    if zk[i] == *val {
        return zk[i]
    } else if zk[i] > *val {
        return findNearestKey(zk[0:i+1], val)
    } else {
        return findNearestKey(zk[i:len(zk)], val)
    }
}

//array zk should be sorted
func getKeyTriplet(zk i64Array, keyValue int64) (int64, int64, int64) {
    var currentIndex int = len(zk)/2
    var delta int = len(zk)/4

    //fmt.Printf("zk = %v\n", zk)
    //fmt.Printf("cIndex = %v\n", currentIndex)
    //fmt.Printf("delta = %v\n", delta)

    if len(zk) == 1 {
        return zk[0], zk[0], zk[0]
    } else if len(zk) == 2 {
        return zk[0], zk[0], zk[1]
    } else if len(zk) == 3 {
        return zk[0], zk[1], zk[2]
    }
    for true {
        if zk[currentIndex] == keyValue {
            if currentIndex == 0 {
                return zk[0], zk[0], zk[1]
            } else if currentIndex == (len(zk) - 1) {
                return zk[len(zk) - 2], zk[len(zk) - 1], zk[len(zk) - 1]
            } else {
                return zk[currentIndex-1], zk[currentIndex], zk[currentIndex+1]
            }
        } else if zk[currentIndex] > keyValue {
            currentIndex -= delta
            if delta >= 2 {
                delta = delta/2
            } else {
                delta = 1
            }
        } else {
            currentIndex += delta
            if delta >= 2 {
                delta = delta/2
            } else {
                delta = 1
            }
        }
    }
    return zk[0], zk[0], zk[1] //only to persuade the compiler
}

func main() {
    stin := bufio.NewScanner(os.Stdin)
    stin.Scan()
    n,_ := strconv.Atoi(stin.Text())
    stin.Scan()
    as := strings.Fields(stin.Text())
    var a [2000]int
    for i := 0; i < n; i++ {
        a[i],_ = strconv.Atoi(as[i])
    }
    stin.Scan()
    m,_ := strconv.Atoi(stin.Text())
    stin.Scan()
    bs := strings.Fields(stin.Text())
    var b [2000]int
    for i := 0; i < m; i++ {
        b[i],_ = strconv.Atoi(bs[i])
    }

    var sumA, sumB int64 = 0, 0
    for i := 0; i < n; i++ {
        sumA += int64(a[i])
    }
    for i := 0; i < m; i++ {
        sumB += int64(b[i])
    }

    var ansp []intPair

    ansv := abs64(sumA - sumB)
    curv := ansv

    //check 1
    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            sumA += int64(b[j] - a[i])
            sumB += int64(a[i] - b[j])
            curv = abs64(sumA - sumB)
            if ansv > curv {
                ansv = curv
                ansp = ansp[:0]  //clear ansp
                ansp = append(ansp, intPair{first:i, second:j})
            }
            sumA -= int64(b[j] - a[i])
            sumB -= int64(a[i] - b[j])
        }
    }

    //check 2
    z = make(map[int64]intPair)
    for j := 0; j < n; j++{
        for i := 0; i < j; i++ {
            z[int64(2) * int64(a[i] + a[j])] = intPair{first: i, second: j}
        }
    }
    //fmt.Printf("z = %v\n", z)
    if len(z) > 0 {
        var zKeys i64Array
        for k := range z {
            zKeys = append(zKeys, k)
        }
        sort.Sort(zKeys)

        for j := 0; j < m; j++ {
            for i := 0; i < j; i++ {
                val := sumA - sumB + int64(2) * int64(b[i] + b[j])
                //fmt.Printf("search for best key in %v\n", zKeys)
                bestKey := findNearestKey(zKeys, &val)
                //fmt.Printf("bestKey = %v\n", bestKey)
                //check several keys near the best one
                var kk [3]int64
                kk[0], kk[1], kk[2] = getKeyTriplet(zKeys, bestKey)
                //fmt.Printf("bestKeys = %v\n", kk)
                for qq := 0; qq < 3; qq++ {
                    curv := abs64(val - kk[qq])
                    p := z[kk[qq]]
                    if ansv > curv {
                        ansv = curv
                        ansp = ansp[:0]  //clear ansp
                        ansp = append(ansp, intPair{first:p.first, second:i})
                        ansp = append(ansp, intPair{first:p.second, second:j})
                    }
                }
            }
        }
    }
    fmt.Printf("%d\n", ansv)
    fmt.Printf("%d\n", len(ansp))
    for i := 0; i < len(ansp); i++ {
        fmt.Printf("%d %d\n", ansp[i].first + 1, ansp[i].second + 1)
    }
}

package main

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

type intPair struct {
    first int
    second int
}

func abs64(x int64) int64 {
    switch {
    case x < 0:
        return -x
    case x == 0:
        return 0 // return correctly abs(-0)
    }
    return x
}

var z map[int64]intPair

type i64Array []int64

func (q i64Array) Len() int {
    return len(q)
}

func (q i64Array) Swap(i, j int) {
    q[i], q[j] = q[j], q[i]
}

func (q i64Array) Less(i, j int) bool {
    if q[i] < q[j] {
        return true
    } else {
        return false
    }
}

//array zk should be sorted
func findNearestKey(zk i64Array, val *int64) int64 {
    n := len(zk)
    fmt.Printf("%v\n", zk)
    if n == 1 {
        return zk[0]
    }
    if n == 2 {
        if abs64(zk[0] - *val) > abs64(zk[1] - *val) {
            return zk[1]
        } else {
            return zk[0]
        }
    }
    i := len(zk)/2
    if zk[i] == *val {
        return zk[i]
    } else if zk[i] > *val {
        return findNearestKey(zk[0:i+1], val)
    } else {
        return findNearestKey(zk[i:len(zk)], val)
    }
}

//array zk should be sorted
func getKeyTriplet(zk i64Array, keyValue int64) (int64, int64, int64) {
    var currentIndex int = len(zk)/2
    var delta int = len(zk)/4
    for true {
        if zk[currentIndex] == keyValue {
            if currentIndex == 0 {
                return zk[0], zk[0], zk[1]
            } else if currentIndex == (len(zk) - 1) {
                return zk[len(zk) - 2], zk[len(zk) - 1], zk[len(zk) - 1]
            } else {
                return zk[currentIndex-1], zk[currentIndex], zk[currentIndex+1]
            }
        } else if zk[currentIndex] > keyValue {
            currentIndex -= delta
            if delta >= 2 {
                delta = delta/2
            } else {
                delta = 1
            }
        } else {
            currentIndex += delta
            if delta >= 2 {
                delta = delta/2
            } else {
                delta = 1
            }
        }
    }
    return zk[0], zk[0], zk[1] //only to persuade the compiler
}

func main() {
    stin := bufio.NewScanner(os.Stdin)
    stin.Scan()
    n,_ := strconv.Atoi(stin.Text())
    stin.Scan()
    as := strings.Fields(stin.Text())
    var a [2000]int
    for i := 0; i < n; i++ {
        a[i],_ = strconv.Atoi(as[i])
    }
    stin.Scan()
    m,_ := strconv.Atoi(stin.Text())
    stin.Scan()
    bs := strings.Fields(stin.Text())
    var b [2000]int
    for i := 0; i < m; i++ {
        b[i],_ = strconv.Atoi(bs[i])
    }

    var sumA, sumB int64 = 0, 0
    for i := 0; i < n; i++ {
        sumA += int64(a[i])
    }
    for i := 0; i < m; i++ {
        sumB += int64(b[i])
    }

    var ansp []intPair

    ansv := abs64(sumA - sumB)
    curv := ansv

    //check 1
    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            sumA += int64(b[j] - a[i])
            sumB += int64(a[i] - b[j])
            curv = abs64(sumA - sumB)
            if ansv > curv {
                ansv = curv
                ansp = ansp[:0]  //clear ansp
                ansp = append(ansp, intPair{first:i, second:j})
            }
            sumA -= int64(b[j] - a[i])
            sumB -= int64(a[i] - b[j])
        }
    }

    //check 2
    z = make(map[int64]intPair)
    for j := 0; j < n; j++{
        for i := 0; i < j; i++ {
            z[int64(2) * int64(a[i] + a[j])] = intPair{first: i, second: j}
        }
    }
    //fmt.Printf("z = %v\n", z)
    if len(z) > 0 {
        var zKeys i64Array
        for k := range z {
            zKeys = append(zKeys, k)
        }
        sort.Sort(zKeys)

        for j := 0; j < m; j++ {
            for i := 0; i < j; i++ {
                val := sumA - sumB + int64(2) * int64(b[i] + b[j])
                //fmt.Printf("search for best key in %v\n", zKeys)
                bestKey := findNearestKey(zKeys, &val)
                //fmt.Printf("bestKey = %v\n", bestKey)
                //check several keys near the best one
                var kk [3]int64
                kk[0], kk[1], kk[2] = getKeyTriplet(zKeys, bestKey)
                //fmt.Printf("bestKeys = %v\n", kk)
                for qq := 0; qq < 3; qq++ {
                    curv := abs64(val - kk[qq])
                    p := z[kk[qq]]
                    if ansv > curv {
                        ansv = curv
                        ansp = ansp[:0]  //clear ansp
                        ansp = append(ansp, intPair{first:p.first, second:i})
                        ansp = append(ansp, intPair{first:p.second, second:j})
                    }
                }
            }
        }
    }
    fmt.Printf("%d\n", ansv)
    fmt.Printf("%d\n", len(ansp))
    for i := 0; i < len(ansp); i++ {
        fmt.Printf("%d %d\n", ansp[i].first + 1, ansp[i].second + 1)
    }
}


You are given a sequence of positive integers a1, a2, ..., an. While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step. You stop performing the operation when there is no pair of equal consecutive elements.For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second — [5, 3, 2, 2], after the third — [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.Determine the final sequence after you stop performing the operation.

The first line contains a single integer n (2 ≤ n ≤ 2·105) — the number of elements in the sequence. The second line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print a single integer k — the number of elements in the sequence after you stop performing the operation.  In the second line print k integers — the sequence after you stop performing the operation.

NoteThe first example is described in the statements.In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].In the third example there are no two equal consecutive elements initially, so the sequence does not change.

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 (
    "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 (
    "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 (
        "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"
	"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"
	"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 (
        "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]
    }
}