Posterize
InterviewTime limit2sMemory limit512 MB
Choose k allowed red values so the weighted sum of squared distances from the d distinct intensities is minimized.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Math, Sorting, Prefix sum
- Solved
- No attempts yet
Problem

A pixel in a digital picture is represented by three integers from 0 to 255 that give the intensity of red, green, and blue. To compress an image or to create an artistic effect, many photo editing tools include a posterize operation. Each color channel is handled separately, and this problem deals only with the red channel.
The red channel of a posterized image does not use every integer from 0 to 255, only at most of them. The original red intensity of each pixel is replaced by the nearest allowed integer. The editing tool picks the integers so that the sum of the squared errors over all pixels of the original image is as small as possible. If the pixels have original red values and the allowed integers are , the sum of squared errors is defined as
Given and the red intensities of the image's pixels, compute the minimum achievable sum of squared errors.
Input
The first line contains the number of distinct red values that occur in the original image, (), and the number of red values allowed in the posterized image, ().
Each of the next lines contains a red intensity () and the number of pixels whose red intensity is , (), separated by a space. Those lines are given in increasing order of red value.
Output
Print the sum of the squared errors for an optimally chosen set of allowed integers.