您的位置:首页 > 其它

HDU 2602 Bone Collector

2015-08-16 16:21 330 查看
HDU 2602 Bone Collector

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

动态规划是用空间换时间的一种方法的抽象。其关键是发现子问题和记录其结果。然后利用这些结果减轻运算量。

比如01背包问题。

/* 一个旅行者有一个最多能用M公斤的背包,现在有N件物品,

它们的重量分别是W1,W2,…,Wn,

它们的价值分别为P1,P2,…,Pn.

若每种物品只有一件求旅行者能获得最大总价值。

输入格式:

M,N

W1,P1

W2,P2

……

输出格式:

X

*/

因为背包最大容量M未知。所以,我们的程序要从1到M一个一个的试。比如,开始任选N件物品的一个。看对应M的背包,能不能放进去,如果能放进去,并且还有多的空间,则,多出来的空间里能放N-1物品中的最大价值。怎么能保证总选择是最大价值呢?看下表。

测试数据:

10,3

3,4

4,5

5,6

c[i][j]数组保存了1,2,3号物品依次选择后的最大价值.

这个最大价值是怎么得来的呢?从背包容量为0开始,1号物品先试,0,1,2,的容量都不能放.所以置0,背包容量为3则里面放4.这样,这一排背包容量为4,5,6,….10的时候,最佳方案都是放4.假如1号物品放入背包.则再看2号物品.当背包容量为3的时候,最佳方案还是上一排的最价方案c为4.而背包容量为5的时候,则最佳方案为自己的重量5.背包容量为7的时候,很显然是5加上一个值了。加谁??很显然是7-4=3的时候.上一排 c3的最佳方案是4.所以。总的最佳方案是5+4为9.这样.一排一排推下去。最右下放的数据就是最大的价值了。(注意第3排的背包容量为7的时候,最佳方案不是本身的6.而是上一排的9.说明这时候3号物品没有被选.选的是1,2号物品.所以得9.)

从以上最大价值的构造过程中可以看出。

标准的01背包问题。状态转移方程

f[i][v] = max{f[i-1][v-c[i]]+v[i],f[i-1][v]}

[code]#include <iostream>
#include <cstdio>
#include <string.h>
#include <math.h>
using namespace std;
int main()
{
#ifndef  ONLINE_JUDGE
    freopen("1.txt", "r", stdin);
#endif
    int t, n, v, value[1002], volume [1002], record[1002];
    int i, j;
    cin >> t;
    while(t--)
    {
        memset(record, 0, sizeof(record));
        cin >> n >> v;
        for(i = 0; i < n; i++)
        {
            scanf("%d", &value[i]);
        }
        for (i = 0; i < n; i++)
        {
            scanf("%d", &volume[i]);
        }
        for(i = 0; i < n; i++)
        {
            for (j = v; j >= volume[i]; j--)
            {
                if (record[j - volume[i]] + value[i] > record[j])
                {
                    record[j] = record[j - volume[i]] + value[i];
                }
            }
        }
        cout << record[v] << endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: