Skip to lesson

Fewest swaps to group present days

A hard problem for practising 5.4 Array & String Techniques. Solve it in your own IDE, check it against every test, and open a hint only when you are stuck. 0/1 solved.

1. Fewest swaps to group present days

hard

A class rep draws a student's attendance as a ring of n cells, one per day, each marked P (present) or A (absent). Because it is a ring, the last cell sits next to the first cell.

For a poster, she wants all the P cells to form one unbroken block on the ring. In one swap she may exchange the marks of any two cells. Print the fewest swaps she needs. If the P cells already form one block, or there are no P cells, print 0.

Input: One line with a string of n letters, each P or A.

Output: One integer: the fewest swaps.

Limits: 1 ≤ n ≤ 10^5 · Every letter is P or A

Example 1

Input

PAPAAP

Output

1

Swap cells 2 and 3 to get PPAAAP. The last cell is next to the first, so PPP is one block on the ring.

Example 2

Input

PAPAPAPA

Output

2

Any block of 4 cells holds only 2 P, so 2 swaps are needed.

Submit to solve