The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings:   $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$);  $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$);  $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.

Print one integer — the number of good substrings of string $$$s$$$.

NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.

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"
	"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 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はとったか？
// 遷移だけじゃなくて最後の最後でちゃんと取れよ？

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


While performing complex market analysis William encountered the following problem:For a given array $$$a$$$ of size $$$n$$$ and a natural number $$$e$$$, calculate the number of pairs of natural numbers $$$(i, k)$$$ which satisfy the following conditions:   $$$1 \le i, k$$$  $$$i + e \cdot k \le n$$$.  Product $$$a_i \cdot a_{i + e} \cdot a_{i + 2 \cdot e} \cdot \ldots \cdot a_{i + k \cdot e} $$$ is a prime number. A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$e$$$ $$$(1 \le e \le n \le 2 \cdot 10^5)$$$, the number of items in the array and number $$$e$$$, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6)$$$, the contents of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output the answer in the following format: Output one line containing the number of pairs of numbers $$$(i, k)$$$ which satisfy the conditions.

NoteIn the first example test case two pairs satisfy the conditions:   $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{5} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 19$$$ which is a prime number. In the second example test case there are no pairs that satisfy the conditions.In the third example test case four pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{4} \cdot a_{7} = 2$$$ which is a prime number.  $$$i = 3, k = 1$$$, for which the product is: $$$a_{3} \cdot a_{6} = 2$$$ which is a prime number.  $$$i = 6, k = 1$$$, for which the product is: $$$a_{6} \cdot a_{9} = 2$$$ which is a prime number. In the fourth example test case there are no pairs that satisfy the conditions.In the fifth example test case five pairs satisfy the conditions:   $$$i = 1, k = 1$$$, for which the product is: $$$a_{1} \cdot a_{2} = 2$$$ which is a prime number.  $$$i = 1, k = 2$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 1, k = 3$$$, for which the product is: $$$a_{1} \cdot a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number.  $$$i = 2, k = 1$$$, for which the product is: $$$a_{2} \cdot a_{3} = 2$$$ which is a prime number.  $$$i = 2, k = 2$$$, for which the product is: $$$a_{2} \cdot a_{3} \cdot a_{4} = 2$$$ which is a prime number. In the sixth example test case there are no pairs that satisfy the conditions.

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"
	"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 := 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
}


There are $$$n$$$ trees in a park, numbered from $$$1$$$ to $$$n$$$. The initial height of the $$$i$$$-th tree is $$$h_i$$$.You want to water these trees, so they all grow to the same height.The watering process goes as follows. You start watering trees at day $$$1$$$. During the $$$j$$$-th day you can:   Choose a tree and water it. If the day is odd (e.g. $$$1, 3, 5, 7, \dots$$$), then the height of the tree increases by $$$1$$$. If the day is even (e.g. $$$2, 4, 6, 8, \dots$$$), then the height of the tree increases by $$$2$$$.  Or skip a day without watering any tree. Note that you can't water more than one tree in a day. Your task is to determine the minimum number of days required to water the trees so they grow to the same height.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of trees. The second line of the test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$ ($$$\sum n \le 3 \cdot 10^5$$$).

For each test case, print one integer — the minimum number of days required to water the trees, so they grow to the same height.

NoteConsider the first test case of the example. The initial state of the trees is $$$[1, 2, 4]$$$.  During the first day, let's water the first tree, so the sequence of heights becomes $$$[2, 2, 4]$$$;  during the second day, let's water the second tree, so the sequence of heights becomes $$$[2, 4, 4]$$$;  let's skip the third day;  during the fourth day, let's water the first tree, so the sequence of heights becomes $$$[4, 4, 4]$$$. Thus, the answer is $$$4$$$.

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

}


Alina has discovered a weird language, which contains only $$$4$$$ words: $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence $$$s$$$ and she is curious: is it possible that it consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$?In other words, determine, if it's possible to concatenate these $$$a+b+c+d$$$ words in some order so that the resulting string is $$$s$$$. Each of the $$$a+b+c+d$$$ words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0\le a,b,c,d\le 2\cdot 10^5$$$) — the number of times that words $$$\texttt{A}$$$, $$$\texttt{B}$$$, $$$\texttt{AB}$$$, $$$\texttt{BA}$$$ respectively must be used in the sentence. The second line contains the string $$$s$$$ ($$$s$$$ consists only of the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$, $$$1\le |s| \le 2\cdot 10^5$$$, $$$|s|=a+b+2c+2d$$$)  — the sentence. Notice that the condition $$$|s|=a+b+2c+2d$$$ (here $$$|s|$$$ denotes the length of the string $$$s$$$) is equivalent to the fact that $$$s$$$ is as long as the concatenation of the $$$a+b+c+d$$$ words. The sum of the lengths of $$$s$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case output $$$\texttt{YES}$$$ if it is possible that the sentence $$$s$$$ consists of precisely $$$a$$$ words $$$\texttt{A}$$$, $$$b$$$ words $$$\texttt{B}$$$, $$$c$$$ words $$$\texttt{AB}$$$, and $$$d$$$ words $$$\texttt{BA}$$$, and $$$\texttt{NO}$$$ otherwise. You can output each letter in any case.

8
1 0 0 0
B
0 0 1 0
AB
1 1 0 1
ABAB
1 0 1 1
ABAAB
1 1 2 2
BAABBABBAA
1 1 2 3
ABABABBAABAB
2 3 5 4
AABAABBABAAABABBABBBABB
1 3 3 10
BBABABABABBBABABABABABABAABABA

NoteIn the first test case, the sentence $$$s$$$ is $$$\texttt{B}$$$. Clearly, it can't consist of a single word $$$\texttt{A}$$$, so the answer is $$$\texttt{NO}$$$.In the second test case, the sentence $$$s$$$ is $$$\texttt{AB}$$$, and it's possible that it consists of a single word $$$\texttt{AB}$$$, so the answer is $$$\texttt{YES}$$$.In the third test case, the sentence $$$s$$$ is $$$\texttt{ABAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}$$$.In the fourth test case, the sentence $$$s$$$ is $$$\texttt{ABAAB}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{AB}$$$, and one word $$$\texttt{BA}$$$, as $$$\texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}$$$. In the fifth test case, the sentence $$$s$$$ is $$$\texttt{BAABBABBAA}$$$, and it's possible that it consists of one word $$$\texttt{A}$$$, one word $$$\texttt{B}$$$, two words $$$\texttt{AB}$$$, and two words $$$\texttt{BA}$$$, as $$$\texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}$$$.

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