HDU 5410 CRB and His Birthday

題目連接:http://acm.hdu.edu.cn/showproblem.php?pid=5410php

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
1 100 2 10 2 1 20 1 1
 

 

Sample Output
21
Hint
CRB's mom buys 10 presents of first kind, and receives 2 × 10 + 1 = 21 candies.
 
題目的大概意思是有M元錢,有N件物品,沒件物品的花費是W[i],第i件物品買X件能獲得A[i]*X+B[i]塊糖,沒件物品買的數量沒有上限
問這M元錢最多能獲得多少塊糖。
問題分析:沒種物品買第一件能獲得A[i]+B[i]塊糖,之後每買一件只能多獲得A[i]塊糖,也就是每種物品買第一件比買後面的獲得的糖多,
              根據貪心的思想很容易想到要先每種物品買一件再買大於一件,這樣就把問題分紅了兩個階段,第一階段每種物品最多隻買一件,
              0/1揹包,第二階段,沒種物品能買無限件,徹底揹包。
 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 int ma(int a,int b)
 6 {
 7     if (a>b)
 8     return a;
 9     else
10     return b;
11 }
12 int main()
13 {
14     int ans[12000],v,a[1100],b[1100],c[1100],n,m,T;
15     cin>>T;
16     while (T--)
17     {
18           cin>>v>>m;
19           for (int i=1;i<=m;i++)
20           cin>>c[i]>>a[i]>>b[i];
21           memset(ans,0,sizeof(ans));
22           for (int i=1;i<=m;i++)//處理第一階段,0/1揹包 
23           {
24               for (int j=v;j>=c[i];j--)
25               {
26                   ans[j]=ma(ans[j],ans[j-c[i]]+a[i]+b[i]);              
27               }
28           }
29           for (int i=1;i<=m;i++)//處理第二階段,徹底揹包。 
30           {
31               for (int j=c[i];j<=v;j++)
32               {
33                    ans[j]=ma(ans[j],ans[j-c[i]]+a[i]);
34               }
35           }
36           cout <<ans[v]<<endl;
37     }
38     return 0;
39 }   
View Code
相關文章
相關標籤/搜索