背包系列 hdu3449 有依赖背包

  这道题真正困扰了笔者3,4天,冥思苦想几日无果之后,只能去找大牛的解法。结合网上的大牛解法与自己的理解,笔者终于解决了这个坑了,在此小庆幸一下。

  原题如下:

  

Consumer
Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/65536 K (Java/Others)
Total Submission(s): 2154    Accepted Submission(s): 1157


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
View Code

AC代码如下:其中dp使用了滚动数组。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int dp[2][100010];
int main()
{
    int n,w;
    while(~scanf("%d%d",&n,&w))
    {
        memset(dp,0,sizeof(dp));
        for(int i=0;i<n;++i)
        {
            int pi,mi;
            scanf("%d%d",&pi,&mi);
            //这里做了个假设,假设dp[1][j]组必须加本轮的箱子
            //得到结果后和上一轮的结果比
            for(int j=0;j<=w-pi;++j)
                dp[1][j+pi] = dp[0][j];
            for(int j=0;j<mi;++j)
            {
                int cj,wj;
                scanf("%d%d",&cj,&wj);
                //当v-cj小于pi,表示连箱子都买不起
                for(int v=w;v-cj>=pi;--v)
                {
                    //01背包
                    dp[1][v] = max(dp[1][v],dp[1][v-cj]+wj);
                }
            }
            for(int v=w;v>=0;--v)
            {
                //跟上一轮比,得出v的最佳答案。
                dp[1][v] = max(dp[1][v],dp[0][v]);
                //滚动数组
                dp[0][v] = dp[1][v];
            }


        }

        printf("%d
",dp[1][w]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jlyg/p/6644947.html