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 800
300 2 30 50 25 80
600 1 50 130
400 3 40 70 30 40 35 60
Sample Output
210
分析:
题意:有钱V,给出n组选择,每组选择有m个物品,要买物品先必须买盒子花费q,物品价格为w[i],价值value[i]。
dp[i][j]表示第i组背包容量为j时的最大价值。
首先当重新进行一组的时候要进行初始化工作
当这个盒子的价格是q的时候,当前组下的所有比q容量小的背包都买不了,则价值赋值为-INF
比q容量大的背包要根据上一组的背包来买,注意这里买盒子是不能获得相应的价值的
当选择这个盒子里面的所有的物品的时候,盒子里面的物品进行01背包,可以再改组下选择这个物品选或则不选,取较大值
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 1<<29
int n,V,m,q;
int w[11],value[11];
int dp[51][100003];
int main()
{
int i, j, x;
while(~scanf("%d%d",&n,&V ))
{
memset(dp,0,sizeof(dp));
for(i=1; i<=n; i++)
{
scanf("%d%d",&q,&m);
for(x=1; x<=m; x++)
scanf("%d%d",&w[x],&value[x]);
for(j=0; j<=q; j++)//比q容量小的背包都没不了
dp[i][j]=-INF;
for(j=q; j<=V ; j++)//在上一组的基础上进行转移,但是没有价值
dp[i][j]=dp[i-1][j-q];
for(x=1; x<=m; x++)//其余的改组里的所有物品进行01
for(j=V ; j>=w[x]; j--)
dp[i][j]=max(dp[i][j],dp[i][j-w[x]]+value[x]);
//如果选dp[i][j]说明选了当前组的物品和盒子,
//如果选dp[i-1][j]说明没有选当前组的物品和盒子。
for(j=0; j<=V ; j++)//这里可以表示整个的当前组选或者不选
dp[i][j]=max(dp[i][j],dp[i-1][j]);
}
printf("%d
",dp[n][V ]);
}
return 0;
}