HDU 1009 FatMouse' Trade(贪心)

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
 1 #include<stdio.h>
 2 #include<algorithm>
 3 using namespace std;
 4 int m,n;
 5 struct x{
 6     int j,c;
 7     double q;
 8 }a[1010];
 9 bool cmp(x a,x b){//贪心,按照最少的猫粮换最多的老鼠吃的排序 
10     return a.q>b.q;
11 }
12 
13 int main(){
14     while(scanf("%d%d",&m,&n)!=EOF){
15         if(m==-1&&n==-1){
16             break;
17         }
18         for(int i=1;i<=n;i++){
19             scanf("%d%d",&a[i].j,&a[i].c);
20             a[i].q=a[i].j/(1.0*a[i].c);//求出每组的转化率 
21         }                 //乘以0.1,转化为浮点型 
22         sort(a+1,a+1+n,cmp);
23         double sum=0;
24         for(int i=1;i<=n;i++){
25             if(m>=a[i].c){//如果老鼠手里有的猫粮比要求的多,把所有的老鼠吃的都换来 
26                 sum+=a[i].j;//加上换来的鼠粮 
27                 m-=a[i].c;//手里剩下的猫粮 
28             }
29             else{
30                 sum+=a[i].q*m;//不足,就按比例换 
31                 m-=m;
32             }
33             if(m==0){
34                 break;
35             } 
36         }
37         printf("%.3f\n",sum);
38     }
39 } 

(寒いですね)

posted on 2018-12-30 16:13  甜甜圈不懂巧克力的苦  阅读(126)  评论(0编辑  收藏  举报

导航