POJ 3258(二分求最大化最小值)

题目链接:http://poj.org/problem?id=3258

题目大意是求删除哪M块石头之后似的石头之间的最短距离最大。

这道题目感觉大致代码写起来不算困难,难点在于边界处理上。我思考边界思考许久,还是没有弄明白为什么这样写正确,另外的写法就不对。

已知的问题数据是:

12 5 4

2 4 6 8 10
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <algorithm>
 5 using namespace std;
 6 const int maxn = 50000 + 15;
 7 int A[maxn];
 8 int L, N, M;
 9 bool C(int k){
10     int del = 0;
11     int last = 0;
12     for(int i = 1; i <= N + 1; i++){
13         if(abs(A[i] - A[last])<=k){
14             del++;
15         }
16         else 
17             last = i;
18     }
19     //cout << k << " " << del << endl; 
20     return del > M;
21 }
22 int solve(int l, int r){
23     while(l <= r){
24         int m = (l + r) >> 1;
25         if(C(m))r = m - 1;
26         else l = m + 1;
27     }
28     /*
29     2 4 6 8 10
30     12 1
31     */
32     return l;
33 }
34 int main(){
35     cin >> L >> N >> M;
36     A[0] = 0;
37     for(int i = 1; i <= N; i++){
38         cin >> A[i];
39     }
40     A[N+1] = L;
41     sort(A, A + N + 2);
42     cout << solve(0, L) << endl;
43     return 0;
44 }
原文地址:https://www.cnblogs.com/Wade-/p/6647034.html