algorithm - 带有 "at least X value"约束的背包

标签 algorithm dynamic-programming knapsack-problem

您将如何解决背包的这种变体?

你有 n 个对象 (x1,...xn),每个对象都有成本 ci 和值 vi (1<=i<=n) 和一个附加约束 X,它是所选项目值的下限. 找到 x1,...,xn 的一个子集,它可以最小化值(value)至少为 X 的项目的成本。

我试图通过动态规划来解决这个问题,我想到的是将常用的表修改为 K[n,c,X],其中 X 是我需要达到的最小值,但这似乎带我无处可去。有什么好的想法吗?

最佳答案

这可以像我们处理背包问题一样完成,在每个索引处我们尝试在背包内放入一个值或不放入一个值,这里背包的大小没有限制因此我们可以放入任何元素在背包里。

那么我们只需要考虑那些满足背包大小>= 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;
}

ideone 上的解决方案链接:http://ideone.com/7ZCW8z

关于algorithm - 带有 "at least X value"约束的背包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38120363/

相关文章:

c++ - double : efficency and quality of my test 的相等性检查

c - 如何接受一组数字,如 {301,102,99,202,198,103} 并丢弃 ~100?

python - 膳食计划算法?

java - 内存:Rememo

java - 使用动态规划删除中间元素的三重乘积的最小总和

python - 如何获得产生特定总和的top-x元素

sql - 检查时间范围重叠,watchman 问题 [SQL]

algorithm - 如何设计近似解算法

algorithm - 动态规划问题从前到后有区别吗?

java - 不同风格的递归,引用/全局/指针变量的使用