Landscaping
InterviewTime limit1sMemory limit128 MB
Each flowerbed has a current and target dirt amount, and dirt can be bought, removed, or moved between beds at a per-unit distance cost; find the cheapest way to hit every target.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Greedy, Implementation, Math
- Solved
- No attempts yet
Problem
A gardener is landscaping a garden and must move a large amount of dirt in the process.
The garden is a row of flowerbeds (). Flowerbed currently holds units of dirt, and the gardener wants it to hold units instead. Every and is an integer between and .
Three operations are available:
- Buy one unit of dirt and place it in any flowerbed, at a cost of .
- Remove one unit of dirt from any flowerbed and ship it away, at a cost of .
- Move one unit of dirt from flowerbed to flowerbed , at a cost of .
Compute the minimum total cost to make every flowerbed hold exactly units of dirt.
Input
- Line 1: four space-separated integers , , , and ().
- Lines to : line contains two space-separated integers and .
Output
- A single integer: the minimum total cost to finish the landscaping.
Explanation
In the first example there are 4 flowerbeds holding 1, 2, 3, and 4 units of dirt, with targets of 4, 3, 2, and 0 units. Buying, removing, and moving one unit cost 100, 200, and 1 respectively.
One unit of dirt must be removed (from flowerbed 4) at a cost of 200. The remaining dirt is rearranged by moving 3 units from flowerbed 4 to flowerbed 1 and 1 unit from flowerbed 3 to flowerbed 2, for a moving cost of 10. The total is 210.