Zombie’s Treasure Chest
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3587 Accepted Submission(s): 726
Problem Description
Some brave warriors come to a lost village. They are very lucky and find a lot of treasures and a big treasure chest, but with angry zombies.
The warriors are so brave that they decide to defeat the zombies and then bring all the treasures back. A brutal long-drawn-out battle lasts from morning to night and the warriors find the zombies are undead and invincible.
Of course, the treasures should not be left here. Unfortunately, the warriors cannot carry all the treasures by the treasure chest due to the limitation of the capacity of the chest. Indeed, there are only two types of treasures: emerald and sapphire. All of the emeralds are equal in size and value, and with infinite quantities. So are sapphires.
Being the priest of the warriors with the magic artifact: computer, and given the size of the chest, the value and size of each types of gem, you should compute the maximum value of treasures our warriors could bring back.
Input
There are multiple test cases. The number of test cases T (T <= 200) is given in the first line of the input file. For each test case, there is only one line containing five integers N, S1, V1, S2, V2, denoting the size of the treasure chest is N and the size and value of an emerald is S1 and V1, size and value of a sapphire is S2, V2. All integers are positive and fit in 32-bit signed integers.
Output
For each test case, output a single line containing the case number and the maximum total value of all items that the warriors can carry with the chest.
Sample Input
2
100 1 1 2 2
100 34 34 5 3
Sample Output
Source
2011 Asia Shanghai Regional Contest
题目大意:题目的意思是给你两种物品,两个物品有各自的cost与value,然后给你一个容量n,问你产生最大的价值是多少。
解题思路:开始想的是直接贪心,但是WA了几发,自己又认真画了一下,并不能直接贪心。想到了02完全背包,但是n得最大值竟然达到了10^9完全是不可能用背包做的。只能找所谓的循环节,然后枚举剩下的,然后思路就出来了。找到两个cost的lcm,这些是可以直接使用贪心策略的,剩下的只是枚举即可。但是需要注意的两点。
1.如果cnt>=1,需要留出来一个lcm,以供枚举。可以用100 3 3 7 7这个情况考虑,lcm为21,cnt为4,把cnt变为3,n变为16+21=37.这样枚举状态即可。
2.枚举的时候需要注意,枚举少的情况,就是枚举s大的情况,所以枚举前先排序。
题目地址:Zombie’s Treasure Chest
AC代码:
#include<iostream>
#include<cstdio>
using namespace std;
__int64 gcd(__int64 m,__int64 n)
{
__int64 tmp;
while(n)
{
tmp=m%n;
m=n;
n=tmp;
}
return m;
}
__int64 lcm(__int64 m,__int64 n)
{
return m/gcd(m,n)*n;
}
int main()
{
int tes,cas;
scanf("%d",&tes);
__int64 n,s1,v1,s2,v2,i;
for(cas=1; cas<=tes; cas++)
{
__int64 tmp,cnt,res,ma;
scanf("%I64d%I64d%I64d%I64d%I64d",&n,&s1,&v1,&s2,&v2);
if(double(v1)/s1<double(v2)/s2)
{
swap(s1,s2);
swap(v1,v2);
}
tmp=lcm(s1,s2);
cnt=n/tmp;
if(cnt) cnt--; //留一个公倍数枚举用
res=tmp*cnt/s1*v1;
n-=cnt*tmp;
if(s1<s2) //枚举容量大的,不然会TLE
{
swap(s1,s2);
swap(v1,v2);
}
ma=0;
for(i=0;i<=n/s1;i++) //枚举各种情况
{
ma=max(ma,v1*i+v2*((n-i*s1)/s2));
}
res+=ma;
printf("Case #%d: %I64d\n",cas,res);
}
return 0;
}
/*
12
100 3 3 7 7
*/
//15MS