Hdu - 1009 - FatMouse' Trade

上题目

FatMouse' Trade

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 33316    Accepted Submission(s): 10813


Problem 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堆的豆,每堆豆有一个余量和要这一堆豆的代价,每一堆豆可以只要一部分,那么付出的代价就按这一部分占这一堆豆的余量的百分比算。问用这m单位猫食可以最多得到多少豆。
    贪心的基础题,白书上也有类似的题目。解法就是得出每一堆豆的单价(余量/代价),先取完单价最高的豆,然后再取第二的···直到猫食用完。
 
上代码:
 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 #define MAX 1000+10
 5 using namespace std;
 6 
 7 typedef struct
 8 {
 9     double J,F;
10     double S;
11 }price;
12 
13 bool cmp(price x,price y) {return x.S>y.S;}
14 
15 price p[MAX];
16 
17 int main()
18 {
19     int i,m,n;
20     double sum;
21     //freopen("data.txt","r",stdin);
22     while(scanf("%d %d",&m,&n)!=EOF)
23     {
24         if(m==-1 && n==-1) break;
25         memset(p,0,sizeof(p));
26         for(i=0;i<n;i++)
27         {
28             scanf("%lf %lf",&p[i].J,&p[i].F);
29             p[i].S=p[i].J/p[i].F;
30         }
31         sort(p,p+n,cmp);
32         sum=0;
33         for(i=0;i<n;i++)
34         {
35             if(m>=p[i].F) {m-=p[i].F;sum+=p[i].J;}
36             else {sum+=p[i].J*m/p[i].F;break;}
37         }
38         printf("%.3lf\n",sum);
39     }
40     return 0;
41 }
1009

 

posted @ 2013-07-20 21:03  海拉鲁的林克  阅读(182)  评论(0编辑  收藏  举报