思路
多重背包。
暴力
用01背包的做法,枚举每一个物品取0个到取m个的情况,时间复杂度。最后两个点会TLE。
优化
使用二进制优化。我们先用二级制把一个数拆分。
如:17
重量 | 价值 | 倍数 |
w | v | 1 |
2*w | 2*v | 2 |
4*w | 4*v | 4 |
8*w | 8*v | 8 |
2*w | 2*v | 2 |
这样我们就能通过让这几个数相加组合出从0到17的任意数,如7=1+2+4,10=2+8
代码
#include<bits/stdc++.h>
#define endl '\n';
using namespace std;
int n,m,cnt;
const int N=1e6+10;
long long w[N],v[N],t[N],dp[N],vv,ww,tt;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>vv>>ww>>tt;
int quan=1;
while(tt>=quan){
v[++cnt]=vv*quan;
w[cnt]=ww*quan;
tt-=quan;
quan*=2;
}if(tt){
v[++cnt]=vv*tt;
w[cnt]=ww*tt;
}
}for(int i=1;i<=cnt;i++){
for(int j=m;j>=w[i];j--){
dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
}
}cout<<dp[m];
return 0;
}