Link: https://www.nowcoder.com/acm/contest/119/F
Source: Niuke.com
Space limit: C/C++ 131072K, other languages 262144K
64bit IO Format: %lld
Topic description
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?
Enter description:
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.
Output description:
For each case, output one integer which means the max value of the trees that can be plant in the land.
enter
1 3 10 5 10 5 10 4 12
output
22
Idea: This 01 backpack is not the usual 01 backpack, because the capacity of the backpack is too large, and the array can't be opened so large, so we adopted transposition thinking (the description is not appropriate). Open an array dp[i] the minimum quality of some items with value i . In this case, the final value obtained when the mass is less than or equal to the total capacity of the backpack is the maximum value that can be placed .
Note: The array needs to be initialized to infinity, because it is the minimum value, of course, dp[0] still needs to be initialized to 0.
dp状态方程:dp[j]=min(dp[j],dp[j-weight[i]]+value[i]) j>=weight[i]。
code show as below:
#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; }