HDU 2602 Bone Collector(动态规划初步)

网上关于动态规划的讲解实在是太多了,最近自己也开始真正的开始学习动态规划。用了HDU 2602 Bone Collector 作为我学习的例子,其实这就是个01背包问题,选择将哪些骨头放到包里使得包里的骨头价值最大。
作为初学者,我很不喜欢上来就说子问题,最优子结构,状态转移方程,一开始就直接接触这些我们大脑里没有明确的概念。就像我上学期学C语言时一直疑惑为什么每一个程序都要加上#include <stdio.h>,我就去问老师。老师说先不用理解,学到后面,代码写的多了,你自然就明白。想想当初如果老师直接上来就讲这是头文件包含指令,在编译预处理阶段编译器会去MinGW目录下的include文件夹中寻找标准输入输出文件,并将其包含到代码里。估计我是肯定听不懂的。
所以我不会用到一些术语,我们现在只知道这是一道动态规划问题,我们只想着如何去解决它,而不是以一种已经掌握了动态规划的视角去分析它。
用题目中的样例数据进行分析
1
5 10
1 2 3 4 5
5 4 3 2 1
显然,每一块骨头只有放与不放两种状态
现在用f(i,j)来表示有选择的将前i根骨头放进体积为j的背包里,背包里所含骨头的最大值
现在轮到了第i+1根骨头。
假设我把第i+1根骨头放进包里(背包能容得下),那么背包中骨头最大总值为f(i,j-vol(i+1))+val(i);
假设我不把第i+1根骨头放进包里,那么背包中骨头最大总值为f(i,j)
那么f(i+1, j)=Max{ f(i,j), f(i,j-vol(i+1))+val(i) }

理论讲解大约就是这样,现在到了实践环节,按照下面的程序,将表填好,填个5,6遍,那么DP在我们脑海里也就会有个初步印象了
HDU 2602 Bone Collector(动态规划初步)_第1张图片
PS:填表的顺序是从右到左,从上到下,选的数据是题目中的样例

代码:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

typedef struct i
{
    int val;
    int v;
}item;

int dp[1010];
int main()
{
    item items[1010];
    int T, N, V;
    int i, j;
    cin>>T;
    while(T--)
    {
        memset(dp, 0, sizeof(dp));
        cin>>N>>V;
        for(i=1;i<=N;i++)
            cin>>items[i].val;
        for(i=1;i<=N;i++)
            cin>>items[i].v;
        for(i=1;i<=N;i++)
            for(j=V;j>=items[i].v;j--)
                dp[j]=max(dp[j], dp[j-items[i].v]+items[i].val);
        cout<<dp[V]<<endl;
    }
    return 0;
}

原题:
Bone Collector

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 46149 Accepted Submission(s): 19198

Problem Description
Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave …
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?

Input
The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output
One integer per line representing the maximum of the total value (this number will be less than 231).

Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1

Sample Output
14

你可能感兴趣的:(动态规划)