第十四届华中科技大学程序设计竞赛决赛同步赛 F-beautiful Land

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

时间限制: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 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.

解题思路:简单的动态规划问题,0-1背包问题:一开始我想的就是用一个二维数组dp[n][k]来表示加入n个,花费k块土地,得到的价值。但是因为k的值最大是1e8所以,这个实现不了,提交之后会出现内存超出的问题,后来又用一维数组dp[i]来表示花费i块土地能得到的价值,但是还是内存超出。。。因为k的值太大了。最后终于想出了另外一种方法来解决这个问题,就是用一位数组dp[i]表示得到价值为i时,需要花费的土地。主要的代码是这三行:sum是表示总的价值,

AC代码:

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
const int maxn = 1e4 + 5;
int a[105], v[105];
int T;
int dp[maxn];
int n, k;
int main()
{
	cin >> T;
	int sum = 0;
	while (T--)
	{
		cin >> n >> k;
		for (int i = 1; i <= n; i++)
		{
			cin >> v[i] >> a[i];
			sum += a[i];
		}
		memset(dp, 0x3f3f3f3f, sizeof(dp));
		dp[0] = 0;
		for (int i = 1; i <= n; i++)
		{
			for (int j = sum; j >= a[i]; j--)
			{
				dp[j] = min(dp[j], dp[j - a[i]] + v[i]);
			}
		}
		int ans = 0;
		for (int i = sum; i >= 0; i--)
		{
			if (dp[i] <= k)
			{
				ans = i;
				break;
			}
		}
		cout << ans << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40129237/article/details/80229875