1. 程式人生 > >二分搜尋——不光是查詢值

二分搜尋——不光是查詢值

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 const int maxn = 100000 + 10;
 6 const double inf = 0x3f3f3f3f;
 7 const double EPS = 1.0e-6;
 8 
 9 int N, K;
10 int v[maxn], w[maxn];
11 struct Node {
12     double val;
13     int id;
14 } y[maxn];
15 
16 bool cmp(struct
Node a, struct Node b) { 17 return a.val > b.val; 18 } 19 bool C(double x) { 20 for(int i = 0; i < N; i++) { 21 y[i].id = i + 1; 22 y[i].val = (v[i] - x * w[i]); 23 } 24 25 sort(y, y + N, cmp); 26 double sum = 0; 27 for(int i = 0; i < K; i++) { 28 sum += y[i].val;
29 } 30 return sum >= 0; 31 } 32 void solve() { 33 double lb = 0, ub = inf; 34 35 while(ub - lb > EPS) { 36 double mid = (ub + lb) / 2; 37 if(C(mid)) 38 lb = mid; 39 else 40 ub = mid; 41 } 42 43 for(int i = 0; i < K - 1
; i++) { 44 printf("%d ", y[i].id); 45 } 46 printf("%d ", y[K - 1].id); 47 } 48 49 int main() 50 { 51 while(scanf("%d%d", &N, &K) != EOF) { 52 for(int i = 0; i < N; i++) { 53 scanf("%d%d", &v[i], &w[i]); 54 } 55 56 solve(); 57 } 58 return 0; 59 }