二分 - bailian 2456:Aggressive cows
题目描述
总时间限制: 1000ms 内存限制: 65536kB
描述
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
输入
- Line 1: Two space-separated integers: N and C
- Lines 2..N+1: Line i+1 contains an integer stall location, xi
输出 - Line 1: One integer: the largest minimum distance
样例输入
5 3
1
2
8
4
9
样例输出
3
分析
就是个最小距离最大化的问题, 当然用二分啦
先把横坐标升序排列, 写一个判断函数, 看在满足最小距离为len的情况下, 能不能使总数达到 m
然后用二分查找距离的右边界(最大值)
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1e8;
int x[maxn], n, m;
int judge(int len){
int k = 1, now = x[1];
for(int i=2; i<=n; i++) if(x[i] - now >= len) now = x[i], k++;
return (k >= m) ? 1 : 0;
}
int main(){
scanf("%d%d", &n, &m);
for(int i=1; i<=n; i++) scanf("%d", &x[i]);
sort(x+1, x+1+n);
int left = 1, right = x[n] - x[1], mid;
while(left < right){
mid = left + (right - left)/2;
if(judge(mid)) left = mid + 1;
else right = mid;
}
printf("%d
", left-1);
return 0;
}