(二分)进击的奶牛

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 using namespace std;
 5 const int N = 100010;
 6 int house[N], n, c;
 7 bool check(int dis){
 8     int cnt = 1, place = 1; //初始时在第一个位置放一头牛
 9     for(int i = 2; i <= n; i ++){
10         if(house[i] - house[place] >= dis){
11             cnt ++;
12             place = i;  //假如能在当前位置 i 处满足条件的话,那么更新就要变成这个能放的位置,因
13         }               //为如果仅将place++的话有可能出现永远防止不了的情况
14     }
15     if(cnt < c) return false;
16     else return true;
17 }
18 int main(){
19     scanf("%d%d", &n, &c);
20     for(int i = 1; i <= n; i ++) scanf("%d", &house[i]);
21     sort(house + 1, house + 1 + n);
22     int l = 0, r = house[n] - 1, ans = 0;
23     while(l < r){
24         int mid = (l + r + 1) >> 1;
25         if(check(mid)) r = mid, ans = mid;
26         else l = mid + 1;
27     }
28     cout << ans << endl;
29 
30     return 0;
31 }
原文地址:https://www.cnblogs.com/pureayu/p/13671629.html