zoukankan      html  css  js  c++  java
  • HDU2602 01背包入门 Bone Collector【01背包模板题】

    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**

    题意:容量为V的背包,尽可能装价值更多的石头,输出背包最大的价值
    思路:01背包的经典套路,由石头1推到石头n,第i个石头下背包容量V的最大价值由i-1递推而来

    #include<stdio.h>
    #include<string.h>
    #define N 1000
    int num[N+10],w[N+10],v[N+10];
    int main()
    {
        int i, j;
        int t, n, V;
        scanf("%d",&t);
        while( t --)
        {
            memset(num,0,sizeof(num));
            memset(w,0,sizeof(w));
            memset(v,0,sizeof(v));
            scanf("%d%d",&n,&V);
            for(i = 1; i <= n; i ++)
                scanf("%d",&w[i]);
            for( i = 1; i <= n; i ++)
                scanf("%d",&v[i]);
            for( i = 1; i <= n; i ++)
                for( j = V; j >=v[i];j --)/*j代表背包的剩余容量*/
                {
                    num[j] = max(num[j],num[j-v[i]]+w[i]);
                    /*num[j]表示不把第i个石头放入背包的价值*/
                    /*num[j-v[i]]+w[i]表示把第i个石头放入背包后的价值*/
                    /*比较二者的最优解存入num[j]*/
                }
            printf("%d
    ",num[V]);
        }
        return 0;
    }
  • 相关阅读:
    [LeetCode] 273. Integer to English Words 整数转为英文单词
    What happens when you type an URL in the browser and press enter?
    HTTP Status Code
    What's binary search?
    [Http] Difference between POST and GET?
    [LeetCode] 53. Maximum Subarray 最大子数组
    [LeetCode] 621. Task Scheduler 任务调度
    C# web项目添加*.ashx文件后报错处理
    Web项目和Windows应用程序的配置文件
    C#中web项目使用log4net日志
  • 原文地址:https://www.cnblogs.com/hellocheng/p/7350163.html
Copyright © 2011-2022 走看看