Bone collector//动态规划

题目

Bone Collector
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 89519 Accepted Submission(s): 36853

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


思路

关键在转移方程的理解,

if(j < valume[i])
    a[i][j] = a[i-1][j];
else
    a[i][j] = max(a[i-1][j], a[i-1][j-valume[i]]+value[i]);

先解释下a,i,j的含义,这里a[i][j]中是考虑第i项东西后的当前最大价值,j代表的是背包可用体积.
然后最难理解的就是else后这句,(考虑第i样物品时,背包体积为j时的最大价值)等于{(考虑i-1样物品时的最大价值)和(除掉第i件物品的体积后剩下体积所能盛放的最大价值加上第i件物品的价值)中的最大值}
有点像最短路中dijkstra中的想法,新拿进去一个点,在用那个点来对原来的最短路进行松弛.

代码

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

int dp(int n, int v, int * value, int * valume)
{
    int a[1000][1000] = {0};
    for(int i = 1; i <= n; i++)
    {
        for(int j = 0; j <= v; j++)//从0开始
        {
            if(j < valume[i])
            {
                a[i][j] = a[i-1][j];
            }
            else 
            {
                a[i][j] = max(a[i-1][j], a[i-1][j-valume[i]]+value[i]);
            }
        }
    }
    return a[n][v];
}

int main()
{
    int num, n, v;
    int value[1000+10];
    int valume[1000+10];
    cin >> num;
    while(num--)
    {
        cin >> n >> v;
        //下标从1开始会方便点.
        for(int i = 1; i <= n; i++)
        {
            cin >> value[i];
        }
        for(int i = 1; i <= n; i++)
        {
            cin >> valume[i];
        }
        int ans = dp(n,v,value,valume);
        cout << ans << endl;
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/10161814.html