**问题 E: FatMouse’s Trade
题目描述
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 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.
输出
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.
样例输入 Copy
4 2
4 7
1 3
5 5
4 8
3 8
1 2
2 5
2 4
-1 -1
样例输出 Copy
2.286
2.500
题意理解:胖老鼠准备了猫粮准备和猫换JavaBean的东西吃(这个出题人难道是Java大佬 )。有n个房间,每个房间有一定数量的JavaBean可以和猫粮进行互换(小学数学问题,换东西。就跟小时候2根辣条可以换3个棒棒糖一样,那么一根辣条可以换几根棒棒糖呢?一个棒棒糖又能换几根辣条呢?答案很明显,交换双方的后者总是作为分子俗话说,高高在上,来追我啊 )。然后很自然的可以算出每一个房间两种食物的一个交换率随便你怎么理解,我是理解为交换率。关键步骤是判断老鼠拿出多少猫粮来换JavaBean了!先把物品的交换率 进行从大到小的排序(换东西肯定要换的越多越好呀,此题贪心之处就体现于此了)。所以有两种情况:1.老鼠手里的猫粮都不足或者刚好等于那个交换率最高的房间的猫粮数哦,此时结果就为此房间的交换率乘以老鼠拿出的猫粮数量了。2.如果老鼠比较贪心想要多换点,但是已经超过了第一个房间的猫粮数量,则先把第一个房间的所有JavaBean换回来,然后需要换的猫粮就变成原猫粮(老鼠拿出的)-第一个房间的猫粮数哦。然后就依次去各个房间1换了,直至把猫粮全换完位置,胖老鼠才会心满意足,然后抱着一大堆JavaBean回到洞里面享用。而猫呢,啧啧啧,不可描述啦
代码时间:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct room
{
double jb;
double cf;
double rate;
} str[1005];
bool cmp(room a,room b)
{
return a.rate>b.rate;//对交换率进行排序
}
int main()
{
int mcf,n;
while(scanf("%d%d",&mcf,&n)&&(mcf!=-1)&&(n!=-1))
{
double maxm=0.0;
for(int i=0; i<n; i++)
{
scanf("%lf%lf",&str[i].jb,&str[i].cf);
str[i].rate=str[i].jb/str[i].cf;
}
sort(str,str+n,cmp);
//maxm=1.0;
for(int i=0; i<n; i++)
{
if(mcf<=str[i].cf)//小于该房间猫粮数量
{
maxm+=mcf*str[i].rate;
break;
}
else
{
maxm=str[i].jb;
mcf-=str[i].cf;
}
}
printf("%.3f\n",maxm);
}
return 0;
}
**最后再强调一下其实是自己年少无知踩到的坑咯:结构体三个变量都要定义为double类型,不然后面做除法会出现问题,以至于输出一直是0.000,我还在那里找是不是我的初始化或者叫做清0的位置出现了问题!幸好之前有关类似的错误,然后恍然大悟~~ **~~