AcWing 4. 多重背包问题 I
原题链接
简单
作者:
Value
,
2020-05-29 11:39:19
,
所有人可见
,
阅读 465
看成01背包即可
数量是多少就存储多少次!
写法一
#include <iostream>
using namespace std;
const int N = 10010;
int weight[N], value[N], f[N];
int main(){
int n, bag;
cin >> n >> bag;
int k = 1;
int w, v, num;
for(int i = 1; i <= n; i ++ ){
cin >> w >> v >> num;
for(int j = 1; j <= num; j ++ ){
weight[k] = w, value[k ++ ] = v;
}
}
for(int i = 1; i < k; i ++ ){
for(int j = bag; j >= weight[i]; j -- ){
f[j] = max(f[j], f[j - weight[i]] + value[i]);
}
}
cout << f[bag] << endl;
return 0;
}
写法二
#include <iostream>
using namespace std;
const int N = 110;
int weight[N], value[N], amount[N];
int f[N];
int main(){
int n, bag;
cin >> n >> bag;
for(int i = 1; i <= n; i ++ ) cin >> weight[i] >> value[i] >> amount[i];
for(int i = 1; i <= n; i ++ ){
for(int j = bag; j >= weight[i]; j -- ){
for(int k = 0; k * weight[i] <= j && k <= amount[i]; k ++ ){
f[j] = max(f[j], f[j - k * weight[i]] + k * value[i]);
}
}
}
cout << f[bag] << endl;
return 0;
}