#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;
}
c++-动态规划算法-完全背包(选择数量无限制)
最新推荐文章于 2022-08-20 15:44:38 发布