HDU 2602 01背包

http://acm.hdu.edu.cn/showproblem.php?pid=2602

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 2 31).

Sample Input

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

Sample Output

1

题目大意:很明显是01背包的问题,给你n种物品的重量和价格,以及背包的容量,每种物品只能选一个,问你能获得的最大价值是多少。(背包可以有剩余空间)

思路:01背包,外层循环遍历n种物品,内层循环从背包总容量V递减到当前物品所占的体积w[i]。为什么要倒序呢?01背包的含义就是一个物品你要么拿走(1)要么不拿(0),其转移方程是:dp[i]=max(dp[i],dp[i-w[i]]+v[i]),即当前背包容量为i时候的价值是由背包容量为i-w[i]时的情况转移过来的,如果正序的话,这个物品就可能拿了多次,问题就转换成了完全背包了,而不是01背包。

#include<iostream>
#include<cstdio>
#include<stack>
#include<cmath>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<algorithm>
#include<iterator>
#define INF 0x3f3f3f3f
#define EPS 1e-10
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

int v[1005];//价值
int w[1005];//体积
int dp[1005];
int n,sum;
				//0 1 背包
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(dp,0,sizeof(dp));
		scanf("%d%d",&n,&sum);
		for(int i=0;i<n;i++)
			scanf("%d",&v[i]);
		for(int i=0;i<n;i++)
			scanf("%d",&w[i]);
		for(int i=0;i<n;i++)
			for(int j=sum;j>=w[i];j--)
				dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
		printf("%d\n",dp[sum]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/86676522