多重背包问题,将每种物品的个数进行拆分,转化成01背包问题
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
int c, n, bag, m;
int w[3000], v[3000];
cin >> c;
for(int i = 0; i < c; i++) {
int dp[3000] = {0};
int cnt = 1;//拆分后物品数量
cin >> bag >> m;
for(int i = 0; i < m; i++) {
int price, weight, num, k = 1;
cin >> price >> weight >> num;
while(num - k > 0) {
num -= k;
w[cnt] = k * price;
v[cnt] = k * weight;
cnt++;
k *= 2;
}
w[cnt] = num * price;
v[cnt] = num * weight;
cnt++;
}
cnt--;//cnt一直指向下一个,全部拆分完的时候指向空的那个位置,所以要减去1
for(int i = 1; i <= cnt; i++) {
for(int j = bag; j >= w[i]; j--) {
dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
}
}
cout << dp[bag] << endl;
}
return 0;
}