您的位置:首页 > 其它

简单dp-bone collector

2018-03-12 20:04 387 查看
题目: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 
HintBy AC_gsws

解题思路:这个是典型的0-1背包问题,主要的代码是这几行

其中的w[i]数组是每种骨头的重量(weight),v[i]数组是每种骨头的价值(value),dp[i][j]是表示已加入i种骨头,背包的容量还剩j的时候能够得到的最优价值。初始化dp数组为0,然后从背包容量从最大容量开始计算,知道最后递推出最优答案。

AC代码:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int T;
int m, n;
const int maxn = 1010;
int dp[maxn][maxn], v[maxn], w[maxn];
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; i++)
{
scanf("%d", &v[i]);
}
for (int j = 1; j <= n; j++)
{
scanf("%d", &w[j]);
}
for (int i = 1; i <= n; i++)
{
for (int j = m; j >=0; j--)
{
if (j < w[i]) dp[i][j] = dp[i - 1][j];
else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i]] + v[i]);
}
}
printf("%d\n", dp
[m]);
}
return 0;
}
有问题欢迎私聊哦~么么哒
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp bone collector