题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2602
最简单常规的01背包。
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 ?
Input The first line contain a integer T , the number of cases.
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 |
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int Vmat[1000][1000];
int dp[1000];
int main(){
int T;
int N[1000]={0};
int V[1000]={0};
cin>>T;
while(T--){
int nNum;cin>>nNum;
int nVol;cin>>nVol;
for(int i=1;i<=nNum;i++){
cin>>N[i];
}
for(int i=1;i<=nNum;i++){
cin>>V[i];
}
for(int i=0;i<=nNum;i++){
Vmat[i][0]=0;
}
for(int i=0;i<=nVol;i++){
Vmat[0][i]=0;
}
memset(dp,0,sizeof(dp));
for(int i=1;i<=nNum;i++){
for(int j=nVol;j>=0;j--){
if(V[i]<=j){
dp[j]=max(dp[j],dp[j-V[i]]+N[i]);
}
}
}
cout<<" 1D matric:dp="<<dp[nVol]<<endl;
//一维数组保存dp
for(int i=1;i<=nNum;i++){
for(int j=0;j<=nVol;j++){
Vmat[i][j]=Vmat[i-1][j];
if(V[i]<=j){
Vmat[i][j]=max(Vmat[i][j],Vmat[i-1][j-V[i]]+N[i]);
}
}
}
cout<<" 2D matric:dp="<<Vmat[nNum][nVol]<<endl;
//二维数组保存dp
}
}