Balancing Bacteria
Time limit2sMemory limit1024 MB
Given N patches with signed bacteria offsets, find the fewest sprays from a linearly decaying sprayer anchored at patch N that bring every patch to zero.
- Level
Medium6 of 10
- Topics
- Greedy, Prefix sum, Implementation
- Solved
- No attempts yet
Problem
Farmer John has () patches of grass in a line. The bacteria level of patch differs from the healthy level by (). For example, if , then patch is 3 units below normal, so it needs exactly 3 more units of bacteria to be healthy.
Farmer John wants every patch to reach the healthy level. He has two pesticides, one that adds bacteria and one that removes bacteria. To spray either one, he stands at patch (the rightmost patch) and chooses a sprayer power ().
The sprayer affects patches near Farmer John most, and its effect weakens with distance. If he uses the pesticide that adds bacteria, then units are added to patch , units to patch , units to patch , and so on. Patches receive nothing because the sprayer does not reach them. The pesticide that removes bacteria works the same way, except it subtracts the amounts instead.
Find the minimum number of times Farmer John must spray so that every patch reaches the healthy bacteria level. The answer is guaranteed to be at most .
The values can be very large, so use a 64-bit integer type such as long long in C/C++.
Input
The first line contains .
The second line contains integers , the initial bacteria levels of the patches of grass.
Output
Print the minimum number of sprays needed to make every patch of grass have the healthy bacteria level.