c++ - 0-1 背包 : return weight and maximum value in C++

标签 c++ dynamic-programming knapsack-problem

我们知道在 0-1 背包问题中,我们从一些容量有限的元素中获得最大 yield 。 (Knapsack problem)。

Example:
4 10 // 5 items, 10 capacity
1 120 // weight cost_value
4 280
3 150
4 200
Ans: 600
Total Weight: 9

但我的问题是,我一次想要总重量和 yield 。这怎么可能?我的代码会有什么变化?请给我建议我自己的代码。

#include <bits/stdc++.h>

using namespace std;

#define MAX_N 100
#define MAX_W 1000
int n;
int dp[MAX_N+1][MAX_W+1];
int weight[MAX_N+1];
int cost[MAX_N+1];
int CAP;
int func(int i,int w)
{
    if(i==n+1) return 0;
    if(dp[i][w]!=-1) return dp[i][w];
    int profit1=0,profit2=0;
    if(w+weight[i]<=CAP)
        profit1=cost[i]+func(i+1,w+weight[i]);

    profit2=func(i+1,w);
    dp[i][w]=max(profit1,profit2);
    return dp[i][w];
}
int main()
{
    memset(dp,-1,sizeof(dp));
    scanf("%d%d",&n,&CAP);
    for(int i=1; i<=n; i++)
    {
        scanf("%d %d",&weight[i],&cost[i]);
    }
    printf("%d\n",func(1,0));


}

最佳答案

这是您的问题的解决方案。你必须使用对。

#include <bits/stdc++.h>

using namespace std;

#define PP pair<int,int>
int n,target;
int cost[102], weight[102];
int CAP;

pair<int,int> Knap(int i,int w)
{
    if(i==n+1) return make_pair(0,w);
    pair<int,int> profit1, profit2;

    if(w+weight[i]<=CAP) {
        pair<int,int> tmp = Knap(i+1, w + weight[i]);
        profit1 = make_pair(tmp.first+cost[i], tmp.second);
    }
    else
        profit1 = make_pair(0,0);

    profit2=Knap(i+1,w);
    return max(profit1, profit2);
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n;
        cin>>CAP;

        for(int i=1; i<=n; i++)
        {
            scanf("%d %d",&weight[i],&cost[i]);
        }
        pair<int,int>P;
        P=Knap(1,0);

        cout<<P.first<<" "<<P.second<<endl;
    }
    return 0;
}

测试:

1
4 10
1 120
4 280
3 150
4 200
Ans: 600 9

关于c++ - 0-1 背包 : return weight and maximum value in C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30324815/

相关文章:

recursion - 用动态规划编写递归算法

algorithm - 携带有数量和重量限制的 gem 如何发挥最大值(value)?

c++ - std::shared_mutex 和 std::shared_lock 是读者还是作者更喜欢?

java - 使用动态规划生成前 n 个素数

c++ - Box2D在特定图层调试绘制

recursion - 动态规划: Tabular vs memoization

knapsack-problem - 曲棍球池算法

从中心开始用较小的矩形填充大矩形的算法

c++ - 虚拟分配地址

c++ - 用 C++ 编写 Stack 类的各种实现