Haybale Restacking
InterviewTime limit1sMemory limit128 MB
Given N piles in a circle with current and target amounts of hay, move bales at cost equal to circular distance to reach the target with minimum total work.
- Level
Medium7 of 10
- Topics
- Greedy, Prefix sum, Math, Array
- Solved
- No attempts yet
Problem
Farmer John has just ordered a large number of hay bales. He wants to organize them into piles () arranged in a circle, where pile should contain bales of hay. Unfortunately, the delivery driver only remembered to leave the hay in piles arranged in a circle. After delivery, pile contains bales of hay. Of course, the sum of the equals the sum of the .
Farmer John would like to move the bales from their current configuration (the ) into his target configuration (the ). Moving one bale from one pile to a pile that is steps away around the circle costs units of work. Compute the minimum total amount of work he needs.
Input
- Line 1: the integer .
- Lines 2 to : line contains two integers and ().
Output
Print a single integer: the minimum total units of work Farmer John needs.
Hint
In the first example there are 4 piles around a circle initially holding 7, 3, 9, and 1 bales, with target amounts 1, 4, 2, and 13. A minimum of 13 units of work suffices: move 6 bales from pile 1 to pile 4, move 1 bale from pile 3 to pile 2, and move 6 bales from pile 3 to pile 4. Because the piles form a circle, pile 1 and pile 4 are adjacent, so each of those moves costs just 1 step per bale.