Check 直徑是否都滿足所有的服務點可以再做一次二分搜。不過 runtime 似乎沒有更快。
#include <bits/stdc++.h>
using namespace std;
const int N = 5e4+4;
int a[N];
int main(){
int n,k; cin>>n>>k;
for(int i = 0; i < n; i++){
cin>>a[i];
}
sort(a,a+n);
int l = 1, r = 1e9;
while(l < r){
int m = (l+r)>>1;
int now = -1, cnt = 0, fail = 0;
while(1){
int ind = upper_bound(a,a+n,now) - a;
if(ind == n) break;
now = a[ind] + m;
if(++cnt > k) {
fail = 1;
break;
}
}
if(fail) l = m+1;
else r = m;
}
cout<<l<<'\n';
}