Greedy Knapsack
Time limit1sMemory limit1024 MB
Given N items with weights and values, find the largest total value the greedy packing reaches over every capacity M from 1 to T.
- Level
Hard8 of 10
- Topics
- Greedy, Simulation, Prefix sum
- Solved
- No attempts yet
Problem
Budi stumbled upon the classical 0-1 Knapsack Problem that he learned in his university class. There are items numbered from 1 to . Item has a positive weight and a positive value . The goal is to take zero or more items so that their total weight does not exceed and their total value is as large as possible.
Budi has not worked on this problem in a while and cannot remember how to solve it. So he devised a greedy algorithm. The algorithm processes the items one by one, from item 1 to item . If item can be taken without the total weight exceeding , it takes the item. Otherwise, it skips the item. The output is the total value of all taken items.
GreedyKnapsack(W[1..N], V[1..N], M):
total_value = 0
total_weight = 0
for i = 1 to N:
if total_weight + W[i] ≤ M:
total_weight = total_weight + W[i]
total_value = total_value + V[i]
return total_value
Budi knows this greedy algorithm may not find the optimal solution, but he does not mind for now. He noticed that the output depends on . So he runs the greedy algorithm for every from 1 to a given upper limit , and wants to find the largest output he can get.
For example, let , , , and . The largest output is 3, for instance with . The greedy algorithm takes items 2, 3, and 4, with a total weight of and a total value of . If , the algorithm takes only item 1, with a total weight of 10 and a total value of 1.
Your task is to find the largest output the greedy algorithm can produce when ranges from 1 to .
Input
The first line contains two integers and (; ), the number of items and the upper limit. The second line contains integers (), the weight of each item. The third line contains integers (), the value of each item.
Output
Print one integer on a line, the largest output the greedy algorithm can obtain.