老鼠的旅行

题目源地址

Description

一只老鼠有M磅猫食,然后在N个房间里面用猫食换JavaBean,房间i中能用F[i]磅的猫食来换J[i]磅的JavaBean,而且老鼠可以在一个房间里根据一定比例a%来换取JavaBean.
现在他是这任务分配给你:告诉他,他的JavaBeans的获取能最多。

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.
M是开始时老鼠有的猫食!

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 <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 using namespace std;
 5 struct sa{
 6 int j;
 7 int f;
 8 double awk;
 9 }data[1001];
10 int cmp(const sa &a,const sa &b)
11 {
12     return (a.awk)>(b.awk);//为什么要用const 
13 }
14 
15 int main()
16 {
17     int m,n;
18     double sum;
19     int i;
20     while (cin>>m>>n)
21     {
22         sum=0;
23         if (m==-1&&n==-1)
24         break;
25         for (i=0;i<n;i++)
26         {
27             cin>>data[i].j>>data[i].f;
28             data[i].awk=(double)data[i].j/data[i].f;
29         }
30         sort (data,data+n,cmp);
31         for (i=0;i<n;i++)
32         {
33             if (m>=data[i].f)
34             {
35                 sum=sum+data[i].j;
36                 m=m-data[i].f;
37 
38             }
39             else
40             {
41                sum=sum+m*data[i].awk;//m很小的时候一个个算
42                break;//没走完所有的房间就没有猫粮了
43             }
44 
45         }printf ("%.3f\n",sum);
46     }
47 
48     return 0;
49 }

贪心算法: 贪心法并不是从整体最优考虑,它所做出的选择只是在某种意义上的局部最优。 这种局部最优选择并不总能获得整体最优解(Optimal Solution),但通常能获得近似最优解(Near-Optimal Solution)。 例:用贪心法求解付款问题。 假设有面值为5元、2元、1元、5角、2角、1角的货币,需要找给顾客4元6角现金,为使付出的货币的数量最少,首先选出1张面值不超过4元6角的最大面值的货币,即2元,再选出1张面值不超过2元6角的最大面值的货币,即2元,再选出1张面值不超过6角的最大面值的货币,即5角,再选出1张面值不超过1角的最大面值的货币,即1角,总共付出4张货币。

猜你喜欢

转载自www.cnblogs.com/twomeng/p/9476051.html