#P7767. Minimum Operations to Convert Sequence to A

    ID: 20953 Type: Default 1000ms 256MiB

Minimum Operations to Convert Sequence to A

Minimum Operations to Convert Sequence to A

You are given a sequence of N letters, where each letter is either $A$ or $B$. You want to transform the sequence so that every character is $A$.

You can perform the following two types of operations:

  1. Single flip: Change any one character (i.e. $A\to B$ or $B\to A$).
  2. Prefix flip: Choose an integer $K$ with $1\le K\le N$, and for each index $i$ from $1$ to $K$, change the $i$-th character as in operation 1.

Determine the minimum number of operations required to make the entire sequence consist of $A$'s.

Hint: One obvious strategy is to flip each $B$ individually, which costs the number of $B$'s. However, a prefix flip may flip several $B$'s at once. An approach inspired by the pancake flipping problem shows that using a prefix flip strategy, the minimum number of prefix flips needed is given by the formula:

[ \text{prefixFlips} = \text{(number of transitions)} + \begin{cases}1,&\text{if the last character is }B,\0,&\text{otherwise.}\end{cases} ]

The answer is the minimum between flipping each $B$ individually and using the prefix flip strategy.

inputFormat

The input consists of a single line containing a non-empty string of length $N$ ($1 \le N \le 10^5$), made up of characters 'A' and 'B' only.

outputFormat

Output a single integer, the minimum number of operations required to convert the sequence into all $A$'s.

sample

B
1