package main

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

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

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

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

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

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

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

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	res := 0

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

	return res
}

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

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

	return res
}

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

var n int64
var S []rune

func main() {
	n = ReadInt64()
	S = ReadRuneSlice()

	ans := n * (n - 1) / 2

	pressed, counts := RunLengthEncoding(S)

	length := len(pressed)
	for i := 0; i < length; i++ {
		if i+1 < length {
			ans -= int64(counts[i+1])
		}
		if i-1 >= 0 {
			ans -= int64(counts[i-1])
		}
	}
	// 重複して減らした部分を補正
	ans += int64(length - 1)

	fmt.Println(ans)
}

// RunLengthEncoding returns encoded slice of an input.
func RunLengthEncoding(S []rune) ([]rune, []int) {
	runes := []rune{}
	lengths := []int{}

	l := 0
	for i := 0; i < len(S); i++ {
		// 1文字目の場合保持
		if i == 0 {
			l = 1
			continue
		}

		if S[i-1] == S[i] {
			// 直前の文字と一致していればインクリメント
			l++
		} else {
			// 不一致のタイミングで追加し、長さをリセットする
			runes = append(runes, S[i-1])
			lengths = append(lengths, l)
			l = 1
		}
	}
	runes = append(runes, S[len(S)-1])
	lengths = append(lengths, l)

	return runes, lengths
}

// RunLengthDecoding decodes RLE results.
func RunLengthDecoding(S []rune, L []int) []rune {
	if len(S) != len(L) {
		panic("S, L are not RunLengthEncoding results")
	}

	res := []rune{}

	for i := 0; i < len(S); i++ {
		for j := 0; j < L[i]; j++ {
			res = append(res, S[i])
		}
	}

	return res
}

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

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

package main

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

func main() {
	var n int
	var s string

	reader := bufio.NewReader(os.Stdin)
	fmt.Fscanf(reader, "%d\n%s\n", &n, &s)

	//fmt.Println(n, s)
	a := make([]int, n)
	lastA := -1
	lastB := -1

	sum := int64(0)

	for i := 0; i < n; i++ {
		if s[i] == 'A' {
			if lastA < 0 {
				a[i] = 0
			} else if lastA+1 < i {
				a[i] = lastA + 1
			} else {
				//lastA + 1 = i
				a[i] = a[i-1] + 1
				if a[i-1] > 0 && i-2 >= 0 && a[i] < a[i-2]+2 {
					a[i] = a[i-2] + 2
				}

				if a[i-1] == 0 && i-2 >= 0 && a[i] < a[i-2]+1 {
					a[i] = a[i-2] + 1
				}
			}
			lastA = i
		} else {
			if lastB < 0 {
				a[i] = 0
			} else if lastB+1 < i {
				a[i] = lastB + 1
			} else {
				//lastB + 1 = i
				a[i] = a[i-1] + 1
				if a[i-1] > 0 && i-2 >= 0 && a[i] < a[i-2]+2 {
					a[i] = a[i-2] + 2
				}

				if a[i-1] == 0 && i-2 >= 0 && a[i] < a[i-2]+1 {
					a[i] = a[i-2] + 1
				}
			}
			lastB = i
		}

		sum += int64(a[i])
	}
	fmt.Printf("%d\n", sum)

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

	// fmt.Printf("\n")
}

package main

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

//утв1: плохая строка выглядит как AB+ или как AB
//утв2: если плохая строка длиннее 2, то добавление любого символа с плохого конца превратит строку в хорошую ABB -> AABB, ABB -> BABB
//утв3: добавление "плохого" символа с хорошего конца - тоже: ABB -> ABBA

//сжимаем строку по типу rle. получаем пары (символ, длина)
//подстроки длины 1 (n штук) и длины 2 вида ab (длина сжатой строки - 1) - плохие. считаем их
//перебираем (плохие) подстроки длины 3. от каждой смотрим в обе стороны и понимаем через сколько они исправятся и сколько попутно подстрок испортят. учитываем дубли (обходим так, чтобы их не было?).
//вычитаем количество плохих из общего количества.

/*
AAABABB
7 плохих по 1
3 плохих по 2
2 плохих по 3
первая плохая 3 портит еще одну
28-13 = 15
*/

type entry struct {
    letter rune
    count int64
}

func compress(s string) []entry {
    res := make([]entry, 0)
    cnt := int64(0)
    var cur rune
    for i, ch := range s {
        if cnt > 0 && cur != ch {
            res = append(res, entry{letter: cur, count: cnt})
            cnt = 0
            cur = ch
        } else if i == 0 {
            cur = ch
        }
        cnt++
    }
    if cnt > 0 {
        res = append(res, entry{letter: cur, count: cnt})
    }
    return res
}

func process(s string) int64 {
    bad := int64(len(s))

    entries := compress(s)

    if len(entries) > 1 {
        for i, e := range entries[:len(entries)-1] {
            next := entries[i+1]
            bad += 1
            bad += e.count - 1 + next.count - 1
        }
    }
    return totalSubstrs(int64(len(s))) - bad
}

func totalSubstrs(size int64) int64 {
    if size % 2 == 1 {
        return size * ((size+1)/2)
    }
    return (size/2) * (size+1)
}

func main() {
//    scanner := bufio.NewScanner(os.Stdin)
//    scanner.Split(bufio.ScanWords)

    reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024)
    n := parseInt(readLine(reader))

    s := readLine(reader)

    if len(s) != int(n) {
        panic(len(s))
    }

/*    if len(s) > 100 {
        entries := compress(s)
        fmt.Println(entries)
    }*/
    fmt.Println(process(s))

/*    if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}*/
}

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

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

func scanInt64(scanner *bufio.Scanner) int64 {
    scanner.Scan()
    return parseInt(scanner.Text())
}

func scanInt(scanner *bufio.Scanner) int {
    return int(scanInt64(scanner))
}

func parseInt(s string) int64 {
    v, err := strconv.ParseInt(s, 10, 64)
    if err != nil {
        panic(err)
    }
    return v
}

package main

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

//утв1: плохая строка выглядит как AB+ или как AB
//утв2: если плохая строка длиннее 2, то добавление любого символа с плохого конца превратит строку в хорошую ABB -> AABB, ABB -> BABB
//утв3: добавление "плохого" символа с хорошего конца - тоже: ABB -> ABBA

//сжимаем строку по типу rle. получаем пары (символ, длина)
//подстроки длины 1 (n штук) и длины 2 вида ab (длина сжатой строки - 1) - плохие. считаем их
//перебираем (плохие) подстроки длины 3. от каждой смотрим в обе стороны и понимаем через сколько они исправятся и сколько попутно подстрок испортят. учитываем дубли (обходим так, чтобы их не было?).
//вычитаем количество плохих из общего количества.

/*
AAABABB
7 плохих по 1
3 плохих по 2
2 плохих по 3
первая плохая 3 портит еще одну
28-13 = 15
*/

type entry struct {
    letter rune
    count int
}

func compress(s string) []entry {
    res := make([]entry, 0)
    cnt := 0
    var cur rune
    for i, ch := range s {
        if cnt > 0 && cur != ch {
            res = append(res, entry{letter: cur, count: cnt})
            cnt = 0
            cur = ch
        } else if i == 0 {
            cur = ch
        }
        cnt++
    }
    if cnt > 0 {
        res = append(res, entry{letter: cur, count: cnt})
    }
    return res
}

