Farmer John likes contemporary architecture, so his new barn is a perfect circle. Inside, the barn is a ring of n rooms, numbered 1 through n clockwise around the perimeter (3≤n≤1000). 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 ri cows to end up in room i (1≤ri≤1000000). To herd the cows in without a stampede he unlocks at most k of the exterior doors (1≤k≤7), 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 1 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.