97 等价交换(贪心-2)

Description

黑龙江的五常大米全国闻名,每年到了秋天,农民们把自己家的大米到集市上去买,但由于五常地区还是一个比较落后的地方,还实行物物交换,即农民用大米换白面,可以用来蒸馒头啊!每个集市上大米换白面的比例并不相等,如何能用最少的大米换到最多的白面呢?(单位是斤)

Input

输入数据有多组,每组数据的第一行有2个数:m和n,m代表大米的斤数,n代表有n集市,接下来有n行,每行2个数t1和t2,表示在这个集市可以用t1斤的大米换t2斤的白面(只有t2斤的白面)。

Output

输出m斤大米能换到的白面的最大值(结果保留2位小数)

Sample Input

5 3
1 2
4 9
1 5

Sample Output

14.00
 1 #include<iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <stdio.h>
 5 #include <math.h>
 6 using namespace std;
 7 struct sa
 8 {
 9     int t1;
10     int t2;
11     double awp;
12 }data[1000];
13 double cmp(const sa &a,const sa &b)
14 {
15     return a.awp>b.awp;
16 }
17 int main()
18 {
19     double ans;
20     int n,m;
21     while(cin>>n>>m)
22     {
23         for(int i=0;i<m;i++)
24         {
25             cin>>data[i].t1>>data[i].t2;
26             data[i].awp=1.0*data[i].t2/data[i].t1;
27         }
28         sort(data,data+m,cmp);
29         ans=0.0;
30         for(int i=0;i<m;i++)
31         {
32             if(n>=data[i].t1)
33             {
34                 ans+=data[i].t2;
35                 n=n-data[i].t1;
36             }
37 
38             else
39             {ans+=n*data[i].awp;break;}
40         }
41         printf("%.2lf\n",ans);
42     }
43     return 0;
44 }
View Code

注意else之后一定要跳出for循环

posted @ 2016-04-03 16:18  Wally的博客  阅读(288)  评论(0编辑  收藏  举报