HDU1009

一 题意描述:

                                     FatMouse' Trade

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


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
 二 思路分析:
本题目主要考察贪心算法,即可以考虑用f/j的比值大小作为依据,显然f/j的值越大,老鼠和猫交易越占优势。那么我们便看可以采用f/j的数值进行排序,从前往后进行交易,直到m为0停止。
三 代码展示:
 1 #include <iostream>
 2 #include <algorithm>
 3 #include<iomanip>
 4 using namespace std;
 5 #define maxn 1005
 6 struct Room
 7 {
 8     int f,j;
 9     double value;
10 }room[maxn];
11 int cmp(Room a,Room b)
12 {
13     return a.value>b.value;
14 }
15 int main()
16 {
17     int m,n;
18     while(cin>>m>>n)
19     {
20         if(m==-1&&n==-1) break;
21         for(int i=0;i<n;i++)
22         {
23          cin>>room[i].j>>room[i].f;
24          room[i].value=(1.0*room[i].j) /room[i].f;
25         }
26         sort(room,room+n,cmp);//排序
27         double total=0;
28           for(int i=0;i<n;i++)
29           {
30               if(m<=room[i].f){total+=(room[i].j*1.0*m)/room[i].f;break;}
31               else {total+=room[i].j;m-=room[i].f;}
32           }
33         cout<<setiosflags(ios::fixed)<<setprecision(3)<<total<<endl;
34 
35     }
36     return 0;
37 }

 

posted @ 2014-07-21 16:56  future_hero  阅读(145)  评论(0编辑  收藏  举报