Hello , I am currently trying to solve this knapsack problem:
You are a burglar, with nothing in your hand but a knapsack. You are about to break into the house that all burglars dream of entering, when you remember the scrap piece of paper in a pocket of your jacket. This piece of paper tells you everything you need to know about every type of item inside the house—the size and the value.
You think back: burglars from previous generations have repeatedly said that there are an infinite number of items of any item type. As soon as a particular item type caught their eye, they would stuff as many of those items as they could into a knapsack. But not you. You want to extract the maximum value out of this idolised house, but you don't know how.
So you go home. You rest your very light knapsack next to your laptop and write a program telling you what to steal.
Input
The first line contains integers N and M, representing the number of item types and the size of the knapsack. Following this will be N lines, one for each item type, each of the form s v, representing the size and value of each type of item respectively. Of these N lines, the ith line corresponds to the ith item type. Note that items types are not guaranteed to appear in any particular order.
You may assume that N,M≤1000, and that s,v≤1000 for each item type.
Output
Your program should output a list of item types, showing you which items to steal. This list should be in ascending order, with one item type on each line, assuming item types are numbered from 1 to N.
If there is more than one possible solution, any correct solution will suffice.
Sample Input
The following corresponds to the example provided by Sedgewick on page 597, with a knapsack of size 17. The optimal filling uses one item of type 1 and two of type 3, giving a total value of 24.
Although my code seems to successfully output the sample outputs, while running it through the online test cases, it seems to never end. Can someone please tell me what is wrong with my code please?
Can you explain (with words) what your algorithm is?
There's are number of inconsistencies with your example and code, I don't want to debug those. It's much more productive if you describe your algorithm, fix that it needs attention, then see how it's implemented.