HDU 1009 贪心算法
View Code
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 5 typedef struct 6 { 7 int J, F; 8 double per; 9 }Point; 10 Point P[1001]; 11 12 int cmp(const void *a,const void *b) 13 { 14 if((*(Point *)a).per < (*(Point *)b).per) 15 return 1; 16 else 17 return -1; 18 } 19 20 int main() 21 { 22 int i, j, m, n, k, num; 23 double max; 24 25 while(scanf("%d%d",&m,&n) != EOF) 26 { 27 if(m==-1 && n==-1) break; 28 for(i=0; i<n; i++) 29 { 30 scanf("%d%d",&P[i].J,&P[i].F); 31 if(P[i].F != 0) 32 P[i].per = P[i].J/(P[i].F*1.0); 33 else 34 P[i].per = 1.0; 35 } 36 qsort(P, n, sizeof(Point),cmp); 37 38 num = m; 39 max = 0.0; 40 for(i = 0; i < n; i++) 41 { 42 if(num - P[i].F >= 0) 43 { 44 max = max + P[i].J*1.0; 45 num = num - P[i].F; 46 } 47 else if(num < P[i].F) 48 { 49 max += ((num*1.0)/P[i].F)*P[i].J; 50 num = 0; 51 } 52 else if(num == 0) 53 break; 54 } 55 56 printf("%.3lf\n",max); 57 } 58 59 return 0; 60 }
要注意:
0 1
1 0
1.000 这组数据,还有就是double类型。