Circular Barn
Time limit2sMemory limit512 MB
Choose up to k outer doors on a ring of n rooms so the total clockwise walking distance to every cow room is minimized.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Prefix sum
- Solved
- No attempts yet
Problem
Farmer John likes contemporary architecture, so his new barn is a perfect circle. Inside, the barn is a ring of rooms, numbered through clockwise around the perimeter (). Each room has a door to each of its two neighbouring rooms, and one more door that opens to the outside.
Farmer John wants exactly cows to end up in room (). To herd the cows in without a stampede he unlocks at most of the exterior doors (), and a cow may enter only through an unlocked door. Once inside, a cow walks clockwise from room to room until she reaches her own room. Walking between two neighbouring rooms adds to the distance. The cows may line up outside the unlocked doors however they like, and lining up costs no distance.
Find the smallest total distance the cows walk after entering the barn, over the best choice of doors.
Input
The first line contains and . Each of the next lines contains one value, through in order.
Output
Print the minimum total distance the cows walk.
Hint
In the first example Farmer John unlocks doors and . The cows entering at door walk a total distance of to reach rooms , and . The cows entering at door walk a total distance of to reach rooms , and .