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

題目連接:http://poj.org/problem?id=3258ios

題目大意是求刪除哪M塊石頭以後似的石頭之間的最短距離最大。spa

這道題目感受大體代碼寫起來不算困難,難點在於邊界處理上。我思考邊界思考許久,仍是沒有弄明白爲何這樣寫正確,另外的寫法就不對。code

已知的問題數據是:blog

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 }
相關文章
相關標籤/搜索