HDU 2602 ——背包问题

本文介绍了一个经典的背包问题案例,通过状态转移方程实现最优解的计算。利用骨收集者的例子,详细解释了如何通过二维数组进行迭代,以找到背包能够容纳的最大价值。

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

Sample Input

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

Sample Output

14


题目大意:有n堆物品,物品有各自的价值和重量,问怎样在装满背包的时候使得背包内的物品价值最高。

解题思路:一开始的时候我是想到的排序方法,用2维数组去求,但是当我查了下网上资料后,发现还有另外一种方法
,就是状态转移:f[j]=max{f[j],f[j-b[i].volume]+b[i].value}

具体方法可以在代码里面看:
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 
 5 
 6 using namespace std;
 7 
 8 
 9 struct things
10 {
11     int h;
12     int v;
13 }goods[1005];
14 
15 int max(int a,int b)
16 {
17     return a>b?a:b;
18 }
19 
20 
21 int main()
22 {
23     int t;
24     int n,v,l;
25     int dp[1005];
26     scanf("%d",&t);
27     while(t--)
28     {
29         scanf("%d%d",&n,&v);
30         int i;
31         for(i = 1;i<=n;i++)
32             scanf("%d",&goods[i].h);
33         for(i = 1;i<=n;i++)
34             scanf("%d",&goods[i].v);
35         memset(dp,0,sizeof(dp));
36         for(i = 1;i<=n;i++)
37         {
38             for(l = v;l>=goods[i].v;l--)
39                 dp[l] = max(dp[l],dp[l-goods[i].v]+goods[i].h);
40         }
41 
42         printf("%d\n",dp[v]);
43     }
44 
45     return 0;
46 }

 



转载于:https://www.cnblogs.com/shadervio/p/5744415.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值