This page is still under construction.

Parts of this page are still being built. What you see may change.

Arranging Heaps

Time limit2sMemory limit128 MB

Summary
Given N heaps at increasing positions with weights, merge them into exactly K heaps where each heap moves only downriver, minimizing total weight times distance moved.
Level

Medium7 of 10

Topics
Dynamic programming, Divide and conquer, Prefix sum, Greedy
Solved
No attempts yet

Problem

A mining company extracts a rare metal from river sand at NN mining points along the Long River. Each mining point is identified by its distance from the river's source, and produces one heap of mineral ore.

To collect the ore, the company regroups the NN heaps into a smaller number of KK heaps, each located at one of the original mining points. A very large barge does the moving: it starts at the source and can only travel downriver, so a heap produced at mining point XX may be carried to mining point YY only if Y>XY > X. Each heap is either moved in full to another mining point or left in place. Moving a heap of weight WW from mining point XX to mining point YY costs W×(Y−X)W \times (Y - X); a heap left in place adds nothing to the cost. The total regrouping cost is the sum of the costs of all heap movements.

Given NN, KK, the positions of the mining points, and the weight produced at each, compute the minimum total cost to regroup the NN heaps into exactly KK heaps.

Input

The input contains several test cases; process test cases until the end of input.

Each test case begins with a line containing two integers NN and KK (1≤K<N≤10001 \le K < N \le 1000): the number of initial heaps and the desired number of heaps after regrouping. Each of the next NN lines contains two integers XX and WW (1≤X,W≤1061 \le X, W \le 10^6), meaning that a heap of weight WW was produced at mining point XX. Within a test case the heaps are listed in strictly increasing order of their positions XX.

Output

For each test case, output a single line containing one integer: the minimum total cost to regroup the NN heaps into KK heaps.

Examples2

  1. Example 1

    Input
    3 1
    20 1
    30 1
    40 1
    3 1
    11 3
    12 2
    13 1
    6 2
    10 15
    12 17
    16 18
    18 13
    30 10
    32 1
    6 3
    10 15
    12 17
    16 18
    18 13
    30 10
    32 1
    
    Expected output
    30
    8
    278
    86
    
  2. Example 2

    Input
    2 1
    5 10
    8 3
    
    Expected output
    30