思路很簡單,要用一定的cat food守護儘可能多得JavaBean,必須要房間的JavaBean多並且需要的cat food 少。所以這種涉及兩方面因素的貪心,可以通過兩方面的比率來判斷優先取哪一個。此題應當優先取J[i]/F[i]大的。
FatMouse' Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 41918 Accepted Submission(s): 13938
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
#include<stdio.h>
#include<algorithm>
using namespace std;
struct cat
{
int j;//javabean
int f;//cat fod
double t;
}B[1005];
typedef struct cat cat;
bool cmp(cat a,cat b)
{
return a.t>b.t;
}
int main()
{
int m,n;
while(scanf("%d%d",&m,&n)!=EOF)
{
int i;
double sum=0;
int k=0;
int xx,yy;
if(m==-1&&n==-1)
break;
for(i=0;i<n;i++)
{
scanf("%d%d",&xx,&yy);
if(yy==0)
sum+=xx;
else
{
B[k].j=xx;//javabean
B[k].f=yy;//cat food(搞清字母含義,不然混亂會加錯,我交了兩遍都是錯在字母搞混含義導致出錯)
B[k].t=(double)xx/yy;
k++;
}
}//考慮特殊的當房間不需要cat food時,不需要cat food
sort(B,B+k,cmp);//進行優先排序
//需要考慮幾種情況,當n=0,時,當m=0時m和n都不爲0時。實際上n=0和m不爲0並且n不爲0可以歸爲一類
if(m==0)
printf("%.3lf\n",sum);//直接輸出不需要cat food的JavaBean總和
else
{
int temp=m;
for(i=0;i<k;i++)
{
if(temp<=B[i].f)
sum+=B[i].t*(double)temp;
else
sum+=(double)B[i].j;
temp-=B[i].f;
if(temp<=0)
break;
}
printf("%.3lf\n",sum);
}//n=0和m!=0&&n!=0的情況歸爲一類
}
return 0;
}