码迷,mamicode.com
首页 > 其他好文 > 详细

HDOJ 2602 Bone Collector--01背包

时间:2015-08-27 11:08:15      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:算法   01背包   dp   

题目来源:HPU 2602--Bone Collector

Problem Description

Manyyears ago , in Teddy’s hometown there was a man who was called “BoneCollector”. 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 ofcollecting there are a lot of bones , obviously , different bone has differentvalue 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

Thefirst line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain twointeger N , V, (N <= 1000 , V <= 1000 )representing the number of bonesand the volume of his bag. And the second line contain N integers representingthe value of each bone. The third line contain N integers representing thevolume of each bone.

 

 

Output

Oneinteger per line representing the maximum of the total value (this number willbe less than 231).

 

 

Sample Input

1

5 10

1 2 3 4 5

5 4 3 2 1

 

 

Sample Output

14

 

 

考察点:动态规划—01背包

 

题目大意:

给定T组测试数据,每组数据给定一个n(n块骨头)和一个V(背包的容量V),接下来给定两行分别输入n块骨头的价值和体积。输出背包能装下的最大价值。

题目解析:

动态规划方程:f(n,m)=max{f(n-1,m),f(n-1,m-w[n])+v(n,m)},根据此递推式可知01背包记录的是当前位置的最优解。

AC代码:

#include<cstdio>
#include<cstring>
#include<cstring>
#include<algorithm>
using namespace std;
int value[1005],volume[1005];//骨头价值,体积 
int dp[1005][1005];//记录背包体积从0到V所装价值最大值 
int main()
{
	int T;
	int n,V;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&V);
		memset(dp,0,sizeof(dp));//dp数组要初始化为0 
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&value[i]);
		}
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&volume[i]);
		}
		for(int i=1;i<=n;i++)
		{
			for(int j=0;j<=V;j++)
			{
				if(j<volume[i])//当前背包体积j不能装下体积为volume[i]的骨头 
				{
					dp[i][j]=dp[i-1][j]; 
				}
				else//当前背包体积j能装下体积为volume[i]的骨头 
				{
					//选择加或不加当前背包的价值 
					dp[i][j]=max(dp[i-1][j],dp[i-1][j-volume[i]]+value[i]);
				}
			}
		}
		printf("%d\n",dp[n][V]);
	}
	return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

HDOJ 2602 Bone Collector--01背包

标签:算法   01背包   dp   

原文地址:http://blog.csdn.net/weihai1996/article/details/48023409

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!