func process(s string) int {
    bad := len(s)

    entries := compress(s)

    if len(entries) > 1 {
        for i, e := range entries[:len(entries)-1] {
            next := entries[i+1]
            bad += 1
            bad += e.count - 1 + next.count - 1
        }
    }
    return totalSubstrs(len(s)) - bad
}

func totalSubstrs(size int) int {
    if size % 2 == 1 {
        return size * ((size+1)/2)
    }
    return (size/2) * (size+1)
}

func main() {
//    scanner := bufio.NewScanner(os.Stdin)
//    scanner.Split(bufio.ScanWords)

    reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024)
    n := parseInt(readLine(reader))

    s := readLine(reader)

    if len(s) != int(n) {
        panic(len(s))
    }

    if len(s) > 100 {
        entries := compress(s)
        fmt.Println(entries)
    }
    fmt.Println(process(s))

/*    if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}*/
}

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

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

func scanInt64(scanner *bufio.Scanner) int64 {
    scanner.Scan()
    return parseInt(scanner.Text())
}

func scanInt(scanner *bufio.Scanner) int {
    return int(scanInt64(scanner))
}

func parseInt(s string) int64 {
    v, err := strconv.ParseInt(s, 10, 64)
    if err != nil {
        panic(err)
    }
    return v
}

package main

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

//утв1: плохая строка выглядит как AB+ или как AB
//утв2: если плохая строка длиннее 2, то добавление любого символа с плохого конца превратит строку в хорошую ABB -> AABB, ABB -> BABB
//утв3: добавление "плохого" символа с хорошего конца - тоже: ABB -> ABBA

//сжимаем строку по типу rle. получаем пары (символ, длина)
//подстроки длины 1 (n штук) и длины 2 вида ab (длина сжатой строки - 1) - плохие. считаем их
//перебираем (плохие) подстроки длины 3. от каждой смотрим в обе стороны и понимаем через сколько они исправятся и сколько попутно подстрок испортят. учитываем дубли (обходим так, чтобы их не было?).
//вычитаем количество плохих из общего количества.

/*
AAABABB
7 плохих по 1
3 плохих по 2
2 плохих по 3
первая плохая 3 портит еще одну
28-13 = 15
*/

type entry struct {
    letter rune
    count int
}

func compress(s string) []entry {
    res := make([]entry, 0)
    cnt := 0
    var cur rune
    for i, ch := range s {
        if cnt > 0 && cur != ch {
            res = append(res, entry{letter: cur, count: cnt})
            cnt = 0
            cur = ch
        } else if i == 0 {
            cur = ch
        }
        cnt++
    }
    if cnt > 0 {
        res = append(res, entry{letter: cur, count: cnt})
    }
    return res
}

func process(s string) int {
    bad := len(s)

    entries := compress(s)

    if len(entries) > 1 {
        for i, e := range entries[:len(entries)-1] {
            next := entries[i+1]
            bad += 1
            bad += e.count - 1 + next.count - 1
        }
    }
    return totalSubstrs(len(s)) - bad
}

func totalSubstrs(size int) int {
    if size % 2 == 1 {
        return size * ((size+1)/2)
    }
    return (size/2) * (size+1)
}

func main() {
//    scanner := bufio.NewScanner(os.Stdin)
//    scanner.Split(bufio.ScanWords)

    reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024)
    n := parseInt(readLine(reader))

    s := readLine(reader)

    if len(s) != int(n) {
        panic(len(s))
    }

    entries := compress(s)
    fmt.Println(entries)
//    fmt.Println(process(s))

/*    if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}*/
}

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

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

func scanInt64(scanner *bufio.Scanner) int64 {
    scanner.Scan()
    return parseInt(scanner.Text())
}

func scanInt(scanner *bufio.Scanner) int {
    return int(scanInt64(scanner))
}

func parseInt(s string) int64 {
    v, err := strconv.ParseInt(s, 10, 64)
    if err != nil {
        panic(err)
    }
    return v
}

package main

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

//утв1: плохая строка выглядит как AB+ или как AB
//утв2: если плохая строка длиннее 2, то добавление любого символа с плохого конца превратит строку в хорошую ABB -> AABB, ABB -> BABB
//утв3: добавление "плохого" символа с хорошего конца - тоже: ABB -> ABBA

//сжимаем строку по типу rle. получаем пары (символ, длина)
//подстроки длины 1 (n штук) и длины 2 вида ab (длина сжатой строки - 1) - плохие. считаем их
//перебираем (плохие) подстроки длины 3. от каждой смотрим в обе стороны и понимаем через сколько они исправятся и сколько попутно подстрок испортят. учитываем дубли (обходим так, чтобы их не было?).
//вычитаем количество плохих из общего количества.

/*
AAABABB
7 плохих по 1
3 плохих по 2
2 плохих по 3
первая плохая 3 портит еще одну
28-13 = 15
*/

type entry struct {
    letter rune
    count int
}

func compress(s string) []entry {
    res := make([]entry, 0)
    cnt := 0
    var cur rune
    for i, ch := range s {
        if cnt > 0 && cur != ch {
            res = append(res, entry{letter: cur, count: cnt})
            cnt = 0
            cur = ch
        } else if i == 0 {
            cur = ch
        }
        cnt++
    }
    if cnt > 0 {
        res = append(res, entry{letter: cur, count: cnt})
    }
    return res
}

func process(s string) int {
    bad := len(s)

    entries := compress(s)

    if len(entries) > 1 {
        for i, e := range entries[:len(entries)-1] {
            next := entries[i+1]
            bad += 1
            bad += e.count - 1 + next.count - 1
        }
    }
    return totalSubstrs(len(s)) - bad
}

func totalSubstrs(size int) int {
    if size % 2 == 1 {
        return size * ((size+1)/2)
    }
    return (size/2) * (size+1)
}

func main() {
//    scanner := bufio.NewScanner(os.Stdin)
//    scanner.Split(bufio.ScanWords)

    reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024)
    n := parseInt(readLine(reader))

    s := readLine(reader)

    if len(s) != int(n) {
        panic(len(s))
    }

    fmt.Println(process(s))

/*    if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}*/
}

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

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

func scanInt64(scanner *bufio.Scanner) int64 {
    scanner.Scan()
    return parseInt(scanner.Text())
}

func scanInt(scanner *bufio.Scanner) int {
    return int(scanInt64(scanner))
}

func parseInt(s string) int64 {
    v, err := strconv.ParseInt(s, 10, 64)
    if err != nil {
        panic(err)
    }
    return v
}

package main

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

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

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

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

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

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

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

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	res := 0

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

	return res
}

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

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

	return res
}

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

var n int
var S []rune

var dp [300000 + 5]int
var memo [300000 + 5]int

func main() {
	n = ReadInt()
	S = ReadRuneSlice()

	aIdx, bIdx := -1, -1
	for i := 0; i < n; i++ {
		if S[i] == 'A' {
			memo[i] = aIdx
			ChMax(&aIdx, i)
		} else {
			memo[i] = bIdx
			ChMax(&bIdx, i)
		}
	}

	cur := 0
	for i := 0; i < n; i++ {
		if memo[i] == -1 {
			continue
		}
		dp[i] = cur + 1
		cur++
	}

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

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

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

package main

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

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

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

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

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

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

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

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	res := 0

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

	return res
}

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

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

	return res
}

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

