Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to modify Knapsack - to find the maximum weighted sum
    primarykey
    data
    text
    <p>The below is a knapsack code using dynamic programming. The original code will return a maximum sum of the values. However, I want to tweak it so that the code will return a maximum sum of (value*weight). The below is what I have done, but it doesn't work well, some advice is appreciated. </p> <pre><code> #include&lt;stdio.h&gt; int max(int a,int b) { return a&gt;b?a:b; } int Knapsack(int items,int weight[],int value[],int maxWeight) { int dp[items+1][maxWeight+1]; /* dp[i][w] represents maximum value that can be attained if the maximum weight is w and items are chosen from 1...i */ /* dp[0][w] = 0 for all w because we have chosen 0 items */ int iter,w; for(iter=0;iter&lt;=maxWeight;iter++) { dp[0][iter]=0; } /* dp[i][0] = 0 for all w because maximum weight we can take is 0 */ for(iter=0;iter&lt;=items;iter++) { dp[iter][0]=0; } for(iter=1;iter&lt;=items;iter++) { for(w=0;w&lt;=maxWeight;w=w+10) { dp[iter][w] = dp[iter-1][w]*weight[iter-1]; /* If I do not take this item */ if(w-weight[iter] &gt;=0) { /* suppose if I take this item */ dp[iter][w] = max( (dp[iter][w]*weight[iter]) , (dp[iter-1][w-weight[iter]]*weight[iter-1])+(value[iter]*weight[iter])); } } } return dp[items][maxWeight]; } int main() { int items=12; int weight[/*items+1*/13]={60, 20, 20, 20, 10, 20, 10, 10, 10, 20, 20, 10}; int value[/*items+1*/13]={48, 77, 46, 82, 85, 43, 49, 73, 65, 48, 47, 51}; int iter; int maxWeight=120; printf("Max value attained can be %d\n",Knapsack(items,weight,value,maxWeight)); } </code></pre> <p>The code is expected to give an output of <em>Max value attained can be 7820</em> (the maximum total sum of value*weight calculated by hand). However, the output is <em>Max value attained can be 0</em>. Why?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload