题目1433:FatMouse
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct goods{
double pound;
double price;
double ratio;
}goods[1005];
bool cmp(struct goods g1,struct goods g2){
return g1.ratio<g2.ratio;
}
int main()
{ int m,n;
while(scanf("%d%d",&m,&n)!=EOF){
if(m==-1&&n==-1)break;
for(int i=0;i<n;i++){
cin>>goods[i].pound>>goods[i].price;
goods[i].ratio=goods[i].price/goods[i].pound;
//cout<<"goods["<<i<<"].ratio="<<goods[i].ratio<<endl;
}
sort(goods,goods+n,cmp);
//for(int i=0;i<n;i++){
// cout<<goods[i].pound<<" "<<goods[i].price<<endl;
//}
int house=0;//从房间0开始访问
double javabeans=0.0;
while(m&&house!=n){
if(goods[house].price<=m){//手里的钱足够购买当前房间里所有的食品
javabeans+=goods[house].pound;
m-=goods[house].price;
}else if(goods[house].price>m){
javabeans+=goods[house].pound*(m/goods[house].price);
m=0;
}
house++;
}
printf("%.3lf\n",javabeans);
}
return 0;
}
贪心算法。