hdu 2191 完全背包

为了挽救灾区同胞的生命,心系灾区同胞的你准备自己采购一些粮食支援灾区,现在假设你一共有资金n元,而市场有m种大米,每种大米都是袋装产品,其价格不等,并且只能整袋购买。
请问:你用有限的资金最多能采购多少公斤粮食呢?

Sample Input
1
8 2
2 100 4
4 100 2
 
Sample Output
400
 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<string.h>
 4 #include<algorithm>
 5 using namespace std;
 6 const int MAXN=110;
 7 
 8 int dp[MAXN];
 9 int value[MAXN];//每袋的价格
10 int weight[MAXN];//每袋的重量
11 int bag[MAXN];//袋数
12 int nValue,nKind;
13 
14 //0-1背包,代价为cost,获得的价值为weight
15 void ZeroOnePack(int cost,int weight)
16 {
17     for(int i=nValue;i>=cost;i--)
18       dp[i]=max(dp[i],dp[i-cost]+weight);
19 }
20 
21 //完全背包,代价为cost,获得的价值为weight
22 void CompletePack(int cost,int weight)
23 {
24     for(int i=cost;i<=nValue;i++)
25       dp[i]=max(dp[i],dp[i-cost]+weight);
26 }
27 
28 //多重背包
29 void MultiplePack(int cost,int weight,int amount)
30 {
31     if(cost*amount>=nValue) CompletePack(cost,weight);
32     else
33     {
34         int k=1;
35         while(k<amount)
36         {
37             ZeroOnePack(k*cost,k*weight);
38             amount-=k;
39             k<<=1;
40         }
41         ZeroOnePack(amount*cost,amount*weight);//这个不要忘记了,经常掉了
42     }
43 }
44 int main()
45 {
46     int T;
47     scanf("%d",&T);
48     while(T--)
49     {
50         //这个dp的初始化一定不要忘记,可以不装满则初始化为0,
51         //否则dp[0]=0,其余的为-INF
52         memset(dp,0,sizeof(dp));
53         scanf("%d%d",&nValue,&nKind);
54         for(int i=0;i<nKind;i++)
55           scanf("%d%d%d",&value[i],&weight[i],&bag[i]);
56         for(int i=0;i<nKind;i++)
57           MultiplePack(value[i],weight[i],bag[i]);
58         printf("%d
",dp[nValue]);
59     }
60     return 0;
61 }
原文地址:https://www.cnblogs.com/cnblogs321114287/p/4325236.html