Editorial for COCI '11 Contest 5 #3 Dna
Submitting an official solution before solving the problem yourself is a bannable offence.
This task can be solved using dynamic programming. Let  be the smallest number of mutations needed to convert the first 
 characters to 
A. Conversely, let  be the smallest number of mutations needed to convert the first 
 characters to 
B.
If the  character is already equal to 
A, then obviously .
On the other hand, if the  character is equal to 
B, we have two options:
Change the
characters using a first-type mutation, giving
mutations;
Change the prefix of length
(second-type mutation); in this case, we first need to convert the first
characters to
B(in order to convert them all toAusing the prefix mutation), which requiresmutations, resulting in a total of
mutations.
Therefore, if the  character is equal to 
B, then .
We also need to derive analogous relations for .
Now the problem can be easily solved by calculating , 
, 
, 
 and so on until obtaining the result 
.
The problem has another, simpler solution. We can iterate over the string backwards, converting each encountered character to A. If we find an A, we can simply continue. However, if we find a B, we have to decide which mutation to use. It turns out that a correct strategy is to look at the character in front of B. If A precedes the current B, then we convert only the B, and if another B precedes the current B, we convert the whole prefix. The proof of correctness of this algorithm, as well as a trick to quickly flip the whole prefix, is left as an exercise to the reader.
Comments