【01背包】 Beauti Land 华中科技大学校赛F

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

#include <bits/stdc++.h>
using namespace std;

const int inf = 0x7ffffff;
//0x7fffffff + 后爆int
int dp[10010];

int main()
{
	int T;scanf("%d",&T);
	while(T--)
	{
		int n,C;
		scanf("%d%d",&n,&C);

		int V=0;
		int c[100],v[100];
		for(int i=0;i<n;i++)
		{
			scanf("%d%d",&c[i],&v[i]);
			V+=v[i];  //总价值
		}

		for(int i=0;i<=V;i++)
			dp[i]=inf;
		dp[0]=0; //背包初始化

		for(int i=0;i<n;i++)
		{
			for(int j=V;j>=v[i];j--)  //价值作为01背包容量
			{
				dp[j]=min(dp[j],dp[j-v[i]]+c[i]);
				//达到价值j时最小的空间C花费
			}
		}

		int res=0;
		for(int j=0;j<=V;j++)  //使达到的价值最大
			if(dp[j]<=C)   //花费空间小于容量
				res=j;
		printf("%d\n",res);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ummmmm/article/details/80216934
今日推荐