HDU 2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活 动态规划多重背包
http://acm.hdu.edu.cn/showproblem.php?pid=2191
题意:
给出大米的价格、重量和袋数,要你计算出在规定的钱数内买最多(重)的米。
坑爹:
算是多重背包问题的模版题吧。
解法:
多重背包。
View Code
1 #include<iostream> 2 using namespace std; 3 4 const int maxn = 20000 + 10; 5 int n; 6 int DP[maxn]; 7 8 int max(int a,int b) 9 { 10 return a > b ? a : b; 11 } 12 13 void ZeroOnePack(int cost,int weight) 14 { 15 int j; 16 for(j=n; j>=cost; j--) 17 { 18 DP[j] = max(DP[j] , DP[j-cost]+weight); 19 } 20 } 21 22 void CompletePack(int cost,int weight) 23 { 24 int j; 25 for(j=cost; j<=n; j++) 26 { 27 DP[j] = max(DP[j] , DP[j-cost]+weight); 28 } 29 } 30 31 void MultiplePack(int cost,int weight,int amount) 32 { 33 if(cost * amount >= n) 34 { 35 CompletePack(cost,weight); 36 return ; 37 } 38 int k = 1; 39 while(k<amount) 40 { 41 ZeroOnePack(k*cost,k*weight); 42 amount = amount - k; 43 k = k * 2; 44 } 45 ZeroOnePack(amount*cost,amount*weight); 46 } 47 48 int main() 49 { 50 int T; 51 cin>>T; 52 while(T--) 53 { 54 int m; 55 cin>>n>>m; 56 int worth[maxn]; 57 int heavy[maxn]; 58 int num[maxn]; 59 int i; 60 memset(DP,0,sizeof(DP)); 61 for(i=1; i<=m; i++) 62 { 63 cin>>worth[i]>>heavy[i]>>num[i]; 64 } 65 for(i=1; i<=m; i++) 66 { 67 MultiplePack(worth[i],heavy[i],num[i]); 68 } 69 cout<<DP[n]<<endl; 70 71 } 72 return 0; 73 }

浙公网安备 33010602011771号