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
题目分析
经典的有依赖的背包问题,要选择某一物品,必须选择另一个物品,这个题目相比于树形的那种,这个更容易些。
对于每一个箱子box,我们可以选择不选这个箱子,或者选择这个箱子以及其中的物品,在各个费用下取两者中的最大值,从这里看起来就是个01背包的问题,不过我们需要求出选择这个箱子以及其中的物品在各个费用下可以得到的最大价值
记箱子i 的价格是box,显然,当花费 j < box的时候是无法购买箱子的,那么我们得到其他花费就不能从这个状态转移而来,记dp[i][j] = -1,表示这个状态不可以转移
当 j >= box 的时候,花费的钱 j 中有 box 元 用于购买箱子,因此此时的价值dp[i][j] 和不买箱子前使用费用 j - box 得到的最大价值一致,此时 dp[i][j] = dp[i - 1][j - box];
然后,现在的 dp[i] 表示选了箱子后的状态,之后直接对箱子中的物品进行01背包求各个费用下的最大价值
if(dp[i][j-cost] != -1) //当转移前的容积小于box,表示这个状态没有买箱子,无法从这个状态转移
{
dp[i][j] = max(dp[i][j], dp[i][j - cost] + val);
}
经过上述操作,我们得到了选择当前箱子 i 的的情况下,各个费用下的最大价值,随后我们就要去和不选择这个箱子的情况下,各个费用下的最大价值,取两者中的最大值,得到挑选过箱子 i 后得到的各个费用下的最大价值。
代码区
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
//#define LOCAL = 1;
using namespace std;
typedef long long ll;
const int Max = 1e5 + 10;
int n, m;
ll dp[55][Max];
int main()
{
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
while (scanf("%d%d", &n, &m) != EOF)
{
memset(dp, 0, sizeof(dp)); //初始化
for(int i = 1 ;i <= n;i ++)
{
int box, num;
scanf("%d%d", &box, &num);
for (int j = 0;j < box; j++) //总费用小于box,无法买任何物品
dp[i][j] = -1;
for (int j = box;j <= m; j++) //由前一个状态j-box,选择了当前的盒子后转移而来
dp[i][j] = dp[i - 1][j - box];
//上述表示选择了当前的盒子后的价值(没有和不选进行比较)
for(int k = 0 ;k < num ; k ++) //由01背包从选择了箱子的状态转移到其余状态
{
int cost;ll val;
scanf("%d%lld", &cost, &val);
for(int j = m ; j >= cost ;j --)
{
if(dp[i][j-cost] != -1) //当转移前的容积小于box,表示这个状态没有买箱子,无法从这个状态转移
{
dp[i][j] = max(dp[i][j], dp[i][j - cost] + val);
}
}
}
for (int j = 0;j <= m;j++) //和不选择此盒子作比较
dp[i][j] = max(dp[i][j], dp[i - 1][j]);
}
printf("%lld\n", dp[n][m]);
}
return 0;
}