var n int
var S []rune

var dp [300000 + 5]int
var memo [300000 + 5]int

func main() {
	n = ReadInt()
	S = ReadRuneSlice()

	aIdx, bIdx := -1, -1
	for i := 0; i < n; i++ {
		if S[i] == 'A' {
			memo[i] = aIdx
			ChMax(&aIdx, i)
		} else {
			memo[i] = bIdx
			ChMax(&bIdx, i)
		}
	}

	cur := 0
	for i := 0; i < n; i++ {
		if memo[i] == -1 {
			continue
		}
		dp[i] = cur + 1
		cur++
	}

	ans := 0
	for i := 0; i < n; i++ {
		ans += dp[i]
	}
	fmt.Println(ans)
}

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

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

package main

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

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

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

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

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

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

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

// ReadInt64 returns as integer as int64.
func ReadInt64() int64 {
	return readInt64()
}
func ReadInt64_2() (int64, int64) {
	return readInt64(), readInt64()
}
func ReadInt64_3() (int64, int64, int64) {
	return readInt64(), readInt64(), readInt64()
}
func ReadInt64_4() (int64, int64, int64, int64) {
	return readInt64(), readInt64(), readInt64(), readInt64()
}

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

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

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

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

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

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

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

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

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

	return res
}

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

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

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

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

	res := 0

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

	return res
}

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

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

	return res
}

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

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

	return s
}

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

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

	if e == 0 {
		return 1
	}

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

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

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

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

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

	return a
}

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

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

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

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

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

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

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

	return string(res)
}

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

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

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

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

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

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

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

var n int
var S []rune

func main() {
	n = ReadInt()
	S = ReadRuneSlice()

	ans := n * (n - 1) / 2

	pressed, counts := RunLengthEncoding(S)

	length := len(pressed)
	for i := 0; i < length; i++ {
		if i+1 < length {
			ans -= counts[i+1]
		}
		if i-1 >= 0 {
			ans -= counts[i-1]
		}
	}
	// 重複して減らした部分を補正
	ans += length - 1

	fmt.Println(ans)
}

// RunLengthEncoding returns encoded slice of an input.
func RunLengthEncoding(S []rune) ([]rune, []int) {
	runes := []rune{}
	lengths := []int{}

	l := 0
	for i := 0; i < len(S); i++ {
		// 1文字目の場合保持
		if i == 0 {
			l = 1
			continue
		}

		if S[i-1] == S[i] {
			// 直前の文字と一致していればインクリメント
			l++
		} else {
			// 不一致のタイミングで追加し、長さをリセットする
			runes = append(runes, S[i-1])
			lengths = append(lengths, l)
			l = 1
		}
	}
	runes = append(runes, S[len(S)-1])
	lengths = append(lengths, l)

	return runes, lengths
}

// RunLengthDecoding decodes RLE results.
func RunLengthDecoding(S []rune, L []int) []rune {
	if len(S) != len(L) {
		panic("S, L are not RunLengthEncoding results")
	}

	res := []rune{}

	for i := 0; i < len(S); i++ {
		for j := 0; j < L[i]; j++ {
			res = append(res, S[i])
		}
	}

	return res
}

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

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


package main

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

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

	const mx int = 1e6
	np := [mx + 1]bool{1: true}
	for i := 2; i <= mx; i++ {
		if !np[i] {
			for j := 2 * i; j <= mx; j += i {
				np[j] = true
			}
		}
	}

	var T, n, d int
	for Fscan(in, &T); T > 0; T-- {
		Fscan(in, &n, &d)
		a := make([]int, n)
		for i := range a {
			Fscan(in, &a[i])
		}
		ans := int64(0)
		for i, v := range a {
			if np[v] {
				continue
			}
			l, r := i, i
			for l >= d && a[l-d] == 1 {
				l -= d
			}
			for r+d < n && a[r+d] == 1 {
				r += d
			}
			ans += int64((i-l)/d+1)*int64((r-i)/d+1) - 1
		}
		Fprintln(out, ans)
	}
}

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

package main

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

/*
1
8 1
2 1 1 1 1 1 1 3
---
12
=======
1
4 1
1 2 1 1
---
5
*/

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

	a := make([]int, n)

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

	cnt := int64(0)

	for i, num := range a {
		if isPrime(num) {
			rhtCnt := int64(0)
			for j := i + e; j < n; j += e {
				if a[j] == 1 {
					rhtCnt++
				} else {
					break
				}
			}

			lftCnt := int64(0)
			for j := i - e; j >= 0; j -= e {
				if a[j] == 1 {
					lftCnt++
				} else {
					break
				}
			}

			cnt += lftCnt*rhtCnt + lftCnt + rhtCnt
		}
	}

	fmt.Fprintln(writer, cnt)
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

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

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

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

	return minNumIdx
}

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

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

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

//goland:noinspection GoUnusedFunction
func findSet(parent []int, v int) int {
	if v == parent[v] {
		return v
	}

	parent[v] = findSet(parent, parent[v])

	return parent[v]
}

//goland:noinspection GoUnusedFunction
func unionSets(parent []int, v, u int) {
	v = findSet(parent, v)
	u = findSet(parent, u)

	if v != u {
		parent[v] = u
	}
}

package main

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

var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assert!")}
}

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

func main() {
    defer output.Flush()
    //solve()
    //return
	var t int64
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
}

func solve() {
    var n, e int
    fmt.Fscan(input, &n, &e)
    a := make([]int, n)
    ones := make([]*int, n)
    for i := 0; i < n; i++ {
        fmt.Fscan(input, &a[i])
        if a[i] == 1 {
            if i - e >= 0 {
                if ones[i - e] != nil {
                    ones[i] = ones[i - e]
                    *ones[i]++
                } else {
                    tmp := 1
                    ones[i] = &tmp
                }
            } else {
                tmp := 1
                ones[i] = &tmp
            }
        }
    }
    // 1 ... 1 ...  p
    ans := int64(0)
    for i := 0; i < n; i++ {
        if !isPrime(a[i]) { continue }
        l, r := int64(0), int64(0)
        if i - e >= 0 && ones[i - e] != nil { l = int64(*ones[i - e]) }
        if i + e < len(a) && ones[i + e] != nil { r = int64(*ones[i + e]) }
        ans += l * r + l + r
    }

    fmt.Fprintln(output, ans)
}

func isPrime(v int) bool {
    if v == 1 { return false }
    for i := 2; i * i <= v; i++ {
        if v % i == 0 { return false }
    }
    return true
}

package main

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

/*
1
8 1
2 1 1 1 1 1 1 3
---
12
=======
1
4 1
1 2 1 1
---
5
*/

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

	a := make([]int, n)

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

	cnt := 0

	for i, num := range a {
		if isPrime(num) {
			rhtCnt := 0
			for j := i + e; j < n; j += e {
				if a[j] == 1 {
					rhtCnt++
				} else {
					break
				}
			}

			lftCnt := 0
			for j := i - e; j >= 0; j -= e {
				if a[j] == 1 {
					lftCnt++
				} else {
					break
				}
			}

			cnt += lftCnt*rhtCnt + lftCnt + rhtCnt
		}
	}

	fmt.Fprintln(writer, cnt)
}

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

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

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

