Consumer (HDU_3449) 有依赖的背包问题

来源:互联网 发布:js定时刷新 编辑:程序博客网 时间:2024/05/31 11:04

Consumer

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/65536 K (Java/Others)
Total Submission(s): 1908    Accepted Submission(s): 1014


Problem Description
FJ is going to do some shopping, and before that, he needs some boxes to carry the different kinds of stuff he is going to buy. Each box is assigned to carry some specific kinds of stuff (that is to say, if he is going to buy one of these stuff, he has to buy the box beforehand). Each kind of stuff has its own value. Now FJ only has an amount of W dollars for shopping, he intends to get the highest value with the money.
 

Input
The first line will contain two integers, n (the number of boxes 1 <= n <= 50), w (the amount of money FJ has, 1 <= w <= 100000) Then n lines follow. Each line contains the following number pi (the price of the ith box 1<=pi<=1000), mi (1<=mi<=10 the number goods ith box can carry), and mi pairs of numbers, the price cj (1<=cj<=100), the value vj(1<=vj<=1000000)
 

Output
For each test case, output the maximum value FJ can get
 

Sample Input
3 800300 2 30 50 25 80600 1 50 130400 3 40 70 30 40 35 60
 

Sample Output
210


题目大意:有现金w,以及n个箱子,箱子的价格为pi,箱子中有mi件物品,每件物品有各自的价格ci和价值vj,求问购买哪几个箱子能购得最大价值,箱子中的物品可买可不买。

解题思路:有依赖的背包问题。需要对每个箱子进行01背包,然后再将得到的值跟原先的未购买该箱子的值进行比较(其实是隐式地进行分组背包)dp[j] = max(dp[j],kdp[j - v])。

代码如下:

#include"iostream"#include"cstdio"#include"cstring"#define INF 11000000 using namespace std;const int maxn = 100010;int dp[maxn];int kdp[maxn];int max(int x,int y){return x>y?x:y;}int main(){int n,V,v,mi,cost,val,i,j,k;while(scanf("%d%d",&n,&V) != EOF){memset(dp,0,sizeof(dp));for(i = 1;i <= n;i ++){scanf("%d%d",&v,&mi);memcpy(kdp,dp,sizeof(dp));for(j = 1;j <= mi; j ++){scanf("%d%d",&cost,&val); for(k = V - v;k >= cost; k --){//01背包对附件组合进行压缩 kdp[k] = max(kdp[k],kdp[k - cost] + val); }}for(j = v;j <= V;j++){dp[j] = max(dp[j],kdp[j - v]);}}printf("%d\n",dp[V]);}return 0;}


0 0
原创粉丝点击