Candy
Time limit1sMemory limit128 MB
Given starting candies, allowed daily eating amounts, and favorite numbers that trigger bonus candies, maximize total candies eaten or report -1 if infinite.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Graph, BFS, Greedy
- Solved
- No attempts yet
Problem
Farmer John has candies that he wants to give Bessie over some number of days ().
Each day, Bessie eats exactly one amount chosen from a fixed master list of options (, ). She may pick option only if at least candies remain, and she then eats exactly candies — no more, no less.
Farmer John has also disclosed of his favorite numbers (, ). Whenever the number of candies remaining at the end of a day (right after Bessie eats) exactly equals one of these favorite numbers, Bessie may have him add exactly more candies to the supply (). If the new remaining count is again a favorite number, she may add again, and so on; she may stop adding at any time. In the best case Bessie can obtain an infinite amount of candy.
Bessie can no longer eat any candy once she cannot pick any option (not enough candies remain for any ) and the remaining count is not one of the favorite numbers.
Bessie cannot plan far ahead, so she needs your help to eat as many candies in total as possible.
For example, suppose the basket starts with 10 candies, Bessie may eat 3 or 5 candies each day, and Farmer John adds 1 candy whenever the remaining count is 2 or 4. One optimal sequence of choices is:
Start of Candies Remaining Bonus End of
Day day eaten after eat added day
1 10 3 7 0 7
2 7 3 4 1 5
3 5 3 2 1 3
4 3 3 0 0 0
The total number of candies eaten is .
Input
- Line 1: four space-separated integers , , , and .
- Lines to : line contains a single integer .
- Lines to : line contains a single integer .
Constraints: , , , , , .
Output
- A single integer: the maximum total number of candies Bessie can eat, or if she can eat an infinite amount of candy.