Problem Description
A long time ago, there was another Garden of Eden which produces three kinds of apples. The number of them were infinite.Each kind of apple had Si size and Pi value.One day, Adam wanted to pick some apples to Eve to make her happy.He had a bag of V size and used the bag take apples.However, he could not bring all the apples but he wanted more values to make Eve happier.Can you help him to find the most values he can take.
Input
In the first line there is an integer T (T <= 50), indicates the number of test cases.
In each case, there are four lines. In the first three lines, there are two integers S and P in each line, which indicates the size (1 <= S <= 100) and the price (1 <= P <= 10000) of this kind of apple.
In the fourth line there is an integer V,(1 <= V <= 100,000,000)indicates the volume of Adam's bag.
In each case, there are four lines. In the first three lines, there are two integers S and P in each line, which indicates the size (1 <= S <= 100) and the price (1 <= P <= 10000) of this kind of apple.
In the fourth line there is an integer V,(1 <= V <= 100,000,000)indicates the volume of Adam's bag.
Output
For each case, first output the case number then follow the most values Adam can gain.
Sample Input
1 1 1 2 1 3 1 6
Sample Output
Case 1: 6
由于V的取值较大,如果一味背包必将超时,所以大范围内贪心,小范围内背包。
#include <iostream> #include <cstring> #include <cstdio> using namespace std; int s[3],p[3];//每种苹果的尺寸、价值 long long int dp[110001]; double rate; int t; long long complete_pack(int v){//背包 memset(dp,-1,sizeof(dp));//初始化dp dp[0] = 0; for(int i = 0;i < 3; i ++){ for(int j = 0;j <= v;j++){ if(j - s[i] >= 0 && dp[j - s[i]] != -1) dp[j] = max(dp[j],dp[j-s[i]]+p[i]); }} long long int res = 0; for(int i = 0;i <= v;i++)//选取最大值 if(dp[i] > res) res = dp[i]; return res; } int main(){ cin>>t; int maxm; int v; for(int i = 0;i < t;i ++){ rate = 0.0; for(int j = 0;j <3;j++){ cin>>s[j]>>p[j]; if((double)p[j]/s[j] > rate){ rate = (double)p[j]/s[j];//选取性价比最高的苹果种类 maxm = j; } } cin>>v; long long int ans = 0; if (v > 100000){//大于100000范围内贪心 long long int n = (v - 100000) / s[maxm]; ans += n*p[maxm]; v -= n*s[maxm]; ans += complete_pack(v); } else { //小范围即小于100000时背包 ans += complete_pack(v); } cout<<"Case "<<i+1<<": "<<ans<<endl; } return 0; }