N 個牛棚位置 x[i],放 C 頭牛,最大化任意兩牛最小距離。N ≤ 100,000。
d ∈ [0, maxPos-minPos]check(d):從最左棚開始,每次選距離上一頭牛 ≥ d 的最左棚,能放 ≥ C 頭則可行
bool check(int d) {
int cnt = 1, last = pos[0];
for (int i = 1; i < n; ++i)
if (pos[i] - last >= d) {
if (++cnt >= c) return true;
last = pos[i];
}
return false;
}
int solve() {
int lo = 0, hi = pos[n-1] - pos[0];
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (check(mid)) lo = mid + 1;
else hi = mid - 1;
}
return hi; // 循環結束 hi 為最大可行值
}
while (lo <= hi) + return hi 亦可,關鍵是 check 正確O(N log N + N log MaxDist)