FatMouse’ Trade - 九度教程第21题
题目
时间限制:1 秒 内存限制:128 兆 特殊判题:否
题目描述:
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.
样例输入:
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
样例输出:
13.333
31.500
题目大意如下:有M元钱,N种物品;每种物品有J[i]磅,价值F[i]元。可以使用0到F[i]的任意价格购买相应磅的物品,例如使用 F[i]* a% 元,可以购买J[i]* a% 磅物品。要求输出用M元钱最多能买到多少磅物品。
采用贪心策略,每次都买剩余物品中性价比(即重量价格比)最高的物品,直到该物品被买完或者钱耗尽。
#include <stdio.h>
#include <algorithm>
using namespace std;
struct Bean{
double weight;
double value;
double rate;
bool operator < (const Bean &B) const {
return rate > B.rate;
}
};
int main()
{
double M;
int N;
while(scanf("%lf%d",&M,&N)!=EOF && M!=-1 &&N!=-1){
Bean bean[N];
for(int i=0;i<N;i++){
scanf("%lf%lf",&bean[i].weight,&bean[i].value);
bean[i].rate=bean[i].weight/bean[i].value;//单位价值能够购买的商品重量
}
sort(bean,bean+N);
for(int i=0;i<N;i++){
printf("%lf %lf\n",bean[i].weight,bean[i].value);
}
double res=0;
for(int i=0;i<N;i++){
if(M-bean[i].value >=0){
res+=bean[i].weight;
M-=bean[i].value;
printf("buy %lf %lf\n",bean[i].weight,bean[i].value);
if(M<=0)break;
}else{
res+=(M/bean[i].value)*bean[i].weight;
printf("buy %lf %lf\n",(M/bean[i].value)*bean[i].weight,M);
break;
}
}
printf("%.3lf\n",res);
}
return 0;
}