链接:https://www.nowcoder.com/acm/contest/119/F
来源:牛客网
Beautiful Land
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld
空间限制: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?
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.8
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≤10
), the number of seeds and the capacity of the land.i
Then next n lines, each line contains two integer c
(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背包不是通常的01背包,因为背包容量太大,数组开不了那么大,于是就采用了换位思考(形容的不贴切)。开一个数组dp[i]一些物品价值为i时的最小质量。这样的话,最后求出质量小于等于背包总容量时的价值就是能放的最大价值。
注意:数组要初始化为无穷大,因为是求最小值,当然dp[0]还是要初始化为0的。
dp状态方程:dp[j]=min(dp[j],dp[j-weight[i]]+value[i]) j>=weight[i]。
代码如下:
#include<iostream> #include<cstring> #include<cmath> #include<cstdio> #define MAXN 0x3f3f3f3f using namespace std; int dp[100005]; int value[105]; int weight[105]; int main(){ int n,w,i,j,sum; int t; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&w); sum=0; for(i=1;i<=n;i++) { cin>>weight[i]>>value[i]; sum+=value[i]; } for(i=1;i<=sum;i++)dp[i]=MAXN; dp[0]=0; for(i=1;i<=n;i++) { for(j=sum;j>=value[i];j--) { dp[j]=min(dp[j],dp[j-value[i]]+weight[i]); } } for(i=sum;i>=0;i--) { if(dp[i]<=w) { cout<<i<<endl; break; } } } return 0; }