Luc*_*rgi 6 algorithm knapsack-problem dynamic-programming
您将如何解决背包的这种变体?
您有 n 个对象 (x1,...xn),每个对象都有成本 ci 和值 vi (1<=i<=n) 以及一个附加约束 X,它是所选项目值的下限。找到 x1,...,xn 的子集,使值至少为 X 的项目的成本最小化。
我试图通过动态编程来解决这个问题,我想到的是将常用的表修改为 K[n,c,X] ,其中 X 是我需要达到的最小值,但这似乎对我无济于事。有什么好主意吗?
这可以像我们做背包问题一样完成,在每个索引处,我们尝试在背包内放入一个值或不放入一个值,这里背包的大小没有限制,因此我们可以在背包内放入任何元素。
那么我们只需要考虑那些满足条件的解决方案size of the knapsack >= X。
背包的状态是DP[i][j]其中i是元素的索引,j是当前背包的大小,注意我们只需要考虑那些具有 的解j >= X。
下面是 C++ 中的递归动态规划解决方案:
#include <iostream>
#include <cstring>
#define INF 1000000000
using namespace std;
int cost[1000], value[1000], n, X, dp[1000][1000];
int solve(int idx, int val){
if(idx == n){
//this is the base case of the recursion, i.e when
//the value is >= X then only we consider the solution
//else we reject the solution and pass Infinity
if(val >= X) return 0;
else return INF;
}
//this is the step where we return the solution if we have calculated it previously
//when dp[idx][val] == -1, that means that the solution has not been calculated before
//and we need to calculate it now
if(dp[idx][val] != -1) return dp[idx][val];
//this is the step where we do not pick the current element in the knapsack
int v1 = solve(idx+1, val);
//this is the step where we add the current element in the knapsack
int v2 = solve(idx+1, val + value[idx]) + cost[idx];
//here we are taking the minimum of the above two choices that we made and trying
//to find the better one, i.e the one which is the minimum
int ans = min(v1, v2);
//here we are setting the answer, so that if we find this state again, then we do not calculate
//it again rather use this solution that we calculated
dp[idx][val] = ans;
return dp[idx][val];
}
int main(){
cin >> n >> X;
for(int i = 0;i < n;i++){
cin >> cost[i] >> value[i];
}
//here we are initializing our dp table to -1, i.e no state has been calculated currently
memset(dp, -1, sizeof dp);
int ans = solve(0, 0);
//if the answer is Infinity then the solution is not possible
if(ans != INF)cout << solve(0, 0) << endl;
else cout << "IMPOSSIBLE" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
ideone 上的解决方案链接:http://ideone.com/7ZCW8z
| 归档时间: |
|
| 查看次数: |
3655 次 |
| 最近记录: |