# 算法提高 01背包 hdu2602 Bone Collector

2017年02月24日 9点热度 0人点赞 0条评论
算法提高 01背包

给定N个物品,每个物品有一个重量W和一个价值V.你有一个能装M重量的背包.问怎么装使得所装价值最大.每个物品只有一个.

输入的第一行包含两个整数n, m，分别表示物品的个数和背包能装重量。
以后N行每行两个数Wi和Vi,表示物品的重量和价值

输出1行，包含一个整数，表示最大价值。

3 5

2 3

3 5

4 7

8

1<=N<=200,M<=5000.

#include
#include
using namespace std;
struct node{
int w,v;
}a;
int main(){
int n,w,dp={0};
scanf("%d%d",&n,&w);
for(int i=1;i<=n;i++)
scanf("%d%d",&a[i].w,&a[i].v);
for(int i=1;i<=n;i++)
for(int j=w;j>=a[i].w;j--)
dp[j]=max(dp[j],dp[j-a[i].w]+a[i].v);
printf("%dn",dp[w]);
return 0;
}

# Bone Collector

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 55478    Accepted Submission(s): 23209

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

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

Sample Output

14

Author
Teddy

Source

#include
#include
#include
using namespace std;
struct node
{
int w,v;
} a;
int main()
{
int n,w,dp= {0},t;
scanf("%d",&t);
while(t--)
{
memset(dp,0,sizeof(dp));
scanf("%d%d",&n,&w);
for(int i=1; i<=n; i++)
scanf("%d",&a[i].v);
for(int i=1; i<=n; i++)
scanf("%d",&a[i].w);
for(int i=1; i<=n; i++)
for(int j=w; j>=a[i].w; j--)
dp[j]=max(dp[j],dp[j-a[i].w]+a[i].v);
printf("%dn",dp[w]);
}
return 0;
} update