现在的位置: 首页 > 综合 > 正文

hdu2602 01背包 题解

2018年04月25日 ⁄ 综合 ⁄ 共 1844字 ⁄ 字号 评论关闭

习DP,甚是迷惑,审其题,虽解其意,但无从下口,故弃而学背包,今日,重拾之,遂发现其乃美味也。故知背包乃DP之基也~

嘻嘻~~小小嘚瑟一下

      我是刚开始接触算法,就被诸位大神弄去学了DP,但是一知半解,遇到这道题的时候,怎么也想不出该怎么做。在我的师兄们(比我高一级的小菜,嘘,别让他听到了)的指引下,看了背包,今天再来看这道题~~~~大神  你在逗我玩吗~~~~~

   建议刚开始学dp的人 , 一定要去看看背包九讲,很精彩~~~

   废话少数,切入正题

E - Bone Collector

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d
& %I64u

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

题意分析:一个骨头搜集爱好者,收集各类各样的骨头,这个骨头爱好者有一个大袋子,容积是一定的,现给出一定的骨头,每个骨头的容积和价值是固定的,现在我们往袋子中装入骨头,求袋子容积所能承受的条件下的可装的最大价值。

思路分析:这是个典型的01背包,状态转移方程模板如下

for(int i = 1; i <= N; i++)//N骨头的总数
{
    for(int j = V; j <= v[i]; j--)//本题中,V指的是袋子的容积,v[i]指第i个骨头的体积,d[i]指第i个骨头的价值
    {
        dp[j]=max(dp[j],dp[j-v[i]]+d[i]);
    }
}

现给出AC代码

#include <iostream>
#include<cstdio>
#include<string.h>
using namespace std;
const int MAX = 1000+10;
int dp[MAX];
int d[MAX];
int v[MAX];
int T,N,V;

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        memset(dp,0,sizeof(dp));
        scanf("%d%d",&N,&V);
        for(int i = 1; i <= N; i++)
        {
            scanf("%d",&d[i]);
        }
        for(int j = 1; j <= N; j++)
        {
            scanf("%d",&v[j]);
        }
        for(int i = 1; i <= N; i++)
        {
            for(int j = V; j >= v[i];j--)
            {
                dp[j]=max(dp[j],dp[j-v[i]]+d[i]);
            }
        }
        printf("%d\n",dp[V]);
   }
    return 0;
}

抱歉!评论已关闭.