Bone Collector(01背包+记忆化搜索)
Bone Collector
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 21 Accepted Submission(s) : 6
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.
Output
One integer per line representing the maximum of the
total value (this number will be less than 2[sup]31[/sup]).
Sample Input
1
5 10
1 2 3 4 5
5 4 3 2 1
Sample Output
14
题解:也就01背包;
代码:
1 #include<stdio.h> 2 #include<string.h> 3 #define max(a,b) (a>b?a:b) 4 int f[2000]; 5 int val[2000]; 6 int cos[2000]; 7 int main() 8 { 9 int T; 10 scanf("%d",&T); 11 while(T--) 12 { 13 memset(f,0,sizeof(f)); 14 memset(val,0,sizeof(val)); 15 memset(cos,0,sizeof(cos)); 16 int n,v; 17 scanf("%d%d",&n,&v); 18 int i,j; 19 for(i=1;i<=n;i++) 20 scanf("%d",&val[i]); 21 for(j=1;j<=n;j++) 22 scanf("%d",&cos[j]); 23 for(i=1;i<=n;i++) 24 { 25 for(j=v;j>=cos[i];j--) 26 { 27 // f[j]=f[j-1]; 28 // if(j>=cos[i]) 29 f[j]=max(f[j],f[j-cos[i]]+val[i]); 30 } 31 } 32 printf("%d\n",f[v]); 33 } 34 return 0; 35 }
记忆化搜索;
ac代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<vector> using namespace std; const int INF=0x3f3f3f3f; #define mem(x,y) memset(x,y,sizeof(x)) #define SI(x) scanf("%d",&x) #define PI(x) printf("%d",x) #define SD(x) scanf("%lf",&x) #define P_ printf(" ") typedef long long LL; const int MAXN=1010; int dp[MAXN][MAXN],w[MAXN],p[MAXN]; int dfs(int i,int v){ if(dp[i][v])return dp[i][v]; if(i==0||v<0)return 0;// if(w[i]>v)dp[i][v]=dfs(i-1,v); else dp[i][v]=max(dfs(i-1,v),dfs(i-1,v-w[i])+p[i]);// return dp[i][v]; } int main(){ int T,N,M; SI(T); while(T--){ SI(N);SI(M); for(int i=1;i<=N;i++)SI(p[i]); for(int i=1;i<=N;i++)SI(w[i]); mem(dp,0); printf("%d\n",dfs(N,M)); } return 0; }