01背包 Bone Collector HDU

来源:互联网 发布:行业数据查询 编辑:程序博客网 时间:2024/05/16 04:53

Bone Collector

 HDU - 2602 

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.
Output
One integer per line representing the maximum of the total value (this number will be less than 2 31).
Sample Input
15 101 2 3 4 55 4 3 2 1
Sample Output
14

AC代码:(一维数组写法)

#include<iostream>  #include<stdio.h>  #include<string.h>    #define maxn 1001 using namespace std;  int main(){int dp[maxn],w[maxn],v[maxn];int T,N,V;cin>>T;while(T--){cin>>N>>V;for(int i=0;i<N;++i){cin>>v[i];}for(int i=0;i<N;++i){cin>>w[i];}memset(dp,0,sizeof(dp));for(int i=0;i<N;++i)     // 物品数for(int j=V;j>=w[i];--j) //放入背包dp[j]=max(dp[j],dp[j-w[i]]+v[i]);// 与前面对比/*int tem; for(int i = 0 ; i < N ; i++)                    {            for(int j = V ; j >= w[i]; j--)            {//也可以使用这种写法(就是把max拆开写),个人觉得这样理解更清晰                 tem = dp[j-w[i]]+v[i];//容量为j的包放入第i件物品后的价值                if(dp[j]<tem)//用上面放入第i件物品的包跟容量为j不放i的包相比                 dp[j] = tem;//取价值较高的包跟后面的比较             }        }*/printf("%d\n",dp[V]);}return 0;}


二维数组写法:

#include<iostream>#include<cstdio>#include<string.h>#include<algorithm>using namespace std;int main(){int dp[1001][1001],w[1001],v[1001];int T,i,j,n,V;scanf("%d",&T);while(T--){scanf("%d",&n);scanf("%d",&V);for(i=0;i<n;i++){scanf("%d",&v[i]);}for(i=0;i<n;i++){scanf("%d",&w[i]);}memset(dp,0,sizeof(dp));for(i=0;i<n;++i){for(j=0;j<=V;++j){if(w[i]<=j){dp[i+1][j]=max(dp[i][j],dp[i][j-w[i]]+v[i]);}else{dp[i+1][j]=dp[i][j];}}}printf("%d\n",dp[n][V]);} return 0;}


原创粉丝点击