Bone Collector
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.
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背包:
首先我们要明白i,j,dp[i][j]都分别代表着什么
i:表示从1~i个物品里取
j:表示此时的最大容积
dp[i][j]:表示在1~i个物品里选取,每个物品只选择一次(限于01背包),且不超过j的容积,问所能得到的最大价值
得出一个转移方程f[i][j] = max(f[i][j], f[i - 1][j - c[i]] + w[i])
即在选取这个物品和不选这个物品中选择一个最大的
最后我们要输出的就是dp[n][m]表示在n个物品中,容积不超出m的最大价值
1 #include2 #include 3 #include 4 using namespace std; 5 int f[1101][1101]; 6 int main() 7 { 8 int t; 9 cin>>t; 10 for (int i=1 ;i<=t ;i++){ 11 memset(f,0,sizeof f); 12 int n,v; 13 int w[1001], c[1001]; 14 cin >> n >> v; 15 for(int i = 1; i <= n; ++i) 16 cin >> w[i] ; 17 for (int i=1 ;i<=n ;i++) 18 cin>>c[i]; 19 for(int i = 1; i <= n; ++i) 20 for(int j = 0; j <= v; ++j) 21 { 22 f[i][j] = f[i - 1][j]; 23 if(j >= c[i]) 24 f[i][j] = max(f[i][j], f[i - 1][j - c[i]] + w[i]); 25 } 26 cout << f[n][v]<<endl; 27 } 28 return 0; 29 }