hdu 5410 CRB and His Birthday(01+多重揹包 dp)

CRB and His Birthday

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


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

solution:

這道題我們可以先跑一遍01揹包,在跑一遍多重揹包。

思路:非常好的一道01揹包和完全揹包結合的題目 首先,對於第i件商品,如果只買1個,得到的價值是Ai+Bi 如果在買1個的基礎上再買,得到的價值就是Ai 也就是說,除了第一次是Ai+Bi,以後購買都是Ai 那麼,我們能否將i商品拆分成兩種商品,其中兩種商品的代價都是Wi, 第一種的價值是Ai+Bi,但是隻允許買一次 第二種的價值是Ai,可以無限次購買 接下來我們來討論這樣拆的正確性 理論上來講,買第二種之前,必須要買第一種 但是對於這道題,由於Ai+Bi>=Ai是必然的,因爲Bi肯定是非負 所以對於代價相同,價值大的肯定會被先考慮 換句話來說,如果已經開始考慮第二種商品了,那麼第一種商品就肯定已經被添加到揹包裏了

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 2500;
int dp[maxn], a[maxn], b[maxn],w[maxn];
int n, m;
int main()
{
    int t;
    scanf("%d", &t);
    while (t--)
    {
        memset(dp, 0, sizeof(dp));
        scanf("%d%d", &m,&n);
        for (int i = 1; i <= n; i++)
            scanf("%d%d%d",&w[i], &a[i], &b[i]);
        for (int i = 1; i <= n; i++)
        {
            for (int j = m; j >= w[i]; j--)
                dp[j] = max(dp[j], dp[j - w[i]] + a[i] + b[i]);
            for (int j = w[i]; j <= m; j++)
                dp[j] = max(dp[j], dp[j - w[i]] + a[i]);
        }
        printf("%d\n", dp[m]);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章