01背包二进制优化
输入
第1行,2个整数,N和W中间用空格隔开。N为物品的种类,W为背包的容量。(1 <= N <= 100,1 <= W <= 50000) 第2 - N + 1行,每行3个整数,Wi,Pi和Ci分别是物品体积、价值和数量。(1 <= Wi, Pi <= 10000, 1 <= Ci <= 200)
输出
输出可以容纳的最大价值。
输入示例
3 6 2 2 5 3 3 8 1 4 1
输出示例
9
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int MAXN=1e5+10; 4 int dp[MAXN]; 5 int weight[MAXN],value[MAXN]; 6 int main() 7 { 8 int n,w; 9 scanf("%d%d",&n,&w); 10 int weig,val,num; 11 int count=0; 12 for (int i = 0; i <n ; ++i) { 13 scanf("%d%d%d",&weig,&val,&num); 14 for (int j = 1; j <=num ; j<<=1) { 15 weight[count]=j*weig; 16 value[count++]=j*val; 17 num-=j; 18 } 19 if(num>0) 20 { 21 weight[count]=num*weig; 22 value[count++]=num*val; 23 } 24 } 25 for (int i = 0; i <count; ++i) { 26 for (int j = w; j >= weight[i]; j--) { 27 dp[j]=max(dp[j],dp[j-weight[i]]+value[i]); 28 } 29 } 30 printf("%d\n",dp[w]); 31 return 0; 32 }