题解报告:hdu 2602 Bone Collector(01背包)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2602

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 ?
题解报告:hdu 2602 Bone Collector(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

1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14

解题思路:简单的01背包(dp)。

AC代码一:(二维数组实现)

 #include<bits/stdc++.h>
using namespace std;
const int maxn=;
int t,n,W,v[maxn],w[maxn],dp[maxn][maxn];
int main(){
while(cin>>t){
while(t--){
cin>>n>>W;
for(int i=;i<=n;++i)cin>>v[i];
for(int i=;i<=n;++i)cin>>w[i];
memset(dp,,sizeof(dp));
for(int i=;i<=n;++i){
for(int j=;j<=W;++j){
if(j<w[i])dp[i][j]=dp[i-][j];//无法挑选这个物品
else dp[i][j]=max(dp[i-][j],dp[i-][j-w[i]]+v[i]);//拿和不拿的两种情况都试一下
}
}
cout<<dp[n][W]<<endl;
}
}
return ;
}

AC代码二:(一维数组实现)

 #include<bits/stdc++.h>
using namespace std;
int value[],weight[],dp[];//dp数组始终记录当前体积的最大价值
int main()
{
int T,N,V;
cin>>T;
while(T--){
cin>>N>>V;
for(int i=;i<N;i++)cin>>value[i];//输入价值
for(int i=;i<N;i++)cin>>weight[i];//输入体积
memset(dp,,sizeof(dp));//初始化
for(int i=;i<N;i++){ //个数
for(int j=V;j>=weight[i];j--) //01背包
dp[j]=max(dp[j],dp[j-weight[i]]+value[i]); //比较放入i物体后的价值与不放之前的价值,记录大的值
}
cout<<dp[V]<<endl;//输出总体积的最大价值
}
return ;
}
上一篇:洛谷 题解 P2727 【01串 Stringsobits】


下一篇:CALayer的m34 - 三维透视效果