cpp-algo-cases/chapter_dynamic_programming/unbounded_knapsack.cpp

65 lines
1.7 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: unbounded_knapsack.cpp
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̬<EFBFBD>滮 */
int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// <20><>ʼ<EFBFBD><CABC> dp <20><>
vector<vector<int>> dp(n + 1, vector<int>(cap + 1, 0));
// ״̬ת<CCAC><D7AA>
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>Ʒ i
dp[i][c] = dp[i - 1][c];
} else {
// <20><>ѡ<EFBFBD><D1A1>ѡ<EFBFBD><D1A1>Ʒ i <20><><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD>Ľϴ<C4BD>ֵ
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* <20><>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ռ<EFBFBD><D5BC>Ż<EFBFBD><C5BB><EFBFBD><EFBFBD>Ķ<EFBFBD>̬<EFBFBD>滮 */
int unboundedKnapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// <20><>ʼ<EFBFBD><CABC> dp <20><>
vector<int> dp(cap + 1, 0);
// ״̬ת<CCAC><D7AA>
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>Ʒ i
dp[c] = dp[c];
} else {
// <20><>ѡ<EFBFBD><D1A1>ѡ<EFBFBD><D1A1>Ʒ i <20><><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD>Ľϴ<C4BD>ֵ
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Driver code */
int main() {
vector<int> wgt = {1, 2, 3};
vector<int> val = {5, 11, 15};
int cap = 4;
// <20><>̬<EFBFBD>
int res = unboundedKnapsackDP(wgt, val, cap);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ʒ<EFBFBD><EFBFBD>ֵΪ " << res << endl;
// <20>ռ<EFBFBD><D5BC>Ż<EFBFBD><C5BB><EFBFBD><EFBFBD>Ķ<EFBFBD>̬<EFBFBD>
res = unboundedKnapsackDPComp(wgt, val, cap);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ʒ<EFBFBD><EFBFBD>ֵΪ " << res << endl;
return 0;
}