Candy

Time limit1sMemory limit128 MB

Summary
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 NN candies that he wants to give Bessie over some number of days (1≤N≤400001 \le N \le 40000).

Each day, Bessie eats exactly one amount chosen from a fixed master list of NoptN_{opt} options CiC_i (1≤Nopt≤501 \le N_{opt} \le 50, 1≤Ci≤N1 \le C_i \le N). She may pick option ii only if at least CiC_i candies remain, and she then eats exactly CiC_i candies — no more, no less.

Farmer John has also disclosed FF of his favorite numbers FNiFN_i (1≤F≤501 \le F \le 50, 1≤FNi≤N1 \le FN_i \le N). 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 MM more candies to the supply (1≤M≤1001 \le M \le 100). If the new remaining count is again a favorite number, she may add MM 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 CiC_i) 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 3+3+3+3=123 + 3 + 3 + 3 = 12.

Input

  • Line 1: four space-separated integers NN, NoptN_{opt}, FF, and MM.
  • Lines 22 to Nopt+1N_{opt}+1: line i+1i+1 contains a single integer CiC_i.
  • Lines Nopt+2N_{opt}+2 to Nopt+F+1N_{opt}+F+1: line i+Nopt+1i+N_{opt}+1 contains a single integer FNiFN_i.

Constraints: 1≤N≤400001 \le N \le 40000, 1≤Nopt≤501 \le N_{opt} \le 50, 1≤Ci≤N1 \le C_i \le N, 1≤F≤501 \le F \le 50, 1≤FNi≤N1 \le FN_i \le N, 1≤M≤1001 \le M \le 100.

Output

  • A single integer: the maximum total number of candies Bessie can eat, or −1-1 if she can eat an infinite amount of candy.

Examples3

  1. Example 1

    Input
    10 2 2 1
    3
    5
    4
    2
    
    Expected output
    12
    
  2. Example 2

    Input
    4 1 1 1
    1
    3
    
    Expected output
    -1
    
  3. Example 3

    Input
    10 1 1 5
    10
    1
    
    Expected output
    10