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.
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磅的猫粮要和n个房间里面的猫做交易来换取他喜欢吃的食物,他不需要和所有的房间都进行交易,他支出F[i],会得到J[i],
问他能得到的最大食物数。
解题思路:这算是我接触到的第一道贪心策略的题目,我用结构体来记录每个房间需要交易的猫粮和能换到的食物,以及兑换比率,贪心策略就是每次选择兑换比率大的来兑换
就能够得到最多兑换食物量。
上代码:
#include<stdio.h> #include<algorithm> using namespace std; struct food { int j; int f; double q; }; int compare(food a,food b) { if(a.q>b.q) return 1; else return 0; } int main() { int n,m,i,k,l; double s; struct food a[1000],t; while(scanf("%d%d",&m,&n)!=EOF) { if(m==-1||n==-1) break; for(i=0; i<n; i++) { scanf("%d%d",&a[i].j,&a[i].f); a[i].q=a[i].j*1.0/a[i].f; } sort(a,a+n,compare); s=0.0; for(i=0; i<n; i++) { if(m>=a[i].f) { s=s+a[i].j; m=m-a[i].f; } else if(m<a[i].f&&m>=0) { s=s+(m*a[i].q); break; } } printf("%.3lf\n",s); } return 0; }