题目链接:http://acm.uestc.edu.cn/#/problem/show/1691
解法:就是裸的多重背包,二进制优化或者直接暴力。
1,二进制优化
#include <bits/stdc++.h>
using namespace std;
const int maxn = 50010;
int n,V,w[maxn],p[maxn],c[maxn],dp[maxn];
int weight[maxn],val[maxn],cnt=0;
int main()
{
scanf("%d %d", &n,&V);
for(int i=1; i<=n; i++){
scanf("%d %d %d", &w[i],&p[i],&c[i]);
int k=1;
while(k<c[i]){
++cnt;
weight[cnt]=k*w[i],val[cnt]=k*p[i];
c[i]-=k;
k<<=1;
}
if(c[i]){
++cnt;
weight[cnt]=c[i]*w[i],val[cnt]=c[i]*p[i];
}
}
memset(dp,0,sizeof(dp));
for(int i=1; i<=cnt; i++){
for(int j=V;j>=weight[i];j--){
dp[j]=max(dp[j],dp[j-weight[i]]+val[i]);
}
}
printf("%d\n", dp[V]);
return 0;
}
2,直接转化成01背包
#include <bits/stdc++.h> using namespace std; const int maxn = 50010; int n,V,w[maxn],p[maxn],c[maxn],dp[110][maxn]; int main() { scanf("%d %d", &n,&V); for(int i=1; i<=n; i++){ scanf("%d %d %d", &w[i],&p[i],&c[i]); } memset(dp,0,sizeof(dp)); for(int i=1; i<=n; i++){ for(int k=0; k<=c[i]; k++){ for(int j=V; j>=0; j--){ if((j-k*w[i])>=0){ dp[i][j]=max(dp[i][j],dp[i-1][j-k*w[i]]+k*p[i]); } else break; } } } printf("%d\n",dp[n][V]); return 0; }