AcWing 7. 混合背包问题
原题链接
中等
#include <iostream>
#include <vector>
using namespace std;
const int N = 1010;
int n, m;
int dp[N];
struct Thing {
int kind;
int v, w;
};
vector<Thing> goods;
int main(){
cin >> n >> m;
int v, w, s;
for (int i = 1; i <= n; i++){
cin >> v >> w >> s;
if (s == -1) goods.push_back({-1, v, w});
else if (s == 0) goods.push_back({0, v, w});
else {
int k = 1;
while (s >= k){
s -= k;
goods.push_back({-1, k*v, k*w});
k *= 2;
}
if (s > 0) {
goods.push_back({-1, s*v, s*w});
}
}
}
for (auto& x: goods){
if (x.kind == -1){
for (int j = m; j >= x.v; j--)
dp[j] = max(dp[j], dp[j - x.v] + x.w);
}
else {
for (int j = x.v; j <= m; j++)
dp[j] = max(dp[j], dp[j - x.v] + x.w);
}
}
cout << dp[m] << endl;
return 0;
}