Beautiful Land(01背包变形)

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

题目描述

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 c i 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.


题意

HUST的容量为C,现在有n棵树,每棵树需要c[i]的土地,会产生v[i]的价值,问所能产生的最大价值。


思路

乍一看是一道裸的01背包,但坑点是它的最大容量有1e8,而我们开不下dp[1e8]的数组,时间复杂度也不行。


原本:dp[i]表示大小为 i 的容量能产生的最大价值:

    for(int i=1; i<=n; i++)
    {  
        for(int j=C; j>=cost[i]; j--)
        {  
            dp[j]=max(dp[j],dp[j-cost[i]]+val[i]);
        }  
    }  

但是,本题的n棵树的价值之和小于1e5,所以我们可以把dp[i]的含义改变为:产生的价值为 i 所需的最小容量。


现在:dp[i]表示产生的价值为 i 所需的最小容量:(sum为n棵树的val之和)

    for (int i = 1; i <= n; i++)
    {
	 for (int j = sum; j >= val[i]; j--)
	 {
		 dp[j] = min(dp[j], dp[j - val[i]] + cost[i]);
	 }
    }

代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

const int MAX = 1e5 + 10;
const int INF = 1e9 + 7;

int n, C;
int cost[105], val[105];
int dp[MAX]; //价值为 i 所需的最小容量

int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%d%d", &n, &C);
		int sum = 0;
		for (int i = 1; i <= n; i++)
		{
			scanf("%d%d", &cost[i], &val[i]);
			sum += val[i];
		}
		memset(dp, INF, sizeof(dp));
		dp[0] = 0;
		for (int i = 1; i <= n; i++)
		{
			for (int j = sum; j >= val[i]; j--)
			{
				dp[j] = min(dp[j], dp[j - val[i]] + cost[i]);
			}
		}
		for (int i = sum; i >= 0; i--)
		{
			if (dp[i] <= C)
			{
				printf("%d\n", i);
				break;
			}
		}	
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/luyehao1/article/details/80218188