动态规划——物品无限的背包问题

动态规划——物品无限的背包问题

物品无限的背包问题。有 n 种物品,每种均有无穷多个。第i种物品的体积为Vi,重量为 Wi 。选一些物品装到一个容量为 C 的背包中,使得背包内物品在总体积不超过C的前提下重量尽量大。 1n100 1ViC10000 1Wi106

记忆化搜索解法

dp要初始化为无法得到的值,比如说-1,使用memset(dp, -1, sizeof(dp))进行初始化。

int dpBag(int S) {
    int& ans = dp[S];
    if(ans >= 0) {
        return ans;
    }
    ans = 0;
    for(int i = 1; i <= n; i++) {
        if(S >= volumn[i]) {
            ans = max(ans, dpBag(S - volumn[i]) + weight[i]);
        }
    }
    return ans;
}

递推法

void solve() {
    dp[0] = 0;
    int ans = -INF;
    for(int i = 1; i <= C; i++) {
        dp[i] = -INF;
    }

    for(int i = 1; i <= C; i++) {
        for(int j = 1; j <= n; j++) {
            if(i >= volumn[j]) {
                dp[i] = max(dp[i], dp[i - volumn[j]] + weight[j]);
                if(dp[i] > ans) {
                    ans = dp[i];
                }
            }
        }
    }
    cout << ans << endl;
}

测试主程序

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int MAX_NUM = 100 + 5;
const int MAX_CAPACITY = 10000 + 5;
const int INF = 100000000;

// 物品种类
int n;
// 背包容量
int C;
// 体积
int volumn[MAX_NUM];
// 重量
int weight[MAX_NUM];
// dp[i]表示体积为i时的最大重量
int dp[MAX_CAPACITY];

void solve() {
    dp[0] = 0;
    int ans = -INF;
    for(int i = 1; i <= C; i++) {
        dp[i] = -INF;
    }

    for(int i = 1; i <= C; i++) {
        for(int j = 1; j <= n; j++) {
            if(i >= volumn[j]) {
                dp[i] = max(dp[i], dp[i - volumn[j]] + weight[j]);
                if(dp[i] > ans) {
                    ans = dp[i];
                }
            }
        }
    }
    cout << ans << endl;
}

int dpBag(int S) {
    int& ans = dp[S];
    if(ans >= 0) {
        return ans;
    }
    ans = 0;
    for(int i = 1; i <= n; i++) {
        if(S >= volumn[i]) {
            ans = max(ans, dpBag(S - volumn[i]) + weight[i]);
        }
    }
    return ans;
}

int main() {
    while(cin >> n && n) {
        cin >> C;
        for(int i = 1; i <= n; i++) {
            cin >> volumn[i] >> weight[i];
        }
        solve();

        memset(dp, -1, sizeof(dp));
        cout << dpBag(C) << endl << endl;
    }
    return 0;
}

输出数据

3 5
1 2
2 3
3 2
10
10

3 7
2 1
3 2
4 3
5
5

3 5
3 3
4 2
3 2
3
3

0

Process returned 0 (0x0)   execution time : 22.801 s
Press any key to continue.
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值