← Home
package main

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

func main() {
	data, _ := io.ReadAll(os.Stdin)
	idx := 0

	nextInt := func() int {
		for idx < len(data) && data[idx] <= ' ' {
			idx++
		}
		sign := 1
		if idx < len(data) && data[idx] == '-' {
			sign = -1
			idx++
		}
		val := 0
		for idx < len(data) && data[idx] >= '0' && data[idx] <= '9' {
			val = val*10 + int(data[idx]-'0')
			idx++
		}
		return sign * val
	}

	nextString := func() string {
		for idx < len(data) && data[idx] <= ' ' {
			idx++
		}
		start := idx
		for idx < len(data) && data[idx] > ' ' {
			idx++
		}
		return string(data[start:idx])
	}

	t := nextInt()
	const neg = -1 << 30
	var out strings.Builder

	for ; t > 0; t-- {
		s := nextString()
		n := len(s)

		weights := make([]int, 0, n+1)
		caps := make([]int, 0, n)

		i := 0
		a := 0
		for i < n && s[i] == 'A' {
			a++
			i++
		}
		weights = append(weights, a)

		for i < n {
			b := 0
			for i < n && s[i] == 'B' {
				b++
				i++
			}
			if b == 1 {
				caps = append(caps, 1)
			} else {
				caps = append(caps, 2)
			}
			a = 0
			for i < n && s[i] == 'A' {
				a++
				i++
			}
			weights = append(weights, a)
		}

		m := len(caps)
		if m == 0 {
			out.WriteString("0\n")
			continue
		}

		dp0, dp1 := neg, neg
		for l := 0; l <= 1; l++ {
			for r := 0; r <= 1; r++ {
				if l+r > caps[0] {
					continue
				}
				score := 0
				if l == 1 {
					score += weights[0]
				}
				if r == 0 {
					if score > dp0 {
						dp0 = score
					}
				} else {
					if score > dp1 {
						dp1 = score
					}
				}
			}
		}

		for i = 1; i < m; i++ {
			ndp0, ndp1 := neg, neg
			for l := 0; l <= 1; l++ {
				for r := 0; r <= 1; r++ {
					if l+r > caps[i] {
						continue
					}
					if dp0 != neg {
						score := dp0
						if l == 1 {
							score += weights[i]
						}
						if r == 0 {
							if score > ndp0 {
								ndp0 = score
							}
						} else {
							if score > ndp1 {
								ndp1 = score
							}
						}
					}
					if dp1 != neg {
						score := dp1 + weights[i]
						if r == 0 {
							if score > ndp0 {
								ndp0 = score
							}
						} else {
							if score > ndp1 {
								ndp1 = score
							}
						}
					}
				}
			}
			dp0, dp1 = ndp0, ndp1
		}

		ans := dp0
		if dp1+weights[m] > ans {
			ans = dp1 + weights[m]
		}
		out.WriteString(strconv.Itoa(ans))
		out.WriteByte('\n')
	}

	os.Stdout.WriteString(out.String())
}