zoukankan      html  css  js  c++  java
  • hdu2602Bone Collector ——动态规划(0/1背包问题)

    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
     
    现附上AC代码:

    #include<iostream>
    #include<cstring>
    using namespace std;
    const int v=1000+10;
    const int num=1000+10;
    int value[num][2]={0};
    int dp[num][v]={0};
    void solve(int s,int n)
    {
    for(int i=0;i<n;i++)
    {
    for(int j=0;j<=s;j++) //这道题之前一直wrong answer,找了很久都没发现问题,最后在此处找到了根源,原先写的是int j=1;后来改为0就对了,体积竟然可以是0,我也是无语了
    {
    if(j>=value[i][0])
    dp[i+1][j]=max(dp[i][j],dp[i][j-value[i][0]]+value[i][1]);
    else
    dp[i+1][j]=dp[i][j];
    }
    }
    }

    int main()
    {
    int n,s,t;
    cin>>t;
    while(t--)
    {
    cin>>n>>s;
    memset(dp,0,sizeof(dp));
    memset(value,0,sizeof(value));
    for(int i=0;i<n;i++)
    cin>>value[i][1];
    for(int i=0;i<n;i++)
    cin>>value[i][0];
    solve(s,n);
    cout<<dp[n][s]<<endl;
    }
    return 0;
    }

    找到递推关系即可。分情况:1)若可重复使用物品,则是dp[i+1][j]=max(dp[i][j],dp[i+1][j-value[i][0]]+value[i][1]) 

                                                     2)若不可重复使用,则为dp[i+1][j]=max(dp[i][j],dp[i][j-value[i][0]]+value[i][1])

    区别是从本行找还是从上一行找


    作者:孙建钊
    出处:http://www.cnblogs.com/sunjianzhao/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    算法笔记codeup-Contest100000568
    算法笔记codeup-Contest100000567
    算法笔记codeup-Contest100000566
    人工智能各种知识点(大杂烩)
    人工智能基础知识复习:机器学习
    人工智能基础知识复习:神经计算 演化计算 模糊计算
    人工智能基础知识复习:问题求解与搜索
    人工智能基础知识复习:推理技术
    前端基础知识学习:概念篇
    MYSQL
  • 原文地址:https://www.cnblogs.com/sunjianzhao/p/11372852.html
Copyright © 2011-2022 走看看