Under construction

Still being built. Things may change

Pseudo-Banana Strings

Interview

Time limit2sMemory limit512 MB

Summary
Given a string of B, A, N, find the minimum number of character replacements that turn it into a concatenation of blocks of the form B+ANANA(NA)*.
Level

Medium6 of 10

Topics
Dynamic programming, String, Implementation, Greedy
Solved
No attempts yet

Problem

A pseudo-banana is defined by the following rules:

  • BANANABANANA is a pseudo-banana.
  • For a pseudo-banana XX, BXBX with BB prepended is also a pseudo-banana.
  • For a pseudo-banana XX, XNAXNA with NANA appended is also a pseudo-banana.

Hence every pseudo-banana has the form BaANANA(NA)tB^{a}ANANA(NA)^{t} with integers a>=1a >= 1 and t>=0t >= 0, and its length is a+5+2ta + 5 + 2t.

A pseudo-banana string is a concatenation of one or more pseudo-bananas. Given a string over BB, AA and NN, determine the minimum number of character replacements needed to turn it into a pseudo-banana string.

Input

A string SS of length MM is given on one line. SS consists only of the characters BB, AA and NN. MM satisfies 6<=M<=1000006 <= M <= 100000.

Output

Print on one line the minimum number of character replacements needed to turn the given string into a pseudo-banana string. Every input with length at least 6 admits such a string, so an answer always exists.

Hint

One pseudo-banana consists of one or more BB characters, followed by ANANAANANA, followed by zero or more repetitions of NANA. A full string is a repetition of such blocks, where after a block boundary either the BB starting the next block or the NN continuing the tail may appear.

This structure can be expressed as a deterministic finite automaton with 8 states. Matching the input against it reduces to dynamic programming that keeps, for each position, the cheapest cost of reaching every state.

Examples2

  1. Example 1

    Input
    BANANANABBANANA
    
    Expected output
    0
    
  2. Example 2

    Input
    BANANANAA
    
    Expected output
    7