Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a version of the Knapsack problem known as the 0-1 knapsack.</p> <p>You are making some silly mistakes in your code.</p> <p>To begin with the first integer in input is the weight and the second is the value. While you are taking first as value and second as weight. Moreover you are taking n+1 values as input 0 to N inclusive.</p> <p>Now in your algorithm, you are considering that you can take any number of copies of the items, this is not true this is a 0-1 knapsack. Read this <a href="http://en.wikipedia.org/wiki/Knapsack_problem">http://en.wikipedia.org/wiki/Knapsack_problem</a> .</p> <p>I came up with this algorithm and I submitted and got accepted. So this should work fine. </p> <pre><code>int M[2000][2000]; int knapsack(int value[], int weight[], int C, int n) { for(int i = 1; i &lt;= C; i++){ for(int j = 0; j &lt;n; j++){ if(j &gt; 0){ M[j][i] = M[j-1][i]; if (weight[j] &lt;= i) M[j][i] = max(M[j][i], M[j-1][i-weight[j]]+value[j]); } else{ M[j][i] = 0; if(weight[j] &lt;= i) M[j][i] = max(M[j][i], value[j]); } } // cout &lt;&lt; M[i][n-1] &lt;&lt; endl; } return M[n-1][C]; } int main() { int C, N; cin &gt;&gt; C &gt;&gt; N; // cout &lt;&lt; C &lt;&lt; endl; int* value = new int[N+1]; int* weight = new int[N+1]; for ( int i = 0; i &lt; N; i++) { cin&gt;&gt;weight[i]&gt;&gt;value[i]; } // vector &lt; int &gt;back(N, 0); cout&lt;&lt;knapsack(value,weight,C,N)&lt;&lt;endl; return 0; } </code></pre> <p>BTW don't dynamically allocate arrays simply use vectors</p> <pre><code>vector &lt;int&gt; My_array(n); </code></pre>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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