Problem-solving ideas: A mouse a total of M cat food, give n rooms, each room can use F[i] cat food in exchange for w[i] beans, ask the mouse to get the maximum number of beans sum
That is, the price of the beans per room is v[i]=f[i]/w[i], want to buy the most beans, must first buy the cheapest, then buy the second cheapest, then buy the third cheapest
When the value of-----m is 0, the sum is the maximum value so the v[i] is sorted from small to large.
|
Fatmouse ' TradeTime limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others) total submission (s): 45970 acce pted Submission (s): 15397Problem Descriptionfatmouse prepared M pounds of cat food, ready-to-trade with the cats guarding the warehouse containing He favorite food, JavaBean. The warehouse has N rooms. The i-th contains j[i] pounds of JavaBeans and requires f[i] pounds of cat food. Fatmouse does not has the to trade for all the JavaBeans in the the the same, instead, he may get j[i]* a% of pounds JavaBeans if he Pays f[i]* a% pounds of cat food. Here A is a real number. Now he's assigning this homework to you:tell him the maximum amount of JavaBeans he can obtain. inputthe input cons Ists of multiple test cases. Each test case is begins with a line containing the non-negative integers M and N. Then N lines follow, each contains, non-negative integers j[i] and f[i] respectively. The last test case was followed by Two-1 ' s. All integers is not greater than 1000. outputfor each test case, print in a single line a real number accurate 3 decimal places, which is the maximum amount of JavaBeans that FATMOuse can obtain. sample Input5 3 7 2 4 3 5 2 3 all 10-1 -1 sample Output13.333 31.500 |
#include <stdio.h>void bubblesort (double v[],int w[],int f[],int n) {int i,j; Double T; for (i=1;i<=n;i++) {for (j=i+1;j<=n;j++) {if (V[i]>v[j]) {T =v[i]; V[I]=V[J]; v[j]=t; T=f[i]; F[I]=F[J]; f[j]=t; T=w[i]; W[I]=W[J]; w[j]=t; }}}}int Main () {int n,m,i,j,w[1000],f[1000];d ouble v[1000],sum;while (scanf ("%d%d", &m,&n)!=eof&& ;(n!=-1) && (m!=-1)) {for (i=1;i<=n;i++) {scanf ("%d%d", &w[i],&f[i]); v[i]=f[i]*1.0/w[i]; } bubblesort (V,w,f,n); sum=0; for (i=1;i<=n&&v[i]<=m&&m>0;i++)//If v[i]>m, the unit price is greater than the total price, cannot be exchanged, jump out of the loop {if (M>=f[i])//Total Price can buy all the beans in the room {sum+=w[i]; M=m-f[i]; } else {sum+=m*1.0/v[i];//The Total price can only buy the room part of the beans, indicating the purchase of the beans in this room, the total price has also run out of m=0; }} printf ("%.3lf\n", sum); }}
HDU 1009 fatmouse ' trade ' greedy '