const maxUint = ^uint(0)

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

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

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

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

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

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

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

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

	return minNumIdx
}

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

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

	return maxNumIdx
}

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

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

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

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

	return true
}

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

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

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

	num = abs(num)

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

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

//goland:noinspection GoUnusedFunction
func findSet(parent []int, v int) int {
	if v == parent[v] {
		return v
	}

	parent[v] = findSet(parent, parent[v])

	return parent[v]
}

//goland:noinspection GoUnusedFunction
func unionSets(parent []int, v, u int) {
	v = findSet(parent, v)
	u = findSet(parent, u)

	if v != u {
		parent[v] = u
	}
}

package main

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

var (
	input = bufio.NewReader(os.Stdin)
	output = bufio.NewWriter(os.Stdout)
)

func assert(test bool) {
    if !test {panic("assert!")}
}

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)
// TODO***
// - read the statement carefully
// - get solution before coding
// - check the boundaries (int/int64)

func main() {
    defer output.Flush()
    //solve()
    //return
	var t int64
	fmt.Fscan(input, &t)
    for t > 0 {
        t--
        solve()
    }
}

func solve() {
    var n, e int
    fmt.Fscan(input, &n, &e)
    a := make([]int, n)
    ones := make([]*int, n)
    for i := 0; i < n; i++ {
        fmt.Fscan(input, &a[i])
        if a[i] == 1 {
            if i - e >= 0 {
                if ones[i - e] != nil {
                    ones[i] = ones[i - e]
                    *ones[i]++
                } else {
                    tmp := 1
                    ones[i] = &tmp
                }
            } else {
                tmp := 1
                ones[i] = &tmp
            }
        }
    }
    // 1 ... 1 ...  p
    ans := int64(0)
    for i := 0; i < n; i++ {
        if !isPrime(a[i]) { continue }
        if i - e >= 0 && ones[i - e] != nil { ans += int64(*ones[i - e]) }
        if i + e < len(a) && ones[i + e] != nil { ans += int64(*ones[i + e]) }
        if i - e >= 0 && i + e < len(a) && ones[i - e] != nil && ones[i + e] != nil {
            ans += int64(*ones[i - e] * *ones[i + e])
        }
    }
    fmt.Fprintln(output, ans)
}

func isPrime(v int) bool {
    if v == 1 { return false }
    for i := 2; i * i <= v; i++ {
        if v % i == 0 { return false }
    }
    return true
}


package main

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

//9 16 15 13
func cal(odd, even int64) int64 {
	//fmt.Println(odd, even)
	if odd > even {
		return odd*2 - 1
	}
	rest := even - odd
	even -= rest / 3
	if rest%3 == 0 || rest%3 == 1 {
		return even * 2
	}
	return even*2 - 1

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

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 0)
			continue
		}

		max := nums[len(nums)-1]
		odd := int64(0)
		even := int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		ans := cal(odd, even)
		max = nums[len(nums)-1] + 1
		odd = int64(0)
		even = int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		temp := cal(odd, even)
		if temp < ans {
			ans = temp
		}
		fmt.Fprintln(out, ans)
	}
}

//4 3

package main

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

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

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

	var c int64
	var n int64
	Fscan(in, &c)
	for t := int64(1); t <= c; t++ {
		Fscan(in, &n)
		a := make([]int64, n)
		max := int64(0)
		for i := range a {
			Fscan(in, &a[i])
			if a[i] > max {
				max = a[i]
			}
		}
		arr := []int64{}
		for _, v := range a {
			if max-v != 0 {
				arr = append(arr, max-v)
			}
		}
		res := slove(arr, 0, 0)
		arr = []int64{}
		fl := false
		max++
		for _, v := range a {
			if v == max-1 && !fl {
				fl = true
			} else {
				arr = append(arr, max-v)
			}
		}
		res = min(res, slove(arr, 1, 2))
		Fprintln(out, res)
	}
}

func slove(arr []int64, two int64, ans int64) int64 {
	odd := int64(0)
	even := int64(0)
	for _, v := range arr {
		even += v / 2
		if v%2 == 1 {
			odd++
		}
	}
	k := even - two - (odd - 1)
	if k <= 0 {
		return ans + odd*2 - 1
	}
	ans += odd*2 - 1
	even = k
	ans += even * 2 / 3 * 2
	r := even * 2 % 3
	if r == 1 {
		ans++
	} else if r == 2 {
		ans += 1
	}
	return ans
}

func min(i, j int64) int64 {
	if i < j {
		return i
	}
	return j
}

package main

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

const (
	INF = 3e5 + 10
)

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

	var t int
	Fscan(in, &t)

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

		var n int
		Fscan(in, &n)

		a := make([]int, n)

		ma := 0
		for i := 0; i < n; i++ {
			Fscan(in, &a[i])

			if a[i] > ma {
				ma = a[i]
			}
		}

		ans := min(check(ma, &a), check(ma+1, &a))
		Fprintln(out, ans)

	}

}

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

}

func check(target int, a *[]int) int64 {
	need1 := int64(0)
	needs := int64(0)
	for i := 0; i < len(*a); i++ {
		tmp := target - (*a)[i]
		if tmp%2 == 1 {
			need1++
		}
		needs += int64(tmp)
	}

	ans := int64(0)

	if needs > need1*3+6 {
		needs -= (need1 - 1) * 3
		ans += (need1 - 1) << 1
		need1 -= need1 - 1

		if needs > 6 {
			ans += (needs / 6) * 4
			needs -= (needs / 6) * 6
		}
	}

	cur := 0
	for needs > 0 {
		ans++
		if cur == 0 {
			if need1 > 0 {
				needs--
				need1--
			} else if needs-need1 > int64(2) {
				needs--
				need1++
			}
		} else {
			if needs-need1 >= int64(2) {
				needs -= 2
			}
		}
		cur ^= 1
	}

	return ans

}

package main

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

//9 16 15 13
func cal(odd, even int64) int64 {
	//fmt.Println(odd, even)
	if odd > even {
		return odd*2 - 1
	}
	rest := even - odd
	even -= rest / 3
	if rest%3 == 0 {

		return even * 2
	}
	return even*2 - 1

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

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 0)
			continue
		}

		max := nums[len(nums)-1]
		odd := int64(0)
		even := int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		ans := cal(odd, even)
		max = nums[len(nums)-1] + 1
		odd = int64(0)
		even = int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		temp := cal(odd, even)
		if temp < ans {
			ans = temp
		}
		fmt.Fprintln(out, ans)
	}
}

//4 3

package main

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

//9 16 15 13
func cal(odd, even int64) int64 {
	if odd > even {
		return odd*2 - 1
	}
	rest := even - odd
	even -= rest / 3
	return even * 2

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

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 0)
			continue
		}

		max := nums[len(nums)-1]
		odd := int64(0)
		even := int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		ans := cal(odd, even)
		max = nums[len(nums)-1] + 1
		odd = int64(0)
		even = int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		temp := cal(odd, even)
		if temp < ans {
			ans = temp
		}
		fmt.Fprintln(out, ans)
	}
}

//4 3

package main

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

