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

亡梦爱人 提交于 2019-12-07 02:49:25

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/8683155/are-these-2-knapsack-algorithms-the-same-do-they-always-output-the-same-thing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!