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
",dp[v]);
43     }
44 
45     return 0;
46 }


原文地址:https://www.cnblogs.com/shadervio/p/5744415.html