func cal(nums []int64, max int64) int64 {
	odd := int64(0)
	even := int64(0)
	for i := 0; i < len(nums); i++ {
		if (max-nums[i])&1 == 1 {
			odd++
			even += (max - nums[i] - 1) / 2
		} else {
			even += (max - nums[i]) / 2
		}
	}

	ans := int64(-1)
	for odd <= even {
		var temp = even * 2
		if temp < ans || ans == -1 {
			ans = temp
		}
		odd += 2
		even--
	}
	if ans > odd*2-1 || ans == -1 {
		ans = odd*2 - 1
	}
	return ans
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 1)
			continue
		}
		max := nums[len(nums)-1]
		ans := cal(nums, max)
		temp := cal(nums, max+1)
		if temp < ans {
			ans = temp
		}
		temp = cal(nums, max+2)
		if temp < ans {
			ans = temp
		}
		temp = cal(nums, max+3)
		if temp < ans {
			ans = temp
		}
		fmt.Fprintln(out, ans)
	}
}

//5 5

package main

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

func cal(nums []int64, max int64) int64 {
	odd := int64(0)
	even := int64(0)
	for i := 0; i < len(nums); i++ {
		if (max-nums[i])&1 == 1 {
			odd++
			even += (max - nums[i] - 1) / 2
		} else {
			even += (max - nums[i]) / 2
		}
	}

	ans := int64(-1)
	for odd <= even {
		var temp = even * 2
		if temp < ans || ans == -1 {
			ans = temp
		}
		odd += 2
		even--
	}
	if ans > odd*2-1 || ans == -1 {
		ans = odd*2 - 1
	}
	return ans
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 1)
			continue
		}
		max := nums[len(nums)-1]
		ans := cal(nums, max)
		temp := cal(nums, max+1)
		if temp < ans {
			ans = temp
		}
		fmt.Fprintln(out, ans)
	}
}

//5 5

package main

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

func cal(nums []int64) int64 {
	max := nums[len(nums)-1]
	odd := int64(0)
	even := int64(0)
	for i := 0; i < len(nums); i++ {
		if (max-nums[i])&1 == 1 {
			odd++
			even += (max - nums[i] - 1) / 2
		} else {
			even += (max - nums[i]) / 2
		}
	}

	ans := int64(-1)
	for odd <= even {
		var temp = even * 2
		if temp < ans || ans == -1 {
			ans = temp
		}
		odd += 2
		even--
	}
	if ans > odd*2-1 || ans == -1 {
		ans = odd*2 - 1
	}
	return ans
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 1)
			continue
		}

		ans := cal(nums)
		nums[len(nums)-1]++
		temp := cal(nums)
		if temp < ans {
			ans = temp
		}
		fmt.Fprintln(out, ans)
	}
}

package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 1)
			continue
		}

		max := nums[len(nums)-1]
		odd := int64(0)
		even := int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		ans := int64(-1)
		for odd <= even {
			var temp int64
			if odd == even {
				temp = odd * 2
			} else {
				temp = even * 2
			}
			if temp < ans || ans == -1 {
				ans = temp
			}
			odd += 2
			even--
		}
		if ans > odd*2-1 || ans == -1 {
			ans = odd*2 - 1
		}
		fmt.Fprintln(out, ans)
	}
}

package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 0)
			continue
		}

		max := nums[len(nums)-1]
		odd := int64(0)
		even := int64(0)
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		ans := int64(-1)
		for odd <= even {
			var temp int64
			if odd == even {
				temp = odd * 2
			} else {
				temp = even * 2
			}
			if temp < ans || ans == -1 {
				ans = temp
			}
			odd += 2
			even--
		}
		if ans > odd*2-1 || ans == -1 {
			ans = odd*2 - 1
		}
		fmt.Fprintln(out, ans)
	}
}

package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 0)
			continue
		}

		max := nums[len(nums)-1]
		odd := 0
		even := 0
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		ans := -1
		for odd <= even {
			var temp int
			if odd == even {
				temp = odd * 2
			} else {
				temp = even * 2
			}
			if temp < ans || ans == -1 {
				ans = temp
			}
			odd += 2
			even--
		}
		if ans > odd*2-1 || ans == -1 {
			ans = odd*2 - 1
		}
		fmt.Fprintln(out, ans)
	}
}

package main

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

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func main() {
	in, out := bufio.NewReader(os.Stdin), bufio.NewWriter(os.Stdout)
	defer out.Flush()
	var t int
	fmt.Fscan(in, &t)

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

		sort.Slice(nums, func(i, j int) bool {
			return nums[i] < nums[j]
		})
		if nums[len(nums)-1] == nums[0] {
			fmt.Fprintln(out, 0)
			continue
		}

		max := nums[len(nums)-1]
		odd := 0
		even := 0
		for i := 0; i < len(nums); i++ {
			if (max-nums[i])&1 == 1 {
				odd++
				even += (max - nums[i] - 1) / 2
			} else {
				even += (max - nums[i]) / 2
			}
		}
		ans := -1
		if odd > even {
			ans = odd*2 - 1
		}
		for odd <= even {
			var temp int
			if odd == even {
				temp = odd * 2
			} else {
				temp = even * 2
			}
			if temp < ans || ans == -1 {
				ans = temp
			}
			odd += 2
			even--
		}
		fmt.Fprintln(out, ans)
	}
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for t := 1; t <= c; t++ {
		Fscan(in, &n)
		a := make([]int, n)
		max := 0
		for i := range a {
			Fscan(in, &a[i])
			if a[i] > max {
				max = a[i]
			}
		}
		arr := []int{}
		for _, v := range a {
			if max-v != 0 {
				arr = append(arr, max-v)
			}
		}
		res := slove(arr, 0, 0)
		arr = []int{}
		fl := false
		max++
		for _, v := range a {
			if v == max-1 && !fl {
				fl = true
			} else {
				arr = append(arr, max-v)
			}
		}
		res = min(res, slove(arr, 1, 2))
		Fprintln(out, res)
	}
}

func slove(arr []int, two int, ans int) int {
	odd := 0
	even := 0
	for _, v := range arr {
		even += v / 2
		if v%2 == 1 {
			odd++
		}
	}
	k := even - two - (odd - 1)
	if k <= 0 {
		return ans + odd*2 - 1
	}
	ans += odd*2 - 1
	even = k
	ans += even * 2 / 3 * 2
	r := even * 2 % 3
	if r == 1 {
		ans++
	} else if r == 2 {
		ans += 1
	}
	return ans
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for t := 1; t <= c; t++ {
		Fscan(in, &n)
		a := make([]int, n)
		max := 0
		for i := range a {
			Fscan(in, &a[i])
			if a[i] > max {
				max = a[i]
			}
		}
		if t == 468 {
			Println(a)
		}
		arr := []int{}
		for _, v := range a {
			if max-v != 0 {
				arr = append(arr, max-v)
			}
		}
		res := slove(arr, 0, 0)
		arr = []int{}
		fl := false
		max++
		for _, v := range a {
			if v == max-1 && !fl {
				fl = true
			} else {
				arr = append(arr, max-v)
			}
		}
		res = min(res, slove(arr, 1, 2))
		Fprintln(out, res)
	}
}

