Bone Collector

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 2[sup]31[/sup]).

Sample Input

1
5 10
1 2 3 4 5
5 4 3 2 1

Sample Output

14

題目大意

輸入第一行爲一個整數表示T組測試樣例。
每組測試樣例有三行:
第一行包含兩個整數N, V, (N <= 1000, V <= 1000),代表骨頭的數量和他的包的體積。
第二行包含N個整數代表每根骨頭的值。
第三行包含N個整數,代表每根骨頭的體積。
現在需要求怎麼裝骨頭能時所裝骨頭的值最大。輸出這個最大值即可。

解題思路

這是一道01揹包模板題,有關01揹包的詳細講解鏈接是
這裏寫鏈接內容

代碼
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int weight[1005]; //各個物品的體積。
int value[1005];//各個物品的價值。
int f[1005]; //f[j]意味容積j時的最優解。
int main()
{
    int T,N,V;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d %d",&N,&V);
        for(int i=0;i<N;i++)
        {
            scanf("%d",&value[i]);
        }
        for(int i=0;i<N;i++)
        {
            scanf("%d",&weight[i]);
        }
        memset(f,0,sizeof(f)); //先把f[]初始化爲0。
        for(int i=0;i<N;i++)   //找出容積爲 j 時向背包裏裝物品的最優解
        {
            for(int j=V;j>=weight[i];j--)
            {
                f[j]=max(f[j],f[j-weight[i]]+value[i]);
            }
        }                 //求最優解結束
        cout << f[V] << endl;
        }
        return 0;
}

是不是很容易懂啊(* ̄rǒ ̄)。客官 留下小心心再走。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章