FatMouse' Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 56784 Accepted Submission(s): 19009
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.
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
简单水题,相同的题目有:HDOJ 1009、ZOJ 2109。
题目大意:胖老鼠拿M磅猫粮去贿赂守卫仓库的猫,仓库有N个房间,第i个房间有J[i]磅JavaBean且需要贿赂F[i]磅猫粮。可以选择只要J[i]*a%磅JavaBean,这样只需要贿赂F[i]*a%磅猫粮。请计算可以换取JavaBean的最大数量。
我们可以用P[i]来表示每磅猫粮能换多少JavaBean,即J[i]/F[i],可以看做性价比。对P排个序,优先选择性价比最高的进行交易,算是贪心算法的思想。需要用到结构体排序。
1 #include <stdio.h> 2 #include <algorithm> 3 struct room{int J,F;double P;}a[1010]; 4 bool cmp(const room&a, const room&b){return a.P>b.P;} 5 6 int main() 7 { 8 int M, N; 9 while(scanf("%d%d",&M,&N)&&~M) { 10 for(int i=0; i<N; i++) { 11 scanf("%d%d", &a[i].J, &a[i].F); 12 a[i].P=(double)a[i].J/a[i].F; 13 } 14 std::sort(a,a+N,cmp); 15 double maxf=.0; 16 for(int i=0; i<N; i++) 17 if(M>a[i].F) { 18 M-=a[i].F; 19 maxf+=a[i].J; 20 }else{ 21 maxf+=(double)a[i].J * M /a[i].F; 22 break; 23 } 24 printf("%.3f ",maxf); 25 } 26 return 0; 27 }