7

私のコードでは、C を容量、N をアイテムの量、w[j] をアイテム j の重量、v[j] をアイテム j の値とすると、0- 1 ナップザックアルゴリズム? いくつかのデータセットでコードを試してみましたが、そのようです。私がこれを不思議に思っている理由は、私たちが教えられてきた 0-1 ナップザック アルゴリズムが 2 次元であるのに対し、これは 1 次元だからです。

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]);

これが 0-1 ナップザック アルゴリズムの私の実装です: (同じ変数を使用)

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]);
4

1 に答える 1

3

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.

于 2011-12-30T20:25:23.493 に答える