ell*_*tmc 5 python knapsack-problem dynamic-programming
我发现了这个非常方便的示例代码,它实现了背包问题的 DP 解决方案(向发布它的人致敬)。
我正在尝试修改它以包含对背包中物品数量 k 的限制。
我添加了第三个参数
def knapsack(items, maxweight, maxitems):
Run Code Online (Sandbox Code Playgroud)
并将重建修改如下:
while i > 0:
if bestvalues[i][j] != bestvalues[i - 1][j] and len(reconstruction) < maxitems:
reconstruction.append(items[i - 1])
j -= items[i - 1][1]
i -= 1
Run Code Online (Sandbox Code Playgroud)
如果我输入了足够多的项目以供选择,这将始终收敛到所需的 k 个项目。但是,我相当确定这不是找到全局最优解的最接近的近似值。我在一些搜索后阅读的讨论是指在重建之前添加第三维 k 并考虑约束(我*认为这将是在最佳价值评估期间)。
有人可以提供一个如何做到这一点的例子吗?理想情况下,一个有效的 Python 示例会很棒,但我会接受伪代码。我已经阅读了一些使用符号的说明,但我仍然不确定如何使用 k 进行约束(除了我在这里所做的之外)。
谢谢!
正如我在上面的评论中所说,需要第三个维度,我编写了一个递归动态编程解决方案:
#include<bits/stdc++.h>
using namespace std;
int noOfItems, items[100], maxWeight, maxItems, value[100];
int dp[100][1000][100];
int solve(int idx, int currentWeight, int itemsLeft){
if(idx == noOfItems || itemsLeft == 0) return 0;
if(dp[idx][currentWeight][itemsLeft] != -1) return dp[idx][currentWeight][itemsLeft];
int v1 = 0, v2 = 0;
//try to included the current item
if(currentWeight >= items[idx]) v1 = solve(idx+1, currentWeight-items[idx], itemsLeft-1) + value[idx];
//exclude current item
v2 = solve(idx+1, currentWeight, itemsLeft);
return dp[idx][currentWeight][itemsLeft] = max(v1, v2);
}
//print the contents of the knapsack
void print(int idx, int currentWeight, int itemsLeft){
if(idx == noOfItems || itemsLeft == 0) return;
int v1 = 0, v2 = 0;
if(currentWeight >= items[idx]) v1 = solve(idx+1, currentWeight-items[idx], itemsLeft-1) + value[idx];
v2 = solve(idx+1, currentWeight, itemsLeft);
if(v1 >= v2){
cout << idx << " " << items[idx] << " " << value[idx] << endl;
print(idx+1, currentWeight-items[idx], itemsLeft-1);
return;
}else{
print(idx+1, currentWeight, itemsLeft);
return;
}
}
int main(){
cin >> noOfItems >> maxWeight >> maxItems;
for(int i = 0;i < noOfItems;i++) cin >> items[i] >> value[i];
memset(dp, -1, sizeof dp);
cout << solve(0, maxWeight, maxItems) << endl; //prints the maximum value that we can get from the constraints
cout << "Printing the elements in the knapsack" << endl;
print(0, maxWeight, maxItems);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
链接到 ideone 上的解决方案:https://ideone.com/wKzqXk
| 归档时间: |
|
| 查看次数: |
1375 次 |
| 最近记录: |