func slove(arr []int, two int, ans int) int {
	odd := 0
	even := 0
	for _, v := range arr {
		even += v / 2
		if v%2 == 1 {
			odd++
		}
	}
	k := even - two - (odd - 1)
	if k <= 0 {
		return ans + odd*2 - 1
	}
	ans += odd*2 - 1
	even = k
	ans += even * 2 / 3 * 2
	r := even * 2 % 3
	if r == 1 {
		ans++
	} else if r == 2 {
		ans += 1
	}
	return ans
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for t := 1; t <= c; t++ {
		Fscan(in, &n)
		a := make([]int, n)
		max := 0
		for i := range a {
			Fscan(in, &a[i])
			if a[i] > max {
				max = a[i]
			}
		}
		if t == 468 {
			Println(a)
		}
		arr := []int{}
		for _, v := range a {
			if max-v != 0 {
				arr = append(arr, max-v)
			}
		}
		res := slove(arr, 0, 0)
		for i := range arr {
			arr[i]++
		}
		res = min(res, slove(arr, 1, 2))
		Fprintln(out, res)
	}
}

func slove(arr []int, two int, ans int) int {
	odd := 0
	even := 0
	for _, v := range arr {
		even += v / 2
		if v%2 == 1 {
			odd++
		}
	}
	k := even - two - (odd - 1)
	if k <= 0 {
		return ans + odd*2 - 1
	}
	ans += odd*2 - 1
	even = k
	ans += even * 2 / 3 * 2
	r := even * 2 % 3
	if r == 1 {
		ans++
	} else if r == 2 {
		ans += 1
	}
	return ans
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for t := 0; t < c; t++ {
		Fscan(in, &n)
		a := make([]int, n)
		max := 0
		for i := range a {
			Fscan(in, &a[i])
			if a[i] > max {
				max = a[i]
			}
		}
		arr := []int{}
		for _, v := range a {
			if max-v != 0 {
				arr = append(arr, max-v)
			}
		}
		res := slove(arr, 0, 0)
		for i := range arr {
			arr[i]++
		}
		res = min(res, slove(arr, 1, 2))
		Fprintln(out, res)
	}
}

func slove(arr []int, two int, ans int) int {
	odd := 0
	even := 0
	for _, v := range arr {
		even += v / 2
		if v%2 == 1 {
			odd++
		}
	}
	k := even - two - (odd - 1)
	if k <= 0 {
		return ans + odd*2 - 1
	}
	ans += odd*2 - 1
	even = k
	ans += even * 2 / 3 * 2
	r := even * 2 % 3
	if r == 1 {
		ans++
	} else if r == 2 {
		ans += 1
	}
	return ans
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for t := 0; t < c; t++ {
		Fscan(in, &n)
		a := make([]int, n)
		max := 0
		for i := range a {
			Fscan(in, &a[i])
			if a[i] > max {
				max = a[i]
			}
		}
		arr := []int{}
		for _, v := range a {
			if max-v != 0 {
				arr = append(arr, max-v)
			}
		}
		res := slove(arr, 0, 0)
		for i := range arr {
			arr[i]++
		}
		Println(arr)
		res = min(res, slove(arr, 1, 2))
		Fprintln(out, res)
	}
}

func slove(arr []int, two int, ans int) int {
	odd := 0
	even := 0
	for _, v := range arr {
		even += v / 2
		if v%2 == 1 {
			odd++
		}
	}
	k := even - two - (odd - 1)
	if k <= 0 {
		return ans + odd*2 - 1
	}
	ans += odd*2 - 1
	even = k
	ans += even * 2 / 3 * 2
	r := even * 2 % 3
	if r == 1 {
		ans++
	} else if r == 2 {
		ans += 1
	}
	return ans
}

func min(i, j int) int {
	if i < j {
		return i
	}
	return j
}

package main

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

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

func A(_r io.Reader, _w io.Writer) {
	in, out := bufio.NewReader(_r), bufio.NewWriterSize(_w, 102400)
	defer out.Flush()

	var c int
	var n int
	Fscan(in, &c)
	for t := 0; t < c; t++ {
		Fscan(in, &n)
		a := make([]uint64, n)
		one := 0
		max := uint64(0)
		for i := range a {
			Fscan(in, &a[i])
			if a[i] > max {
				max = a[i]
			}
		}
		total := uint64(0)
		for _, v := range a {
			if k := max - v; k > 1 {
				total += k
			} else if k == 1 {
				one++
			}
		}
		two := one - 1
		ans := uint64(one)
		if ans > 0 {
			ans = ans*2 - 1
		}
		if k := total % 3; k != 0 {
			if k%2 == 0 {
				if two <= 0 {
					ans += 2
				}
			} else {
				ans++
			}
		}
		ans += total / 3 * 2
		Fprintln(out, ans)
	}
}

package main

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

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

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

	var c int
	var n int
	Fscan(in, &c)
	for ; c > 0; c-- {
		Fscan(in, &n)
		max := uint64(0)
		arr := make([]uint64, n)
		for i := range arr {
			Fscan(in, &arr[i])
			if arr[i] > max {
				max = arr[i]
			}
		}
		b := []uint64{}
		var sum uint64
		for i := range arr {
			if max-arr[i] != 0 {
				b = append(b, max-arr[i])
				sum += max - arr[i]
			}
		}
		var ans uint64
		k := sum % 3
		if k == 0 {
			ans = sum / 3 * 2
		} else if k%2 == 0 {
			ans = sum/3*2 + 2
		} else if k%2 == 1 {
			ans = sum/3*2 + 1
		}
		Fprintln(out, ans)
	}
}

package main

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

const (
	INF = 3e5 + 10
)

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

	var t int
	Fscan(in, &t)

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

		var n int
		Fscan(in, &n)

		a := make([]int, n)

		ma := 0
		for i := 0; i < n; i++ {
			Fscan(in, &a[i])

			if a[i] > ma {
				ma = a[i]
			}
		}

		ans := check(ma, &a)
		Fprintln(out, ans)

	}

}

func check(target int, a *[]int) int {
	need1 := int64(0)
	needs := int64(0)
	for i := 0; i < len(*a); i++ {
		tmp := target - (*a)[i]
		if tmp%2 == 1 {
			need1++
		}
		needs += int64(tmp)
	}

	ans := 0
	cur := 0
	for needs > 0 {
		ans++
		if cur == 0 {
			if need1 > 0 {
				needs--
				need1--
			} else if needs-need1 > int64(2) {
				needs--
				need1++
			}
		} else {
			if needs-need1 >= int64(2) {
				needs -= 2
			}
		}
		cur ^= 1
	}

	return ans

}


package main

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

var T, N int
var S string
var A, B, AB, BA int

