最大化平均值
题目大意:给定你n个分数,从中找出k个数,使∑a/∑b的最大值
这一题同样的也可以用二分法来做(用DP会超时,可见二分法是多么的实用呵!),大体上是这样子:假设最大的平均值是w,那么题目就是问存不存在∑a/b>=w,我们把这条式子变形
∑a-w∑b>=0
那么这一题就变成了寻找k个最大的a-w*b,使∑a-w∑b>=0成立
1 #include <iostream> 2 #include <algorithm> 3 #include <functional> 4 5 using namespace std; 6 7 static double mid, y[1001]; 8 struct _set 9 { 10 int a,b; 11 }nums[1001]; 12 13 bool judge(const int,const int); 14 15 int main(void) 16 { 17 int n, k, t; 18 double lb, rb; 19 20 while (~scanf("%d%d", &n, &k)) 21 { 22 if (n == 0 && k == 0) 23 break; 24 for (int i = 0; i < n; i++) 25 scanf("%d", &nums[i].a); 26 for (int i = 0; i < n; i++) 27 scanf("%d", &nums[i].b); 28 lb = 0; rb = 1.00, t = 100; 29 30 while (t--) 31 { 32 mid = (lb + rb) / 2; 33 if (judge(k, n)) lb = mid; 34 else rb = mid; 35 } 36 printf("%d\n", int(100 * rb + 0.5)); 37 } 38 39 return 0; 40 } 41 42 bool judge(const int k,const int n) 43 { 44 double sum = 0; 45 46 for (int i = 0; i < n; i++) 47 y[i] = nums[i].a - nums[i].b*mid;//把∑a/b>=w移项 48 sort(y, y + n); 49 50 for (int i = 0; i < n - k; i++) 51 sum += y[n - i - 1];//要选择最大的k个,而不是最小的k个 52 return sum > 0; 53 }