Are these two knapsack algorithms the same? (They always output the same thing)

In my code, assuming C is capacity, N is the number of elements, w [j] is the weight of j, and v [j] is the value of j, does it do the same as the 0-1 rocket algorithm? I am trying to use my code on some datasets, and it seems to be so. The reason I am interested is because the 0-1 ranking algorithm we studied is two-dimensional, while it is one-dimensional:

for (int j = 0; j < N; j++) { if (Cw[j] < 0) continue; for (int i = Cw[j]; i >= 0; --i) { //loop backwards to prevent double counting dp[i + w[j]] = max(dp[i + w[j]], dp[i] + v[j]); //looping fwd is for the unbounded problem } } printf( "max value without double counting (loop backwards) %d\n", dp[C]); 

Here is my implementation of the 0-1 backpack algorithm: (with the same variables)

 for (int i = 0; i < N; i++) { for (int j = 0; j <= C; j++) { if (j - w[i] < 0) dp2[i][j] = i==0?0:dp2[i-1][j]; else dp2[i][j] = max(i==0?0:dp2[i-1][j], dp2[i-1][jw[i]] + v[i]); } } printf("0-1 knapsack: %d\n", dp2[N-1][C]); 
+7
source share
1 answer

Yes, your algorithm gives you the same result. This enhancement to the classic 0-1 Knapsack is quite popular: Wikipedia explains this as follows:

In addition, if we use only the 1-dimensional array m [w] to store the current optimal values ​​and pass this array i + 1 times, each time rewriting from m [W] to m [1], we get the same result for only space O (W).

Please note that they specifically mention your reverse loop.

+3
source

All Articles