func solve() string {
	N = len(S)
	var na, nb int
	for _, c := range(S) {
		if c == 'A' {
			na++
		}else{
			nb++
		}
	}

	if na != A + AB + BA || nb != B + AB + BA {
		return "NO"
	}

	segs := []string{}
	i, j := 0, 0
	for i < N - 1{
		for j = i + 1; j < N && S[j] != S[j-1]; j++ {}
		if j - i > 1 {
			segs = append(segs, S[i:j])
		}
		i = j
	}

	sort.Slice(segs, func(i, j int) bool {
		ni, nj := len(segs[i]) % 2, len(segs[j]) % 2
		if ni == nj {
			return len(segs[i]) < len(segs[j])
		}
		return ni < nj
	})

	for i := 0; i < len(segs); i++ {
		s := segs[i]
		n := len(s)

		if n % 2 == 1 {
			break;
		}

		if s[0] == 'A' && AB > 0 {
			if n / 2 > AB {
				segs[i] = segs[i][AB * 2:]
				AB = 0
			}else{
				AB -= n / 2
				segs[i] = ""
			}
		} else if s[0] == 'B' && BA > 0 {
			if n / 2 > BA {
				segs[i] = segs[i][BA * 2 :]
				BA = 0
			}else {
				BA -= n / 2
				segs[i] = ""
			}
		}
	}

	cnt := 0
	for i := 0; i < len(segs); i++ {
		s := segs[i]
		n := len(s)
		cnt += (n - 1)/2
	}

	if cnt < AB + BA {
		return "NO"
	}

	return "YES"

}

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

	fmt.Fscan(in, &T)

	for t := 1; t <= T; t++ {
		fmt.Fscan(in, &A, &B, &AB, &BA)
		fmt.Fscan(in, &S)

		fmt.Println(solve())
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)
var wrtr = bufio.NewWriterSize(os.Stdout, 10_000_000)
var rdr = bufio.NewScanner(os.Stdin)
func gs() string  { rdr.Scan(); return rdr.Text() }
func gi() int     { i,e := strconv.Atoi(gs()); if e != nil {panic(e)}; return i }
func gi2() (int,int) { return gi(),gi() }
func gi3() (int,int,int) { return gi(),gi(),gi() }
func gi4() (int,int,int,int) { return gi(),gi(),gi(),gi() }
func gis(n int) []int  { res := make([]int,n); for i:=0;i<n;i++ { res[i] = gi() }; return res }
func gf() float64 { f,e := strconv.ParseFloat(gs(),64); if e != nil {panic(e)}; return f }
func gbs() []byte { return []byte(gs()) }
func gfs(n int) []float64  { res := make([]float64,n); for i:=0;i<n;i++ { res[i] = gf() }; return res }
func gss(n int) []string  { res := make([]string,n); for i:=0;i<n;i++ { res[i] = gs() }; return res }
func ia(m int) []int { return make([]int,m) }
func iai(m int,v int) []int { a := make([]int,m); for i:=0;i<m;i++ { a[i] = v }; return a }
func twodi(n int,m int,v int) [][]int {
	r := make([][]int,n); for i:=0;i<n;i++ { x := make([]int,m); for j:=0;j<m;j++ { x[j] = v }; r[i] = x }; return r
}
func fill2(m int) ([]int,[]int) { a,b := ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i] = gi(),gi()}; return a,b }
func fill3(m int) ([]int,[]int,[]int) { a,b,c := ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i] = gi(),gi(),gi()}; return a,b,c }
func fill4(m int) ([]int,[]int,[]int,[]int) { a,b,c,d := ia(m),ia(m),ia(m),ia(m); for i:=0;i<m;i++ {a[i],b[i],c[i],d[i] = gi(),gi(),gi(),gi()}; return a,b,c,d }
func abs(a int) int { if a < 0 { return -a }; return a }
func rev(a []int) { i,j := 0,len(a)-1; for i < j { a[i],a[j] = a[j],a[i]; i++; j-- } }
func max(a,b int) int { if a > b { return a }; return b }
func min(a,b int) int { if a > b { return b }; return a }
func tern(cond bool, a int, b int) int { if cond { return a }; return b }
func terns(cond bool, a string, b string) string { if cond { return a }; return b }
func maxarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa > ans { ans = aa } }; return ans }
func minarr(a []int) int { ans := a[0]; for _,aa := range(a) { if aa < ans { ans = aa } }; return ans }
func sumarr(a []int) int { ans := 0; for _,aa := range(a) { ans += aa }; return ans }
func zeroarr(a []int) { for i:=0; i<len(a); i++ { a[i] = 0 } }
func powmod(a,e,mod int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m % mod }; m = m * m % mod; e >>= 1 }; return res }
func powint(a,e int) int { res, m := 1, a; for e > 0 { if e&1 != 0 { res = res * m }; m = m * m; e >>= 1 }; return res }
func gcd(a,b int) int { for b != 0 { t:=b; b=a%b; a=t }; return a }
func gcdExtended(a,b int) (int,int,int) { if a == 0 { return b,0,1 }; gcd,x1,y1 := gcdExtended(b%a,a); return gcd, y1-(b/a)*x1,x1 }
func modinv(a,m int) (int,bool) { g,x,_ := gcdExtended(a,m); if g != 1 { return 0,false }; return (x % m + m) % m,true  }
func makefact(n int,mod int) ([]int,[]int) {
	fact,factinv := make([]int,n+1),make([]int,n+1)
	fact[0] = 1; for i:=1;i<=n;i++ { fact[i] = fact[i-1] * i % mod }
	factinv[n] = powmod(fact[n],mod-2,mod); for i:=n-1;i>=0;i-- { factinv[i] = factinv[i+1] * (i+1) % mod }
	return fact,factinv
}
func vecintstring(a []int) string { astr := make([]string,len(a)); for i,a := range a { astr[i] = strconv.Itoa(a) }; return strings.Join(astr," ") }
func main() {
	//f1, _ := os.Create("cpu.prof"); pprof.StartCPUProfile(f1); defer pprof.StopCPUProfile()
	defer wrtr.Flush()
	infn := ""; if infn == "" && len(os.Args) > 1 {	infn = os.Args[1] }
	if infn != "" {	f, e := os.Open(infn); if e != nil { panic(e) }; rdr = bufio.NewScanner(f) }
	rdr.Split(bufio.ScanWords); rdr.Buffer(make([]byte,1024),1_000_000_000)
	// PROGRAM STARTS HERE
	T := gi()
	for tt:=1;tt<=T;tt++ {
		a,b,c,d := gi(),gi(),gi(),gi(); s := gs()
		N := len(s)
		cnta,cntb := 0,0; for _,c := range s { if c == 'A' { cnta++ } else { cntb++ } }
		if cnta != a + c + d || cntb != b + c + d { fmt.Fprintln(wrtr,"NO"); continue }
		idx := 0
		evena,evenb,odd := ia(0),ia(0),ia(0)
		for idx < N {
			for idx+1 < N && s[idx] == s[idx+1] { idx++ }; if idx >= N-1 { break }
			idx2 := idx+1; for idx2 < N && s[idx2] != s[idx2-1] { idx2++ }
			if (idx2-idx) % 2 == 1 {
				odd = append(odd,(idx2-idx-1)/2)
			} else if s[idx] == 'A' {
				evena = append(evena,(idx2-idx)/2)
			} else {
				evenb = append(evenb,(idx2-idx)/2)
			}
			idx = idx2
		}
		cc,dd := c,d
		sort.Slice(evena,func(i,j int) bool { return evena[i] < evena[j] } )
		sort.Slice(evenb,func(i,j int) bool { return evenb[i] < evenb[j] } )
		for _,x := range evena { if x <= cc { cc -= x } else { x -= cc+1; cc = 0; if x > 0 { odd = append(odd,x) } } }
		for _,x := range evenb { if x <= dd { dd -= x } else { x -= dd+1; dd = 0; if x > 0 { odd = append(odd,x) } } }
		sumodd := sumarr(odd)
		if sumodd >= cc + dd { fmt.Fprintln(wrtr,"YES") } else { fmt.Fprintln(wrtr,"NO") }
	}
}


