• 第十四届华中科技大学程序设计竞赛决赛同步赛 F Beautiful Land(01背包,背包体积超大时)...


    链接:https://www.nowcoder.com/acm/contest/119/F
    来源:牛客网

    Beautiful Land
    时间限制:C/C++ 1秒,其他语言2秒
    空间限制:C/C++ 131072K,其他语言262144K
    64bit IO Format: %lld

    题目描述

    It’s universally acknowledged that there’re innumerable trees in the campus of HUST.
    Now HUST got a big land whose capacity is C to plant trees. We have n trees which could be plant in it. Each of the trees makes HUST beautiful which determined by the value of the tree. Also each of the trees have an area cost, it means we need to cost ci area of land to plant.
    We know the cost and the value of all the trees. Now HUSTers want to maximize the value of trees which are planted in the land. Can you help them?

    输入描述:

    There are multiple cases.
    The first line is an integer T(T≤10), which is the number of test cases.
    For each test case, the first line is two number n(1≤n≤100) and C(1≤C≤10
    8
    ), the number of seeds and the capacity of the land. 
    Then next n lines, each line contains two integer c
    i
    (1≤c
    i
    ≤10
    6
    ) and v
    i
    (1≤v
    i
    ≤100), the space cost and the value of the i-th tree.

    输出描述:

    For each case, output one integer which means the max value of the trees that can be plant in the land.
    示例1

    输入

    1
    3 10
    5 10
    5 10
    4 12

    输出

    22

    思路:这个01背包不是通常的01背包,因为背包容量太大,数组开不了那么大,于是就采用了换位思考(形容的不贴切)。开一个数组dp[i]一些物品价值为i时的最小质量。这样的话,最后求出质量小于等于背包总容量时的价值就是能放的最大价值

    注意:数组要初始化为无穷大,因为是求最小值,当然dp[0]还是要初始化为0的。

    dp状态方程:dp[j]=min(dp[j],dp[j-weight[i]]+value[i])   j>=weight[i]。

    代码如下:

    #include<iostream> 
    #include<cstring> 
    #include<cmath> 
    #include<cstdio> 
    #define MAXN 0x3f3f3f3f 
    using namespace std; 
    int dp[100005]; 
    int value[105]; 
    int weight[105]; 
    int main(){ 
        int n,w,i,j,sum;
        int t;
      scanf("%d",&t);
      while(t--)
      {
        scanf("%d%d",&n,&w);
            sum=0; 
            for(i=1;i<=n;i++)
            { 
            cin>>weight[i]>>value[i]; 
            sum+=value[i]; 
        } 
        for(i=1;i<=sum;i++)dp[i]=MAXN; 
        dp[0]=0; 
        for(i=1;i<=n;i++)
        { 
            for(j=sum;j>=value[i];j--)
            { 
                dp[j]=min(dp[j],dp[j-value[i]]+weight[i]); 
            } 
        } 
        for(i=sum;i>=0;i--)
        { 
            if(dp[i]<=w)
            { 
                cout<<i<<endl; 
                break; 
            } 
        }   
      }
        return 0; 
    } 
  • 相关阅读:
    Spring加载xsd引起的问题小记
    kafka配置参数
    nginx常见内部参数,错误总结
    从毕业到现在的总结
    storm坑之---传递对象
    Java多线程读取大文件
    webpack4.0.1安装问题及解决方法
    git入门篇shell
    less教程
    原生js的ajax请求
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/13271033.html
Copyright © 2020-2023  润新知