Painting stones#5

Painting stones (Editorial)

Problem Author:

Oleksandr Tymkovich

Prepared by:

Oleksandr Tymkovich

Editorial by:

Oleksandr Tymkovich

Solution for n\le 1\,000:

Let's iterate over the color in which all the stones will be painted in the end. To find the minimum number of paintings for a certain color, you can follow the following greedy algorithm:

  • if the color of the stone is the one we are iterating over, then move on;

  • otherwise, paint the current stone and the next one in the color we are iterating over.

Full solution:

Let's assume we are iterating over the color . For which minimum number of operations can we paint the segment [l,r] where the end stones are of color , and there are no other stones of color except the end ones? From the algorithm for the solution n\le 1000, the answer is \lfloor \frac{r-l}{2} \rfloor.

We can divide the array into such segments, and the overall answer for the color is the sum of the answers for each segment. (Also, don't forget that you may need to paint the prefix and suffix).

So the solution is to calculate each color separately. For the color , we have provided an algorithm with a complexity of where is the number of occurrences of the number in the array. In total, for all colors, the solution has a complexity of .