c++-动态规划算法-完全背包(选择数量无限制)

#include <iostream>
#include <utility>
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>

using namespace std;

using namespace std;

#define optimizing
class Solution {
private:
    const vector<int> &_weights;
    const vector<int> &_values;
public:
    Solution(const vector<int> &weights, const vector<int> &values) : _weights(weights), _values(values) {}

    /*  1. dfs(0, w) 求(0, end)能得到的最大重量
     *    dp[i][w] (i->end ) 最大重量不超过 w的最大价值
     *  2. 递推公式
     *      dp[i][w] = max(dp[i + 1][w - weight[i] * k] + value[i] * k);
     *  3. 初始化全为 0
     *  4. 遍历顺序从前往后
     *  5. 模拟一遍
     * */

    /*
     *   递推公式优化->   ^^^^^^^^    哎 数学
     *   dp[i][w] = max(dp[i + 1][w - weight[i] * k) + value[i] * k)   K >= 0  (1)
     *              = max(dp[i + 1][w], max(dp[i + 1][w - weight[i] * k] + value[i] * k)) K >=1  (2) 将 k=0 单独剥离出来
     *                     = max    dp[i + 1][w]
     *                     = max    dp[i + 1][(w - weight[i]) - weight[i] * (K - 1)] + value[i] * (K - 1) + value[i]  令 t = K - 1, t >= 0
     *                          = max dp[i + 1][(w - weight[i]) - weight[i] * t] + value[i] * t + value[i]  t >= 0
     *                          = dp[i][w - weight[i]] + value[i]
     *             = max(dp[i + 1][w], dp[i][w - weight[i]] + value[i])
     * */
    int dfs(int cur, int expectedWeight, vector<vector<int>> &dp) {
        if (cur >= _weights.size()) {
            return 0;
        }
        if (expectedWeight <= 0) {
            return INT_MIN;
        }
        if (dp[cur][expectedWeight] != 0) {
            cout << "(" << cur << "," << expectedWeight << ")" << endl;
            return dp[cur][expectedWeight];
        }
#ifndef optimizing
        int max_value = 0;
        for (int k = 0; k <= expectedWeight / _weights[cur]; ++k) {
            int res = dfs(cur + 1, expectedWeight - _weights[cur] * k, dp) + k * _values[cur];
            max_value = max(res, max_value);
        }
        return dp[cur][expectedWeight] = max_value;
#endif
        return dp[cur][expectedWeight] = max(dfs(cur + 1, expectedWeight, dp),
                                             dfs(cur, expectedWeight - _weights[cur], dp) + _values[cur]);
    }
};

int main() {
    vector<int> weights = {2, 3, 5, 7};
    vector<int> values = {1, 5, 2, 4};
    int m = 10;
    vector<vector<int>> dp(weights.size(), vector<int>(m + 1));
    cout << Solution(weights, values).dfs(0, m, dp) << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值