hdu2602 01揹包 題解

習DP,甚是迷惑,審其題,雖解其意,但無從下口,故棄而學揹包,今日,重拾之,遂發現其乃美味也。故知揹包乃DP之基也~

嘻嘻~~小小嘚瑟一下

      我是剛開始接觸算法,就被諸位大神弄去學了DP,但是一知半解,遇到這道題的時候,怎麼也想不出該怎麼做。在我的師兄們(比我高一級的小菜,噓,別讓他聽到了)的指引下,看了揹包,今天再來看這道題~~~~大神  你在逗我玩嗎~~~~~

   建議剛開始學dp的人 , 一定要去看看揹包九講,很精彩~~~

   廢話少數,切入正題

E - Bone Collector
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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 31).
 

Sample Input

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

Sample Output

14

題意分析:一個骨頭蒐集愛好者,收集各類各樣的骨頭,這個骨頭愛好者有一個大袋子,容積是一定的,現給出一定的骨頭,每個骨頭的容積和價值是固定的,現在我們往袋子中裝入骨頭,求袋子容積所能承受的條件下的可裝的最大價值。

思路分析:這是個典型的01揹包,狀態轉移方程模板如下

for(int i = 1; i <= N; i++)//N骨頭的總數
{
    for(int j = V; j <= v[i]; j--)//本題中,V指的是袋子的容積,v[i]指第i個骨頭的體積,d[i]指第i個骨頭的價值
    {
        dp[j]=max(dp[j],dp[j-v[i]]+d[i]);
    }
}

現給出AC代碼

#include <iostream>
#include<cstdio>
#include<string.h>
using namespace std;
const int MAX = 1000+10;
int dp[MAX];
int d[MAX];
int v[MAX];
int T,N,V;

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        memset(dp,0,sizeof(dp));
        scanf("%d%d",&N,&V);
        for(int i = 1; i <= N; i++)
        {
            scanf("%d",&d[i]);
        }
        for(int j = 1; j <= N; j++)
        {
            scanf("%d",&v[j]);
        }
        for(int i = 1; i <= N; i++)
        {
            for(int j = V; j >= v[i];j--)
            {
                dp[j]=max(dp[j],dp[j-v[i]]+d[i]);
            }
        }
        printf("%d\n",dp[V]);
   }
    return 0;
}



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