天天看點

Bone Collector------HDOJ杭電2602(純01背包問題!!!!!!詳解!)

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 ?

Bone Collector------HDOJ杭電2602(純01背包問題!!!!!!詳解!)

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

Sample Output

先輸入一個t,代表有t個例子,然後輸入n和v,n代表有多少骨頭,v代表背包體積,每樣東西隻有一個,也就是說隻能取一次,剛開始看這道題的時候完全不知道怎麼做,感覺會很麻煩的樣子,學長是作為例題給我們講的,剛開始有點頭緒,但具體還是完全不懂,後來自己專門刷這方面的專題,還算了解的比較好,動态規劃的思想得要了解好,這題是用空間換時間,過程中會産生大量之間資料,嗯,就是這樣,好了,回到這道題,我們用一維數組來存儲資料,但是有些pdf文檔比如背包九講就是用二維數組來講解,都可以的。

現在進入正題:輸入前面講過了,現在講核心代碼

這三行就是核心,就像背包九講裡面說的,這個狀态轉移方程非常重要,一定要了解,它聯系了上一個狀态和這一個狀态,是以叫做狀态轉移方程!!!!!!

為了更加清楚描述運作過程中數組每個值的具體變化,我在這裡加了幾行代碼:

我們以題目給的資料為例,運作結果如下:

Bone Collector------HDOJ杭電2602(純01背包問題!!!!!!詳解!)

從圖中我們可以看出(結合上面的代碼),程式循環五次,每次循環的結果都在動态變化,如果還不能了解,建議自己在草稿子上模拟i=1,i=2的時候數組變化的情況,就會很好了解了,動态規劃給我的感覺就是代碼很短,但是了解之後就很簡單了!!!!!!

好了,講完了,最近在做dp專題,會不定時更新做題的心得還有題解,大家一起學習!

下面貼下AC代碼:

寫代碼能力有限,如有程式設計愛好者發現bug,還請指出,不勝感激!