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.

We can use dynamic programming to solve this task. Let Ai be the color of the ith marble. Let our state be described with 3 items: (l,r,count) that gives the minimal number of marbles we need to insert into subsequence {Al,Al+1,,Ar} so that it disappears, with the added bonus that we can insert count copies of marble Al on the beginning of the sequence.

For example, let A={1,3,3,3,2,3,1,1,1,3}. State [0][4][3] denotes the minimal number of marbles we need to insert into {1,1,1,1,3,3,3,2} 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 [l][r][X]=[l][r][X+1]+1.
  • If X=k1, we can delete all marbles on the beginning of the sequence, including the first marble of our subsequence. This gives [l][r][X]=[l+1][r][0] for X=k1.
  • Third and most complex case is merging the first marble with some later marble. We expect to merge our first marble (Al) with some marble Aj assuming Al=Aj. This merger gives [l][r][X]=[l+1][j1][0]+[j][r][X+1].

For each state, we must of course find the minimum of all possible transitions.


Comments

There are no comments at the moment.