题目链接: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 ?
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 231).
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
解题思路:简单的01背包(dp)。
AC代码一:(二维数组实现)
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1005; 4 int t,n,W,v[maxn],w[maxn],dp[maxn][maxn]; 5 int main(){ 6 while(cin>>t){ 7 while(t--){ 8 cin>>n>>W; 9 for(int i=1;i<=n;++i)cin>>v[i]; 10 for(int i=1;i<=n;++i)cin>>w[i]; 11 memset(dp,0,sizeof(dp)); 12 for(int i=1;i<=n;++i){ 13 for(int j=0;j<=W;++j){ 14 if(j<w[i])dp[i][j]=dp[i-1][j];//无法挑选这个物品 15 else dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]);//拿和不拿的两种情况都试一下 16 } 17 } 18 cout<<dp[n][W]<<endl; 19 } 20 } 21 return 0; 22 }
AC代码二:(一维数组实现)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int value[1005],weight[1005],dp[1005];//dp数组始终记录当前体积的最大价值 4 int main() 5 { 6 int T,N,V; 7 cin>>T; 8 while(T--){ 9 cin>>N>>V; 10 for(int i=0;i<N;i++)cin>>value[i];//输入价值 11 for(int i=0;i<N;i++)cin>>weight[i];//输入体积 12 memset(dp,0,sizeof(dp));//初始化 13 for(int i=0;i<N;i++){ //个数 14 for(int j=V;j>=weight[i];j--) //01背包 15 dp[j]=max(dp[j],dp[j-weight[i]]+value[i]); //比较放入i物体后的价值与不放之前的价值,记录大的值 16 } 17 cout<<dp[V]<<endl;//输出总体积的最大价值 18 } 19 return 0; 20 }