Bone Collector
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 9840 Accepted Submission(s): 3778
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 2
31).
Sample Input
1 5 10 1 2 3 4 5 5 4 3 2 1
Sample Output
14
二维数组:
#include <iostream>
using namespace std;
int opt[1001][1001];
int v[1001],w[1001];
int main()
{
int t,N,i,j,V;
cin>>t;
while(t--)
{
cin>>N>>V;
for(i=1;i<=N;i++)
scanf("%d",&w[i]);
for(i=1;i<=N;i++)
scanf("%d",&v[i]);
memset(opt,0,sizeof(opt)); //初始化
for(i=1;i<=N;i++)
for(j=0;j<=V;j++) //注意要从0开始,这个题测试数据有点变态,有的骨头有价值,但占的空间是0
{
if(v[i]<=j && opt[i-1][j]<opt[i-1][j-v[i]]+w[i])
opt[i][j]=opt[i-1][j-v[i]]+w[i];
else
opt[i][j]=opt[i-1][j];
}
cout<<opt[N][V]<<endl;
}
return 0;
}
一维数组:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#define maxV 1111//总价值
#define maxN 1111//总量
long opt[maxV];
long w[maxN],v[maxN];
int N,V,t;
int main(void){
int i,j;
scanf("%d",&t);
while(t-->0){
scanf("%d%d",&N,&V);//V 背包容量
for(i=0;i<N;i++){
scanf("%ld",v+i); //为什么写成v[i]就wa! 但是换成cin是可以的
}
for(i=0;i<N;i++){
scanf("%ld",w+i);
}
memset(opt,0,sizeof(opt));//用0初始化 不限定背包装满 即opt[v]不限;
for(i=0;i<N;i++)
for(j=V;j-w[i]>=0;j--) //j-w[i]>=0 即是一维数组里的if判断 也是ZeroOnePark的优化方案
opt[j] = std::max(opt[j],opt[j-w[i]]+v[i]);
printf("%ld\n",opt[V]);
}
return 0;
}