HDU1009FatMouse' Trade
FatMouse' Trade
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 3 Accepted Submission(s) : 3
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
Author
CHEN, Yue
Source
ZJCPC2004
贪心算法HDU1009 FatMouse' Trade
题目大意:
老鼠有M磅猫食。有N个房间,每个房间前有一只猫,房间里有老鼠最喜欢的食品JavaBean,J[i]。若要引开猫,必须付出相应的猫食F[i]。当然这只老鼠没必要每次都付出所有的F[i]。若它付出F[i]的a%,则得到J[i]的a%。求老鼠能吃到的做多的JavaBean。
解题思路:
老鼠要获得最多的食品,就要用最小的猫食换取最多的猫食,这就要求J[i]/F[i]的比例要大。J[i]/F[i]的比例越大,证明在这个房间,小鼠付出得到的收获最有价值。于是我们将设置结构体,结构体里设置percent放置J[i]/F[i]。然后对结构体数组进行排序。依次按比例排序的付出猫食,即可。
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; struct node { double f; double j; double s; }; bool cmp(node a,node b) { return a.s>b.s; } int main() { double m; int n; double sum; node nodes[1005]; while(~scanf("%lf%d",&m,&n)) { if(m==-1&&n==-1) break; sum=0; for(int i=0;i<n;i++) { scanf("%lf%lf",&nodes[i].j,&nodes[i].f); nodes[i].s=(double)nodes[i].j/nodes[i].f; } sort(nodes,nodes+n,cmp); for(int k=0;k<n;k++) { if(m>=nodes[k].f) { sum=sum+nodes[k].j; m=m-nodes[k].f; } else { sum=sum+m*nodes[k].s; m=0; break; } } printf("%.3lf\n",sum); } }