package main

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

type (
	input struct{ n int }
	guess struct{ ans []int64 }
	qIn   struct{ q []int }
	qOut  struct{ or int64 }
)

// github.com/EndlessCheng/codeforces-go
func run(in input, _Q func(qIn) qOut) (gs guess) {
	n := in.n
	mask6 := make([]uint, n)
	qs := [13][]int{}
	x := uint(0)
	for i := range mask6 {
		for x++; bits.OnesCount(x) != 6; x++ {
		}
		mask6[i] = x
		for j := range qs {
			if x>>j&1 == 0 {
				qs[j] = append(qs[j], i+1)
			}
		}
	}
	or := [13]int64{}
	for i, q := range qs {
		if len(q) > 0 {
			or[i] = _Q(qIn{q}).or
		}
	}
	a := make([]int64, n)
	for i, v := range mask6 {
		for j, o := range or {
			if v>>j&1 > 0 {
				a[i] |= o
			}
		}
	}
	gs.ans = a
	return
}

func ioq() {
	in := bufio.NewReader(os.Stdin)
	out := os.Stdout
	Q := func(q qIn) (resp qOut) {
		Fprint(out, "? ", len(q.q))
		for _, v := range q.q {
			Fprint(out, " ", v)
		}
		Fprintln(out)
		//out.Flush()
		Fscan(in, &resp.or)
		return
	}
	d := input{}
	Fscan(in, &d.n)
	gs := run(d, Q)
	Fprint(out, "!")
	for _, v := range gs.ans {
		Fprint(out, " ", v)
	}
	Fprintln(out)
	//out.Flush()
}

func main() { ioq() }

package main

import (
	. "fmt"
	"math/bits"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	n := 0
	Scan(&n)
	m := make([]uint, n)
	qs := [13][]interface{}{}
	x := uint(0)
	for i := range m {
		for x++; bits.OnesCount(x) != 6; x++ {
		}
		m[i] = x
		for j := range qs {
			if x>>j&1 == 0 {
				qs[j] = append(qs[j], i+1)
			}
		}
	}
	or := [13]int64{}
	for i, q := range qs {
		if len(q) > 0 {
			Print("? ", len(q), " ")
			Println(q...)
			Scan(&or[i])
		}
	}
	Print("!")
	for _, v := range m {
		a := int64(0)
		for j, o := range or {
			if v>>j&1 > 0 {
				a |= o
			}
		}
		Print(" ", a)
	}
	Println()
}

package main

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

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

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

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

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

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

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

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

	return i
}

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

	n := readNum(reader)

	var buf bytes.Buffer

	query := func(arr []int) uint64 {
		m := len(arr)

		buf.WriteString(fmt.Sprintf("? %d", m))

		for i := 0; i < len(arr); i++ {
			buf.WriteString(fmt.Sprintf(" %d", arr[i]))
		}
		fmt.Println(buf.String())
		buf.Reset()

		s, _ := reader.ReadBytes('\n')
		var r uint64
		readUint64(s, 0, &r)
		return r
	}

	res := solve(n, query)

	buf.WriteString("!")

	for i := 0; i < n; i++ {
		buf.WriteString(fmt.Sprintf(" %d", res[i]))
	}
	fmt.Println(buf.String())
}

const Q = 13

func solve(n int, query func([]int) uint64) []uint64 {

	ask := make([][]int, Q)

	for i := 0; i < Q; i++ {
		ask[i] = make([]int, 0, n)
	}

	masks := make([]int, n+1)

	var assigned int
	for i := 1; i < 1<<Q && assigned < n; i++ {
		if popCount(i) != Q/2 {
			continue
		}
		masks[assigned] = i

		for j := 0; j < Q; j++ {
			if i>>j&1 == 0 {
				ask[j] = append(ask[j], assigned+1)
			}
		}

		assigned++
	}

	val := make([]uint64, Q)

	for i := 0; i < Q; i++ {
		if len(ask[i]) > 0 {
			val[i] = query(ask[i])
		}
	}

	ans := make([]uint64, n)

	for i := 0; i < n; i++ {
		for j := 0; j < Q; j++ {
			if masks[i]>>j&1 == 1 {
				ans[i] |= val[j]
			}
		}
	}

	return ans
}

func popCount(num int) int {
	var res int

	for num > 0 {
		res += num & 1
		num >>= 1
	}

	return res
}

package main

import (
	. "fmt"
	"math/bits"
)

// github.com/EndlessCheng/codeforces-go
func main() {
	n := 0
	Scan(&n)
	m := make([]uint, n)
	qs := [13][]int{}
	x := uint(0)
	for i := range m {
		for x++; bits.OnesCount(x) != 6; x++ {
		}
		m[i] = x
		for j := range qs {
			if x>>j&1 == 0 {
				qs[j] = append(qs[j], i+1)
			}
		}
	}
	or := [13]int64{}
	for i, q := range qs {
		if len(q) > 0 {
			Print("? ", len(q))
			for _, v := range q {
				Print(" ", v)
			}
			Println()
			Scan(&or[i])
		}
	}
	Print("!")
	for _, v := range m {
		a := int64(0)
		for j, o := range or {
			if v>>j&1 > 0 {
				a |= o
			}
		}
		Print(" ", a)
	}
	Println()
}

package main

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

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

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

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

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

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

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

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

	return i
}

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

	n := readNum(reader)

	var buf bytes.Buffer

	query := func(arr []int) int {
		m := len(arr)

		buf.WriteString(fmt.Sprintf("? %d", m))

		for i := 0; i < len(arr); i++ {
			buf.WriteString(fmt.Sprintf(" %d", arr[i]))
		}
		fmt.Println(buf.String())
		buf.Reset()
		return readNum(reader)
	}

	res := solve(n, query)

	buf.WriteString("!")

	for i := 0; i < n; i++ {
		buf.WriteString(fmt.Sprintf(" %d", res[i]))
	}
	fmt.Println(buf.String())
}

const Q = 13

func solve(n int, query func([]int) int) []int {

	ask := make([][]int, Q)

	for i := 0; i < Q; i++ {
		ask[i] = make([]int, 0, n)
	}

	masks := make([]int, n+1)

	var assigned int
	for i := 1; i < 1<<Q && assigned < n; i++ {
		if popCount(i) != Q/2 {
			continue
		}
		masks[assigned] = i

		for j := 0; j < Q; j++ {
			if i>>j&1 == 0 {
				ask[j] = append(ask[j], assigned+1)
			}
		}

		assigned++
	}

	val := make([]int, Q)

	for i := 0; i < Q; i++ {
		if len(ask[i]) > 0 {
			val[i] = query(ask[i])
		}
	}

	ans := make([]int, n)

	for i := 0; i < n; i++ {
		for j := 0; j < Q; j++ {
			if masks[i]>>j&1 == 1 {
				ans[i] |= val[j]
			}
		}
	}

	return ans
}

func popCount(num int) int {
	var res int

	for num > 0 {
		res += num & 1
		num >>= 1
	}

	return res
}