题目描述
Once ago, there is a mystery yard which only produces three kinds of apples. The number of each kind is infinite. A girl carrying a big bag comes into the yard. She is so surprised because she has never seen so many apples before. Each kind of apple has a size and a price to be sold. Now the little girl wants to gain more profits, but she does not know how. So she asks you for help, and tell she the most profits she can gain.
输入
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 the girl's bag.
输出
For each case, first output the case number then follow the most profits she can gain.
示例输入
11 12 13 16
示例输出
Case 1: 6
提示
来源
示例程序
很早就看到这道题目,今天才得以真正解决了, 刚看到他是刚学背包的时候,当时看到V那么大,心里想肯定会超时,不知道怎么办才好,现在才知道大范围内贪心 小范围背包。注意用long long int
#include <stdio.h>
#include <string.h>
#include <math.h>
struct num
{
double val;
long long int s,p;
}a[10];
long long int dp[1100000];
int cmp(const void *e,const void *f)
{
struct num *p1=(struct num *)e;
struct num *p2=(struct num *)f;
if(fabs(p1->val-p2->val)<=1e-7)
{
return 0;
}
if(p1->val < p2->val)
{
return 1;
}
return -1;
}
int main()
{
long long int CompletePack(long long int m);
long long int i,j,n,m,s,t,tem=1;
scanf("%lld",&t);
while(t--)
{
for(i=0;i<=2;i++)
{
scanf("%lld %lld",&a[i].s,&a[i].p);
a[i].val=(double)a[i].p/(double)a[i].s;
}
scanf("%lld",&m);
if(m<=1000000)
{
s=CompletePack(m);
}else
{
qsort(a,3,sizeof(a[0]),cmp);
n=ceil((double)(m-1000000)/(double)(a[0].s));
m-=(n*a[0].s);
s=n*a[0].p;
s+=CompletePack(m);
}
printf("Case %lld: %lld\n",tem++,s);
}
return 0;
}
long long int CompletePack(long long int m)
{
long long int i,j;
memset(dp,0,sizeof(dp));
for(i=0;i<=2;i++)
{
for(j=a[i].s; j<=m; j++)
{
if(dp[j]<(dp[j-a[i].s]+a[i].p))
{
dp[j]=dp[j-a[i].s]+a[i].p;
}
}
}
return dp[m];
}