第十四届华中科技大学程序设计竞赛决赛同步赛 Beautiful Land(01背包变形)

题目链接

Beautiful Land

题目

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≤108), the number of seeds and the capacity of the land.
Then next n lines, each line contains two integer ci(1≤ci≤106) and vi(1≤vi≤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

题意

给定一个空间为C的背包和n个物品,每个物品有两个值c和v,分别代表物品所占空间和价值。现求在空间为C的背包中能放的最大价值是多少?

分析

每种物品一个,取或不取,裸的01背包问题。但是空间C太大了,需要换一种方法来维护。
设dp[i]表示价值总价值为i的物品所需占据空间的最小值。那么动态转移方程为:
dp[i]=min(dp[i],dp[i-v]+c)。
边界条件为:
dp[0]=0,dp[others]=INF。
根据i的值由大到小遍历dp[i],第一个满足dp[i]<=C的i即为所求。

AC代码

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;

const int maxn=1e4+100;
int dp[maxn],c[110],v[110];

int main()
{
    ios::sync_with_stdio(false);
    int T;
    cin>>T;
    while(T--)
    {
        int n,C,sum=0;
        memset(dp,0x3f,sizeof(dp));
        dp[0]=0;
        cin>>n>>C;
        for(int i=0;i<n;i++)
            cin>>c[i]>>v[i],sum+=v[i];
        for(int i=0;i<n;i++)
            for(int j=sum;j>=v[i];j--)
            dp[j]=min(dp[j],dp[j-v[i]]+c[i]);
        int ans=0;
        for(int i=sum;i>=0;i--)
        {
            if(dp[i]<=C)
            {
                ans=i;
                break;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37685156/article/details/80224038