Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these 2 knapsack algorithms the same? (Do they always output the same thing)

In my code, assuming C is the capacity, N is the amount of items, w[j] is the weight of item j, and v[j] is the value of item j, does it do the same thing as the 0-1 knapsack algorithm? I've been trying my code on some data sets, and it seems to be the case. The reason I'm wondering this is because the 0-1 knapsack algorithm we've been taught is 2-dimensional, whereas this is 1-dimensional:

for (int j = 0; j < N; j++) {
    if (C-w[j] < 0) continue;
    for (int i = C-w[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 knapsack 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][j-w[i]] + v[i]);
    }
}
printf("0-1 knapsack: %d\n", dp2[N-1][C]);
like image 933
Richie Li Avatar asked Dec 30 '11 19:12

Richie Li


1 Answers

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

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

Note that they specifically mention your backward loop.

like image 200
Sergey Kalinichenko Avatar answered Sep 28 '22 00:09

Sergey Kalinichenko