链接:https://www.nowcoder.com/acm/contest/119/F
来源:牛客网
Beautiful Land
时间限制: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 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
思路:01背包问题
但是这题不同于(poj3624)Charm Bracelet
本题中的C最大可达10^8,如果直接开10^8的Int类型数组,会TLE,但本题中V最大是100,那么总价值最大为10^4,所以按照价值从大到小遍历即可。最后输出容量C能对应能装的最大价值V。
代码:
#include <bits/stdc++.h>
using namespace std;
#define mem(a,n) memset(a,n,sizeof(a))
#define rep(i,a,n) for(int i=a;i<n;i++)
typedef long long ll;
const double eps=1e-5;
const int N=1e4+5;
const int MOD=1e7+7;
const int INF=0x3f3f3f3f;
const int dir[4][2]= {1,0,-1,0,0,1,0,-1};
ll dp[N],w[N]; ///dp[i]:价值为i时的最小容量为dp[i];
int v[N];
int main()
{
int T,i,n,sum;
ll V;
scanf("%d",&T);
while(T--)
{
scanf("%d%lld",&n,&V);
sum=0;
for(i=1; i<=n; i++)
{
scanf("%lld%d",&w[i],&v[i]);
sum=sum+v[i];
}
memset(dp,INF,sizeof(dp));
dp[0]=0;
for(i=1; i<=n; i++)
{
for(int j=sum; j>=v[i]; j--)
dp[j]=min(dp[j],dp[j-v[i]]+w[i]);
}
for(i=sum; i>=0; i--)
{
if(dp[i]<=V)
{
printf("%d\n",i);
break;
}
}
}
return 0;
}