这个就是一个多重背包!
$\quad$其实这个题跟多重背包完全一样,无非就是要设置下每种物品个数上限,最朴素的,直接按照多重背包的不优化版写出程序如下:
#include <iostream>
using namespace std;
const int N = 1010;
int f[N];
int main()
{
int n, m; cin >> n >> m;
for(int i = 1; i <= n; i++)
{
int v, w, s; cin >> v >> w >> s;
if(s==-1) s = 1; // 设置物品数上限为1
else if(s==0) s = 1010; // 设置物品无限个,不超过背包体积
for(int j = m; j >= v; j--) //
for(int k = 0; k <= s && k * v <= j; k++)
f[j] = max(f[j], f[j - k * v] + k * w);
}
cout << f[m] << endl;
return 0;
}
$\quad$利用二进制优化才能过这个题,如下:
#include <iostream>
#include <vector>
using namespace std;
const int N = 1010;
int f[N];
struct Good
{
int v, w;
};
int main()
{
vector<Good> goods;
int n, m; cin >> n >> m;
for(int i = 1; i <= n; i++)
{
int v, w, s; cin >> v >> w >> s;
if(s==-1) s = 1;
else if(s==0) s = 1010;
for(int k = 1; k <= s; k *= 2)
{
s -= k;
goods.push_back({k * v, k * w});
}
if(s>0) goods.push_back({s * v, s * w});
}
// 01背包
for(auto good: goods)
for(int j = m; j >= good.v; j--)
f[j] = max(f[j], f[j - good.v] + good.w);
cout << f[m] << endl;
return 0;
}