C語言貪心演算法之貪婪的老鼠
阿新 • • 發佈:2019-02-11
Greedy Mouse
時間限制:1000 ms | 記憶體限制:65535 KB 難度:3- 描述
-
A fat mouse prepared M pounds of cat food,ready to trade with the cats guarding the warehouse containing his
favorite food:peanut. The warehouse has N rooms.The ith room containsW[i] pounds of peanut and requires
F[i] pounds of cat food. Fatmouse does not have to trade for all the peanut in the room,instead,he may get
W[i]*a% pounds of peanut if he pays F[i]*a% pounds of cat food.The mouse is a stupid mouse,so can you tell
him the maximum amount of peanut he can obtain.
- 輸入
- 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 W[i] and F[i] respectively. The test case is terminated by two -1. All integers are not greater than 1000.
- 輸出
- For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of penaut that FatMouse can obtain.
- 樣例輸入
-
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
- 樣例輸出
-
13.333 31.500
- 上傳者
#include<stdio.h> #include<math.h> #include<string.h> #include<algorithm> using namespace std; int cmp(double a,double b) { return a>b; } int main() { int m,n,w[1111],f[1111]; while(scanf("%d%d",&m,&n)!=EOF) { if(m==-1&&n==-1) break; int i,j,t1,t2; double ans=0,sum=0,a[1111]; for(i=0; i<n; i++) { scanf("%d%d",&w[i],&f[i]); a[i]=(double)w[i]/f[i]; } for(i=0; i<n-1; i++) for(j=0; j<n-1-i; j++) if(a[j]<a[j+1]) { ans=a[j],t1=w[j],t2=f[j]; a[j]=a[j+1],w[j]=w[j+1],f[j]=f[j+1]; a[j+1]=ans,w[j+1]=t1,f[j+1]=t2; } for(i=0; i<n; i++) { if(m>f[i]) { sum+=w[i]; m=m-f[i]; } else { sum+=(double)m*w[i]/f[i]; break; } } printf("%.3lf\n",sum); } return 0; }