HDU 1009 FatMouse' Trade(贪心)

题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=1009

题目:

FatMouse' Trade

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


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

思路:

贪心算法。将数据先处理,算出rate[i]=J[i]/F[i],根据rate[i]做降序排序,比值大的先喂,得到的JavaBeans总值就最大。

代码:

 1 #include <cstdio>
 2 #include <vector>
 3 #include <algorithm>
 4 using namespace std;
 5 struct node{
 6     int j,f;
 7     double rate;
 8 };
 9 vector<node>v;
10 bool cmp(node x,node y){
11     return x.rate>y.rate;
12 }
13 int main(){
14     int m,n;
15     double res;
16     while (scanf("%d%d",&m,&n)!=EOF && m!=-1 && n!=-1) {
17         res=0;
18         v.clear();
19         for (int i=0; i<n; i++) {
20             node x;
21             scanf("%d%d",&x.j,&x.f);
22             x.rate=x.j*1.0/x.f;
23             v.push_back(x);
24         }
25         sort(v.begin(), v.end(), cmp);
26         for (int i=0; i<n; i++) {
27             if(v[i].f<=m){//则喂100%f[i]
28                 m-=v[i].f;
29                 res+=v[i].j;
30             }else{//将剩余的m全部喂掉
31                 res+=m*1.0/v[i].f*v[i].j;
32                 m=0;
33                 break;
34             }
35         }
36         printf("%.3lf\n",res);
37     }
38     return 0;
39 }

 

posted @ 2017-07-19 15:51  ventricle  阅读(131)  评论(0编辑  收藏  举报