SDUT FatMouse' Trade(贪心算法)

题目描述

 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

贪心算法:
题目意思:
以第一组数据为例:最多卖n=5单位重量的货物,有m=3种货物
下面m=3行 为 每种货物的单价,具有的重量,求出能获得的最大收入;

思路:
按单位重量价格(价格除以重量)由大到小排序;
从最大的单位重量价格开始计算;
求出最大的价格;

 1 #include<stdio.h>

 2 #include<stdlib.h>

 3 int main()

 4 {struct

 5 {

 6     double money,weight,rat;

 7 }num[10000],t;

 8 

 9     int n,i,j,m,k,s;

10     double sum;

11      while(scanf("%d %d",&s,&m)&&s!=-1||m!=-1)

12         {

13             sum=0;

14         for(j=0;j<m;j++)

15         {

16             scanf("%lf %lf",&num[j].money,&num[j].weight);         //单价 ,重量

17             num[j].rat=num[j].money/num[j].weight;                 //单位重量价格

18         }

19         for(k=0;k<=m-2;k++)                                        //单位重量价格由大到小排序

20         for(j=0;j<=m-k-2;j++)

21         {

22             if(num[j].rat<num[j+1].rat)

23             {

24                 t=num[j];num[j]=num[j+1];

25                 num[j+1]=t;

26             }

27         }

28         for(j=0;j<m;j++)                                    //计算卖出货物的最大价格

29         {

30             if(s>=num[j].weight)

31             {

32                 sum=sum+1.0*num[j].money;

33                 s=s-num[j].weight;

34             }

35             else

36             {

37             sum+=1.0*num[j].money*s/num[j].weight;

38             break;

39             }

40         }

41 

42     printf("%.3lf\n",sum);

43     }

44     return 0;

45 }

 



你可能感兴趣的:(贪心算法)