01背包—hdu2602—附加个人认为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. 
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 

5 10 
1 2 3 4 5 
5 4 3 2 1

Sample Output 
14

这道题就是一道典型的套模板的题目,不过这一题有一点跟链接里的不一样,链接里重量是从1开始的,但是这道题重量可以为0,因此在写循环的时候记得要把j从0开始


5 0 
1 2 3 4 5 
0 0 0 0 1

这个样例值输出为10的话那基本代码是可以ac的

终于学会了01模板一定要大吃一餐的ac代码:

#include 
using namespace std;
#define n 10005
int m[n][n];
int w[n];
int v[n];
int x[n];

int main()
{
	int i,j;
	int num,mmax;
	int t;
	cin>>t;
	while(t--){
		fill(m[0],m[0]+n*n,0);
		fill(x,x+n,1);
		cin>>num>>mmax;
		for(i=1;i<=num;i++)
		    cin>>v[i];
		for(i=1;i<=num;i++)
		    cin>>w[i];
		for(i=1;i<=num;i++){
			for(j=0;j<=mmax;j++){
				if(j>=w[i]){
					m[i][j]=max(m[i-1][j],m[i-1][j-w[i]]+v[i]);
				}
				else
				    m[i][j]=m[i-1][j];
			}
		}
		cout<

 

你可能感兴趣的:(01背包—hdu2602—附加个人认为01背包讲解的最清晰简单的一篇博文链接)