码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 2602 Bone Collector(01背包)

时间:2016-02-19 18:58:50      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

Bone Collector

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
 
Answer
01背包,详见注释。
 
技术分享
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <map>
#define PI acos(-1.0)
#define ms(a) memset(a,0,sizeof(a))
#define msp memset(mp,0,sizeof(mp))
#define msv memset(vis,0,sizeof(vis))
using namespace std;
//#define LOCAL
struct Node
{
    int val;
    int vol;
}v[1000];
int dp[1000][1000];
int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    //freopen("out.txt","w",stdout);
#endif // LOCAL
    ios::sync_with_stdio(false);
    int N;
    cin>>N;
    while(N--)
    {
        int n,m;
        cin>>n>>m;
        ms(dp);
        for(int i=1;i<=n;i++)
            cin>>v[i].val;
        for(int i=1;i<=n;i++)
            cin>>v[i].vol;
        for(int i=1;i<=n;i++)//每件物品
        {
            for(int j=0;j<=m;j++)//分别放入容量为[0,m]的背包(物品重量可以是0)
            {
                if(v[i].vol<=j)//如果能放入
                    dp[i][j]=max(dp[i-1][j],dp[i-1][j-v[i].vol]+v[i].val);
                    //1.如果前一个大,就不放
                    //Q:为什么后面的加上了一个可能会比原来小?
                    //A:dp[i-1][j-v[i].vol]表示前i-1个物品,放入j-v[i].vol的背包,
                    //如果放不下,那么这n-1个物品就没有放进去,
                    //也就是说如果放入了第n个物品,背包里只有这个物品,
                    //就可能比不放这个物品而放前n-1个物品要小.
                    //2.后一个大,放
                else dp[i][j]=dp[i-1][j];//如果不能放入
            }
        }
        printf("%d\n",dp[n][m]);//输出[把第n个物品放入m的背包中]获得的最大价值
    }
    return 0;
}
View Code

 

HDU 2602 Bone Collector(01背包)

标签:

原文地址:http://www.cnblogs.com/gpsx/p/5201920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!