Solution
Every string that can appear during the process is a prefix of .
Let be the minimum cost needed to obtain the prefix of of length .
Initially,
There are two possible transitions.
Appending one character
Suppose the current prefix has length .
Appending the next character makes its length equal to x+1, and the cost of this operation is x+1.
Therefore,
Applying the transformation
Suppose the current string is
Let
Every character A produces two characters, while every character B produces one character.
Therefore,
After applying the operation, the new string becomes
so its length becomes
The operation is valid exactly when
Now construct
Since the transformation is applied independently to every character,
is exactly the prefix of of length L_x.
Thus, we only need to check whether
This is a longest common prefix query between and the suffix of starting from position x+1.
Construct the string
where # is a character different from A and B, and calculate its Z-function.
The Z-value corresponding to position x+1 in gives the length of the common prefix between and
Therefore, the transformation is possible exactly when
and the corresponding Z-value is at least L_x.
Then we can perform the transition
The answer is .
Correctness
Every reachable string is a prefix of , so it is enough to store only its length.
From a prefix of length , there are exactly two possible operations: append one character or apply the transformation.
The first DP transition handles the append operation.
For the second operation, the Z-function checks exactly whether f(t_1t_2\dots t_x) appears immediately after the current prefix.
Therefore, every valid transition is considered and no invalid transition is added.
Hence, is the minimum possible cost of obtaining the prefix of length , and is the required answer.
Complexity
The string has length at most .
Building , calculating prefix counts, and calculating the Z-function all take time.
Every DP state has at most two transitions.
Therefore, the total complexity is
time and
memory.