CRB and His Birthday(完全背包变形)

来源:互联网 发布:unity3d 过山车轨道 编辑:程序博客网 时间:2024/04/30 13:34


Link:http://acm.hdu.edu.cn/showproblem.php?pid=5410


CRB and His Birthday

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 440    Accepted Submission(s): 244


Problem Description
Today is CRB's birthday. His mom decided to buy many presents for her lovely son.
She went to the nearest shop with M Won(currency unit).
At the shop, there are N kinds of presents.
It costs Wi Won to buy one present of i-th kind. (So it costs k × Wi Won to buy k of them.)
But as the counter of the shop is her friend, the counter will give Ai × x + Bi candies if she buys x(x>0) presents of i-th kind.
She wants to receive maximum candies. Your task is to help her.
1 ≤ T ≤ 20
1 ≤ M ≤ 2000
1 ≤ N ≤ 1000
0 ≤ Ai, Bi ≤ 2000
1 ≤ Wi ≤ 2000
 

Input
There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contains two integers M and N.
Then N lines follow, i-th line contains three space separated integers WiAi and Bi.
 

Output
For each test case, output the maximum candies she can gain.
 

Sample Input
1100 210 2 120 1 1
 

Sample Output
21
Hint
CRB's mom buys 10 presents of first kind, and receives 2 × 10 + 1 = 21 candies.
 

Author
KUT(DPRK)
 

Source
2015 Multi-University Training Contest 10
 


题意:题意就不一一翻译了,直接看Input部分说明就好了,将题意抽象成背包问题就是,给出背包的最大容量M,物品个数N,对于第i种物品,其对应的单个的容量是W[i],假设最后背包里第i种物品装了x个,则第i种物品能取得的价值是a[i]*x+b[i],问对于给出的这n种物品,怎样做能使最终装到背包里的每种物品产生的价值总和最大,求出这个最大价值。


编程思想:由于物品价值不是固定的,对于第i种物品,拿第一个时能得到的价值是a[i]+b[i],接着从第二个开始,若要再拿的话每次价值只能累加a[i],也就是说分成问题可以分成两个阶段,第一个阶段物品i的固定价值是a[i]+b[i],第二个阶段固定价值是a[i],这样的话相当于每个阶段的价值被固定住了,然后基于贪心的思想,要想最终价值最大,则第一阶段先求出最大价值来,然后再基于第一阶段求出的结果,第二阶段继续求最大价值,最终得到的价值肯定就是最优解,也就是价值最大的。所以,只要对每一阶段判断是何种裸背包问题就行了。可以先将问题分成这两个过程,依次处理这两个阶段,很明显,第一阶段对于每种物品,最多只能取一个,很明显就是01背包。第二阶段由于每种物品数量没有限制,所以就是裸的完全背包。


AC code:

#include<iostream>#include<algorithm>#include<cstring>#include<cstdio>#include<cmath>#include<queue>#include<vector>#define LL long long#define MAXN 1000010using namespace std;int f[MAXN];int c[MAXN],a[MAXN],b[MAXN];int V,n;void init()//01背包初始化第一阶段 {memset(f,0,sizeof(f));for(int i=1;i<=n;i++){for(int j=V;j>=c[i];j--){f[j]=max(f[j],f[j-c[i]]+a[i]+b[i]);}}}void Complete()//完全背包处理第二阶段 {for(int i=1;i<=n;i++){for(int j=c[i];j<=V;j++){f[j]=max(f[j],f[j-c[i]]+a[i]);}}}int main(){int i,t;scanf("%d",&t);while(t--){scanf("%d%d",&V,&n);for(i=1;i<=n;i++){scanf("%d%d%d",&c[i],&a[i],&b[i]);}init();//01背包初始化第一阶段 Complete();//完全背包处理第二阶段printf("%d\n",f[V]);}return 0; } 


0 0
原创粉丝点击