#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;
// 有限背包
// 1. 背包不用装满的最大价值
// 2. 背包必须装满的最大价值
class Solution {
private:
vector<int> _weights;
vector<int> _values;
vector<int> _amounts;
int _m;
vector<vector<int>> _dp;
public:
Solution(const vector<int> &weights, const vector<int> &values, const vector<int> &amounts, int m) : _weights(
weights), _values(values), _amounts(amounts), _m(m), _dp(weights.size(), vector<int>(_m + 1)) {}
/* 1. dp[i][j] (i->end, 最大为j重)的最大价值
* 2. dp[i][j] = max(dp[i + 1][j - k * weight[i]] + value[i] * k) 0 <= k <= min(amount[i], j / weight[i]);
优化-> dp[i][j] = dp[i + 1][j]
= dp[i + 1][(j - weight[i]) - k * weight[i]] + value[i] * k + value[i];
= dp[i][j - weight[i]] + value[i] ? 保证 dp[i][j - weight[i]]的时候还能取weight[i]还能取
how to 知道 保证 dp[i][j - weight[i]]的时候还能取weight[i]还能取
(1) 用另一个二维数组记录
(2) dp[i][j] (i->end, 取到 j 时i 还剩多少)
* 3. 初始化全为 0
* 4. 遍历顺序 从前到后
* 5. 模拟一遍
* */
int dfs(int cur, int expectedWeight) {
if (expectedWeight < 0) {
return INT_MIN;
}
if (cur >= _weights.size() || expectedWeight == 0) {
return 0;
}
if (_dp[cur][expectedWeight]) {
return _dp[cur][expectedWeight];
}
int max_value = 0;
for (int k = 0; k <= min(_amounts[cur], expectedWeight / _weights[cur]); ++k) {
max_value = max(max_value, dfs(cur + 1, expectedWeight - k * _weights[cur]) + _values[cur] * k);
}
return _dp[cur][expectedWeight] = max_value;
}
};
/* 围绕两个点 1. 当前总重量w; 2. 当前最大价值v
* 分析 dp[i][w] <-> dp[i][v] 哪个复杂度更低
* dp[i][w] 1. 可以定义为(i->end, 重量小于等于 w) 的最大价值
* 2. 也可以定义为(i->end, 重量等于w)的最大价值
* 这两者的差别: 1. 如果求的是重量刚好为 w 的最大价值, 则定义1 不可用
* 2. 若求的是重量不超过 w的时候的最大价值, 则在区域最终结果的时候, 定义 1保证结果的位置,定义 2 不提供保证
*
*
* */
int main() {
vector<int> weights = {2, 3, 5, 7};
vector<int> values = {1, 5, 2, 4};
vector<int> amount = {2, 1, 3, 2};
int m = 15;
vector<vector<int>> dp(weights.size(), vector<int>(m + 1));
}
c++动态规划算法-有限背包问题
最新推荐文章于 2024-09-06 14:02:45 发布