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 ofW 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) Thenn lines follow. Each line contains the following number pi (the price of the ith box 1 ≤pi ≤1000), mi (1 ≤ mi ≤ 10 the number goodsi-th box can carry), and mi pairs of numbers, the pricecj (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 本题的解题思想:1.创建两个数组(在此我创建了一个二维数组dp[2][]),其中,dp[0]为处理数据的即时数组,dp[1]为更新状态的数组 2.在此就有一条思考的隐形分割线, 我们可以从两个方面思考这个问题,首先我们要知道,买物品必须买对应的箱子,而我们有两个数组,所以我们可以考虑 dp[0]不买箱子,而dp[1]更新时把箱子买上或者dp[0]买箱子,dp[1]直接更新,这两种代码在细节上有些不同 1.dp[0]不买箱子
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cstdio>
using namespace std;
int dp[2][100005];
struct a
{
int c;int v;
}x[15];
int main()
{
int n, w, p, m;
int i, j, k;
while(~scanf("%d%d", &n, &w))
{
memset(dp[1], 0, sizeof(dp[1]));//初始化更新数组
while(n--)
{
scanf("%d%d", &p, &m);
memcpy(dp[0], dp[1], sizeof(dp[1]));将更新数组贴到即时数组上,由于dp[0]不买箱子,因此不需要对买箱子这一条件进行处理
for(i = 1; i <= m; i++)
{
scanf("%d%d", &x[i].c, &x[i].v);
}
for(i = 1; i <= m; i++)
{
for(j = w - p; j >= x[i].c; j--)//不买箱子,需要用w减去箱子的价钱q
{
dp[0][j] = max(dp[0][j], dp[0][j - x[i].c] + x[i].v);
}
}
for(i = p; i <= w; i++)
{
dp[1][i] = max(dp[1][i], dp[0][i - p]);
}
}
printf("%d\n", dp[1][w]);
}
}
2.dp[0]买箱子
#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<cstdio>
#include<climits>
#include<ctime>
#include<vector>
#include<queue>
#include<map>
using namespace std;
int dp[2][100005];
struct a
{
int c;int v;
}x[15];
int main()
{
int n, w, p, m;
int i, j, k;
while(~scanf("%d%d", &n, &w))
{
memset(dp[1], 0, sizeof(dp[1]));
while(n--)
{
scanf("%d%d", &p, &m);
for(i = 0; i < p; i++)
dp[0][i] = -1;
for(i = p; i <= w; i++)
dp[0][i] = dp[1][i - p];//dp[0]是买箱子的,而dp[1]没有买这个箱子,因此要减去箱子价钱p
for(i = 1; i <= m; i++)
{
scanf("%d%d", &x[i].c, &x[i].v);
}
for(i = 1; i <= m; i++)
{
for(j = w; j >= x[i].c; j--)
{
if(dp[0][j - x[i].c] != -1)
dp[0][j] = max(dp[0][j], dp[0][j - x[i].c] + x[i].v);
}
}
for(i = 0; i <= w; i++)
{
dp[1][i] = max(dp[1][i], dp[0][i]);
}
}
printf("%d\n", dp[1][w]);
}
}
tips:什么时候减去箱子价钱,是在对dp数组有良好理解后的决策,dp[][i] = a表示买了i(价钱)的商品后商品的总价值,而这里的i如果包含箱子这一无价值的物品,
那么就有dp[][i - p](p为箱子价钱) == dp[][i] = a,理解了这一点,就能写出正确的状态转移方程