原题:
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
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.
题意:
老鼠准备M磅的食物去找猫换豆子,猫有很多个仓库,每个仓库储存着数量不同的豆子,而且换取豆子的需要的食物都不相同,不过老鼠可以在每个仓库都换取一部分豆子,只需要付出相应比例的食物就可以。
题解:
简单的贪心问题,就是求出每个仓库的豆子/食物的比值作为价值,然后依次从价值大到价值小开始换取,到最后如果还有豆子但是不够换取下一个仓库的所有豆子,就用剩下的所有豆子换取这个仓库里的一部分豆子。
题解:AC
#include<stdio.h>
#include<stdlib.h>
struct rate
{
double a;
double b;
double rt;
}rat[1010];
int cmp(const void *a, const void *b)
{
return (*(rate *)b).rt > (*(rate *)a).rt ? 1:-1 ;
}
int main()
{
int m, n, i;
double sum, x;
while(scanf("%d%d", &m, &n) != EOF &&( m != -1 || n != -1))
{
x = (double)m;
for( i = 0; i < n; i++)
{
scanf("%lf%lf", &rat[i].a, &rat[i].b);
if( rat[i].b != 0)
rat[i].rt = rat[i].a / rat[i].b;
else
rat[i].rt = 0;
}
qsort(rat, n, sizeof(rat[0]), cmp);
sum = 0;
for(i = 0 ; i < n; i++)
{
if( x >= rat[i].b )
{
sum += rat[i].a;
x -= rat[i].b;
}
else
{
if(x > 0)
{
sum += (x / rat[i].b) * rat[i].a;
x = 0;
}
}
}
printf("%.3lf\n", sum);
}
return 0;
}