Editorial for COCI '09 Contest 5 #4 Zuma
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
We can use dynamic programming to solve this task. Let be the color of the marble. Let our state be described with 3 items: that gives the minimal number of marbles we need to insert into subsequence so that it disappears, with the added bonus that we can insert copies of marble on the beginning of the sequence.
For example, let . State denotes the minimal number of marbles we need to insert into so that the entire subsequence disappears.
There are three transitions for each state:
- Add a duplicate of the first marble to the beginning of the sequence. This gives .
- If , we can delete all marbles on the beginning of the sequence, including the first marble of our subsequence. This gives for .
- Third and most complex case is merging the first marble with some later marble. We expect to merge our first marble () with some marble assuming . This merger gives .
For each state, we must of course find the minimum of all possible transitions.
Comments