一道简单而经典的二分,借用一点挑战上的方法
Aggressive cows
题目: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?
Input:
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output:
* Line 1: One integer: the largest minimum distance
Simple Input:
5 3
1
2
8
4
9
Simple Output:
3
题目大意:
约翰新建了一座谷仓,谷仓的N个摊位的位置分别为x1,...,xN (0 <= xi <= 1,000,000,000)。
他的C头牛对于谷仓的布局不满意,经常在进入摊位后相互侵略。为了防止它们继续发生冲突,约翰要将这些牛放进摊位中使得每两头牛之间的最小距离尽可能大,请设计一个程序将其计算出来。
代码如下:
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 int N,C,l,u,mid; 6 const int Max=1e9+15; 7 const int maxn=1e5+100; 8 int X[maxn]; //摊位的位置; 9 10 bool OK(int d){ 11 int crt=1,last=0; 12 for(int i=1;i<N;i++){ 13 if(X[i]-X[last]>=d){ 14 last=i; 15 crt++; 16 } 17 } 18 if(crt>=C) return true; 19 else return false; //通过计算最后满足所选中间值的摊位数量与牛的数量进行比较来将摊位间的距离缩小; 20 } 21 22 int main(){ 23 while(~scanf("%d%d",&N,&C)){ 24 for(int i=0;i<N;i++){ 25 scanf("%d",&X[i]); 26 } 27 sort(X,X+N); //将摊位的位置进行排序,方便后面的二分时遍历; 28 u=Max; 29 l=0; //定义初始上下限; 30 while(u-l>1){ 31 mid=(u+l)/2; 32 if(OK(mid)) l=mid; 33 else u=mid; //逐渐缩小范围,直到无法继续缩小时结束二分,取最后一次的下限作为最终取值; 34 } 35 printf("%d\n",l); 36 } 37 }
版权声明:本文允许转载,转载时请注明原博客链接,谢谢~