Farmer John has built a new barn in the shape of a perfect circle. Inside, the barn is a ring of n rooms, numbered 1 through n clockwise around the perimeter of the barn (3≤n≤1000). Each room has a door to each of its two neighboring rooms, and also a door to the outside of the barn.
Farmer John wants exactly ri cows to end up in room i (1≤ri≤100). To herd the cows in without a mess, he unlocks the outside door of a single room, and every cow enters through that door. Each cow then walks clockwise through the rooms until she reaches the room she belongs in. The distance one cow walks is the number of interior doors she passes through. Farmer John wants to unlock the outside door that makes the total distance walked by all the cows as small as possible. Find that minimum total distance.