• 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/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    (转)Mat, vector<point2f>,Iplimage等等常见类型转换
    人脸检测与识别的趋势和分析
    经典网络LeNet5看卷积神经网络各层的维度变化
    C++: int int& int * int**的区别、联系和用途
    c++从txt中读取数据,数据并不是一行路径(实用)
    Spyder常用快捷键
    批量读写变换图片(转)
    OpenCV属性页配置问题~
    视觉目标检测和识别之过去,现在及可能(2017.06.28)
    数据库---SQL Server
  • 原文地址:https://www.cnblogs.com/sunjianzhao/p/11372852.html
Copyright © 2020-2023  润新知