Circular Barn Revisited
Time limit2sMemory limit512 MB
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 rooms, numbered through clockwise around the perimeter. Each room has inner doors to its two neighbours and one door to the outside.
Farmer John wants exactly cows to end up in room . To herd them in an orderly way he unlocks only 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 and settles in room walks a distance of . The cows may line up outside the unlocked doors however they like, and the lining up does not count toward the distance.
Choose the doors that minimise the total distance the cows walk inside the barn, then report that total.
, , , and .
Input
The first line contains and , separated by a space. Each of the next lines contains one value, through 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 and . Eleven cows enter at door and settle in rooms , and , walking in total. Ten cows enter at door and settle in rooms , and , walking in total. The two values add up to .