<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.</span>
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
题目大意是一只胖老鼠有M磅猫粮,想要和一只守卫javabean仓库的喵星人进行交换,总共有N个仓库。第i个房间里放有就J[i]磅JavaBean,需要
F[i]磅猫粮来交换。胖老鼠可以选择交换某个仓库的部分JavaBean。比如他可以用F[i]a%磅猫粮换J[i]a%磅JavaBean。求胖老鼠最多可以换到多少JavaBean。
输入m为胖老鼠拥有的猫粮,n为房间数,然后依次输入每个房间有的javabean和交换所需要的猫粮。
输出保留三位小数。
(比较有意思的是DISCUSS区有个逗比居然特意去查了JavaBean是一种咖啡豆,老鼠不可能喜欢吃JavaBean的,2333333333.。、、、)
废话不多说,这是一道贪心算法的入门题,既然要尽可能多的换取JavaBean,那么我们肯定要选择同样的猫粮能换取JavaBean多的房间咯。也就是我们需要求出F[i]/J[i]。
然后排序后进行交换。
下面是AC代码
//hdoj1009
#include<iostream>
#include <algorithm>//sort函数在这里
#include<iomanip>
using namespace std;
#define MAX_LEN 1002//定义一个常量
struct good{
int catFood;
int javaBean;
double rate;
};//用结构体是最好的选择
bool cmp(good a,good b)//排序的规则
{
return a.rate > b.rate;
}
void main(){
struct good str[MAX_LEN];//定义一个结构体数组
int m,n,i;
while(cin>>m>>n&&(m!=-1&&n!=-1)){ //m,n等于-1时结束
double sum=0.0;//一定要用double,用float会WA
for(i=0;i<n;i++){ //依次输入数据
cin>>str[i].javaBean;
cin>>str[i].catFood;
str[i].rate=(double)(str[i].catFood)/(double)(str[i].javaBean);
}
sort(str,str+n,cmp);//根据rate排序,一开始用的是qsort,后来一直WA,后来网上有人说qsort有BUG,换了sort马上AC了
for(i=n-1;i>=0;i--){
if(m>=str[i].catFood){
m-=str[i].catFood;
sum+=str[i].javaBean;
}
else{
sum+=(double)m/str[i].rate;
break;
}
}
cout<<fixed<<setprecision(3)<<sum<<endl;//保留三位小数
}
}