Under construction

Still being built. Things may change

Posterize

Interview

Time limit2sMemory limit512 MB

Summary
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 kk of them. The original red intensity of each pixel is replaced by the nearest allowed integer. The editing tool picks the kk integers so that the sum of the squared errors over all pixels of the original image is as small as possible. If the nn pixels have original red values r1,…,rnr_1, \dots, r_n and the allowed integers are v1,…,vkv_1, \dots, v_k, the sum of squared errors is defined as

∑i=1nmin⁡1≤j≤k(ri−vj)2\sum_{i=1}^{n} \min_{1 \le j \le k} (r_i - v_j)^2

Given kk 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, dd (1≤d≤2561 \le d \le 256), and the number of red values allowed in the posterized image, kk (1≤k≤d1 \le k \le d).

Each of the next dd lines contains a red intensity rr (0≤r≤2550 \le r \le 255) and the number of pixels whose red intensity is rr, pp (1≤p≤2261 \le p \le 2^{26}), separated by a space. Those dd lines are given in increasing order of red value.

Output

Print the sum of the squared errors for an optimally chosen set of kk allowed integers.

Examples3

  1. Example 1

    Input
    2 1
    50 20000
    150 10000
    
    Expected output
    66670000
    
  2. Example 2

    Input
    2 2
    50 20000
    150 10000
    
    Expected output
    0
    
  3. Example 3

    Input
    4 2
    0 30000
    25 30000
    50 30000
    255 30000
    
    Expected output
    37500000