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]);
Richie li
source share