Problem Description
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.
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.
Input
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1's. All integers are not greater than 1000.
Output
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.
Sample Input
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
Sample Output
13.333 31.500
Author
CHEN, Yue
Source
题目大意:
这里有N个房间,鼠粮j[i],猫粮f[i],在房间中放入一定的猫粮
f[i]能获得一定的鼠粮
j[i],m代表老鼠拥有诱惑猫的猫粮总量,问老鼠用有限的猫粮换取最多的鼠粮。输入老鼠拥有的猫粮总量m和房间个数n,随后输入每个房间的
j[i],f[i],并且输入-1 -1 时结束程序,所有整数不大于1000。输出获得的最多鼠粮总量,输出结果精确到小数点后三位。
解题思路:
为了获得更多的收获,这就需要考虑付出最少得到最多,也就是j[i]/f[i]比值越大,得到的越多,所以首先算出每个房间的比例
j[i]/f[i]然后将其比例进行从大到小的排序,相应的j[i],f[i]数组也需要随之进行调整,然后按照比例大小顺序将猫粮放入获取最多的猫粮。在输入输出的类型上一定要做好相应的匹配否则会使输出结果有问题。
#include<stdio.h>
#include<math.h>
int main()
{
int i,a;//sum为获得鼠粮总量,maxr为最大比例
double sum=0,maxr=0,zhuan1,zhuan2,zhuan3,m,n;
double j[1000],f[1000],r[1000],to[1000];//j猫粮,f老鼠量,r比例
while(scanf("%lf%lf",&m,&n)!=EOF&&(n!=-1||m!=-1))
{
for(i=0;i<n;i++)
{
scanf("%lf%lf",&j[i],&f[i]);
r[i]=j[i]/f[i];
}
for(i=0;i<n;i++)
{
for(a=0;a<n-i-1;a++)
{
if(r[a]<r[a+1])
{
zhuan1=r[a];
r[a]=r[a+1];
r[a+1]=zhuan1;
zhuan2=f[a];
f[a]=f[a+1];
f[a+1]=zhuan2;
zhuan3=j[a];
j[a]=j[a+1];
j[a+1]=zhuan3;
}
}
}
for(i=0;i<n;i++)
{
if(m>f[i])
{
sum=sum+j[i];
m=m-f[i];
}
else
{
sum=sum+m*r[i];
m=0;
}
}
printf("%.3lf\n",sum);
sum=0;//因为是连续输入,所以一定要在上一个结果输出后初始化sum
}
return 0;
}