Under construction

Still being built. Things may change

Circular Barn Revisited

Time limit2sMemory limit512 MB

Summary
Farmer John opens k doors on a ring of n rooms so cows walking clockwise to their assigned rooms travel the smallest total distance.
Level

Medium7 of 10

Topics
Dynamic programming, Prefix sum, Intervals
Solved
No attempts yet

Problem

Farmer John's circular barn is a ring of nn rooms, numbered 11 through nn clockwise around the perimeter. Each room has inner doors to its two neighbours and one door to the outside.

Farmer John wants exactly rir_i cows to end up in room ii. To herd them in an orderly way he unlocks only kk of the exterior doors, and every cow enters through one of those. Once inside, a cow walks clockwise until it reaches its room, so a cow that enters at the door of room dd and settles in room ii walks a distance of (i−d) mod n(i - d) \bmod n. The cows may line up outside the kk unlocked doors however they like, and the lining up does not count toward the distance.

Choose the kk doors that minimise the total distance the cows walk inside the barn, then report that total.

3≤n≤1003 \le n \le 100, 1≤k≤71 \le k \le 7, k≤nk \le n, and 1≤ri≤1061 \le r_i \le 10^6.

Input

The first line contains nn and kk, separated by a space. Each of the next nn lines contains one value, r1r_1 through rnr_n in order.

Output

Print the minimum total distance the cows walk, on one line.

Note

In the first example Farmer John unlocks the doors of rooms 22 and 55. Eleven cows enter at door 22 and settle in rooms 22, 33 and 44, walking 88 in total. Ten cows enter at door 55 and settle in rooms 55, 66 and 11, walking 66 in total. The two values add up to 1414.

Examples3

  1. Example 1

    Input
    6 2
    2
    5
    4
    2
    6
    2
    
    Expected output
    14
    
  2. Example 2

    Input
    3 1
    1
    1
    1
    
    Expected output
    3
    
  3. Example 3

    Input
    3 3
    1000000
    1000000
    1000000
    
    Expected output
    0