杂题——ABBC or BACB
ABBC or BACB
You are given a string $s$ made up of characters $\texttt{A}$ and $\texttt{B}$. Initially you have no coins. You can perform two types of operations:
- Pick a substring$^\dagger$ $\texttt{AB}$, change it to $\texttt{BC}$, and get a coin.
- Pick a substring$^\dagger$ $\texttt{BA}$, change it to $\texttt{CB}$, and get a coin.
What is the most number of coins you can obtain?
$^\dagger$ A substring of length $2$ is a sequence of two adjacent characters of a string.
Input
The input consists of multiple test cases. The first line of the input contains a single integer $t$ ($1 \leq t \leq 1000$) — the number of test cases.
The only line of each test case contains the string $s$ ($1 \leq |s| \leq 2 \cdot 10^5$). All characters of $s$ are either $\texttt{A}$ or $\texttt{B}$.
The sum of the lengths of $s$ over all test cases does not exceed $2 \cdot 10^5$.
Output
For each test case, output a single integer — the maximum number of coins you can obtain.
Example
input
1 |
|
output
1 |
|
Note
In the first test case you can perform the following operations to get $2$ coins:
$$
\color{red}{\texttt{AB}}\texttt{BA} \to \texttt{BC}\color{red}{\texttt{BA}} \to \texttt{BCCB}
$$
In the second test case you can perform the following operation to get $1$ coin:
$$
\color{red}{\texttt{AB}}\texttt{A} \to \texttt{BCA}
$$
In the third test case you can perform the following operations to get $3$ coins:
$$
\color{red}{\texttt{BA}}\texttt{ABA} \to \texttt{CBA}\color{red}{\texttt{BA}} \to \texttt{C}\color{red}{\texttt{BA}}\texttt{CB} \to \texttt{CCBCB}
$$
翻译
您将获得一个由字符 $\texttt{A}$ 和 $\texttt{B}$ 组成的字符串 $s$ 。最初你没有硬币。您可以执行两种类型的操作:
- 选择一个子字符串 $^\dagger$ $\texttt{AB}$ ,将其更改为 $\texttt{BC}$ ,并获得一枚硬币。
- 选择一个子字符串 $^\dagger$ $\texttt{BA}$ ,将其更改为 $\texttt{CB}$ ,然后获得一枚硬币。
您最多可以获得多少金币?
$^\dagger$ 长度为 $2$ 的子字符串是字符串的两个相邻字符的序列。
输入
输入由多个测试用例组成。输入的第一行包含一个整数 $t$ ( $1 \leq t \leq 1000$ ) - 测试用例的数量。
每个测试用例的唯一行包含字符串 $s$ ( $1 \leq |s| \leq 2 \cdot 10^5$ )。 $s$ 的所有字符都是 $\texttt{A}$ 或 $\texttt{B}$ 。
所有测试用例的 $s$ 的长度总和不超过 $2 \cdot 10^5$ 。
输出
对于每个测试用例,输出一个整数——您可以获得的最大硬币数量。
Example
input
1 |
|
output
1 |
|
笔记
在第一个测试用例中,您可以执行以下操作来获取 $2$ 币:
$$
\color{red}{\texttt{AB}}\texttt{BA} \to \texttt{BC}\color{red}{\texttt{BA}} \to \texttt{BCCB}
$$
在第二个测试用例中,您可以执行以下操作来获取 $1$ 币:
$$
\color{red}{\texttt{AB}}\texttt{A} \to \texttt{BCA}
$$
在第三个测试用例中,您可以执行以下操作来获取 $3$ 币:
$$
\color{red}{\texttt{BA}}\texttt{ABA} \to \texttt{CBA}\color{red}{\texttt{BA}} \to \texttt{C}\color{red}{\texttt{BA}}\texttt{CB} \to \texttt{CCBCB}
$$
思路
推论一、每个B都可以使它的左右任意一边的A都变成硬币,例如AAAB,可以从左开始变,变成3个硬币
推论一继续延申
1.只要有n个B,就可以使N个区间内的A变成硬币(有多少A就有多少硬币)
2. 以AAB….BA为例,需要舍去最小A区间。
3.如果两个B相连,则可以获得所有A。如…AAA BB AAA…
4.B在开头或者结尾,也都可以获得所有A。以B开头为例,所有B只要清空右边的A,即可
代码
1 |
|