Circular Barn
Time limit2sMemory limit512 MB
Assign each cow waiting outside n rooms on a ring to a distinct room clockwise ahead so the sum of squared walking distances is as small as possible.
- Level
Medium7 of 10
- Topics
- Greedy, Prefix sum
- Solved
- No attempts yet
Problem
Farmer John likes contemporary architecture, so he built a new barn in the shape of a perfect circle. Inside, rooms form a ring, numbered through clockwise around the perimeter of the barn (). Every room has two doors to its neighboring rooms and one door to the outside of the barn.
Farmer John owns cows and wants exactly one cow to end up in each room. The cows line up at arbitrary outside doors, and several cows may pick the same door. Exactly cows stand outside the door of room , and .
Farmer John herds them this way. Each cow enters through the door where she lined up, then walks clockwise through rooms until she reaches the room she will stay in. A cow that walks through doors spends energy. Find the smallest total energy the cows can spend when every room ends up with one cow.
Input
The first line contains . Each of the next lines contains one value, giving through in order.
Output
Print the smallest total energy the cows spend.