题目大意:
你有一个体积为N的箱子和两种数量无限的宝物,宝物1的体积为s1,价值为v1; 宝物2的体积为s2, 价值为v2. 输入均为32位带符号整数。你的任务是计算最多能够装多大的宝物。
题目分析:
两种枚举方法,枚举宝物1的个数尽量多拿宝物2,这个很好理解,但是时间复杂度为O(N/s1); 当s1很小的时候,时间效率是非常低的;这个时候就有第二种枚举方法;
s2个宝物1的体积等于s1个宝物2的体积,而价值分别为s2*v1和s1*v2。 如果前者比较大,则宝物2最多只拿s1-1个(否则可以吧s1个宝物2换成s2个宝物1); 反之同理最多只能拿宝物一s2-1个;
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
int main()
{
int n, s1, v1, s2, v2;
int T, cas = 0;
scanf("%d", &T);
while(T--){
scanf("%d%d%d%d%d", &n, &s1, &v1, &s2, &v2);
if(s1 > s2){
swap(s1, s2);
swap(v1, v2);
}
LL ans = 0;
if(n/s2 > 50000){
if(s2*v1 > s1*v2){
for(LL i = 0; i < s1; ++i){
ans = max(ans, v2*i+(n-s2*i)/s1*v1);
}
} else{
for(LL i = 0; i < s2; ++i){
ans = max(ans, v1*i+(n-s1*i)/s2*v2);
}
}
} else{
for(LL i = 0; i*s2 <= n; ++i){
ans = max(ans, i*v2+(n-i*s2)/s1*v1);
}
}
printf("Case #%d: ", ++cas);
printf("%lld\n", ans);
}
return 0;
}