1. 程式人生 > >Bone Collector 0-1揹包問題

Bone Collector 0-1揹包問題

題目描述:

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 ? 

輸入:

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.

輸出:

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
題目大意:
有一個人喜歡收集骨頭(呃),現在有N根骨頭,每根骨頭對應著各自的體積和價值,這個人的揹包容量為V,求能裝的骨頭的最大總價值。
程式碼:
#include<iostream>
#include<stdio.h>
#define
max(a,b) a>b?a:b struct bone{ int wei,val; }; int f[1002][1002]; bone temp[1005]; int value(int num,int v){ for(int i=1;i<=num;++i){ for(int j=0;j<=v;++j){ if(j<temp[i-1].wei) f[i][j]=f[i-1][j]; else f[i][j]=max(f[i-1][j-temp[i-1].wei]+temp[i-1].val,f[i-1][j]); } } return f[num][v]; } using namespace std; int main(){ int n,num,v; scanf("%d",&n); for(int i=0;i<n;++i){ scanf("%d%d",&num,&v); for(int j=0;j<num;++j) scanf("%d",&temp[j].val); for(int j=0;j<num;++j) scanf("%d",&temp[j].wei); printf("%d\n",value(num,v)); } return 0; }

這是一道0-1揹包問題,要解決的問題就是要放哪些物品進揹包,總價值是多少。

而對於每一個物品只有放與不放兩種情況:

1. 第i件放進去:價值為:f[i-1][v-temp[i-1].wei]+temp[i-1].val(揹包容量減去第i件物品的體積,再加上對前i-1件進行判斷後得到價值的最大值(容量為v-temp[i-1].wei的揹包))

2. 第i件不放進去:價值為:f[i-1][v](容量不減少(為v),對前i-1件進行判斷後得到價值的最大值)

狀態轉移方程為:f[i][v] = max(f[i-1][v], f[i-1][v-w[i]]+c[i])

隨後對兩種情況取較大值。第一行初始化為0.從第一個物品開始列表記錄揹包容量內剩餘不同容積存放前i個物品情況的最大值。

這個解法比較容易理解,下面的連結有對揹包問題更詳盡的解釋,受啟發於此:

https://www.cnblogs.com/A-S-KirigiriKyoko/p/6036368.html

https://www.cnblogs.com/xym4869/p/8513801.html

(其中的程式碼將第一列也初始化為0,這樣子的話當物品中同時存在體積=揹包容量的物品和體積=0的物品時就會出錯,因此稍作改動)