Beautiful Land(01背包问题另解)

链接: 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.

示例1

输入

1
3 10
5 10
5 10
4 12

输出

22
#include
#include
#include
#include
const int MAX = 1e2 + 5;
const int MAXSIZE = 0x3f3f3f3f;
using namespace std;

int t, n, C, v[MAX], c[MAX];//测试次数、用例数、背包大小、权值、占用空间
int dp[10005];
int maxV;
int main()
{
	scanf("%d", &t);
	while (t--)
	{
		memset(dp, MAXSIZE, sizeof(dp));
		maxV = 0;
		scanf("%d %d", &n, &C);
		for (int i = 0; i < n; i++)
		{
			scanf("%d %d", &c[i], &v[i]);
			maxV += v[i];
		}
		dp[0] = 0;
		for (int i = 0; i < n; i++)
		{
			for (int j = maxV; j >= v[i]; j--)
			{
				dp[j] = min(dp[j], dp[j - v[i]] + c[i]);
			}
		}
		for (int i = maxV; i >= 0; i--){
			if (dp[i] <= C){
				printf("%d\n", i);
				break;
			}
		}
	}
	return 0;
}

你可能感兴趣的:(算法)