题目
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
Sample Input
5 3
1
2
8
4
9
Sample Output
3
意思就是说,牛之间有意见,离得近了会打架,要让每两头牛之间的最小距离最大
#include <stdio.h>
#include <algorithm>
using namespace std;
int a[100010],n,c;
int check(int len) //判断当最小距离为len时能不能放下所有的牛
{
int sum=1,ch=a[0],i; //第一头牛放在第一个槽里
for(i=1;i<n;i++)
{
if(a[i]-ch>=len) //当a[i]这个位置距离上一头牛的位置大于len时在这个位置放一头牛
{
sum++; //更新牛的数目
ch=a[i]; //更新位置
}
}
if(sum>=c) return 1;
else return 0;
}
int main()
{
scanf("%d%d",&n,&c);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n); //把每个牛槽的位置排序
int l,r,dis,mid;
l=0; //左边界)
r=a[n-1]-a[0]; //右边界,牛槽之间的最大距离
if(c==2) //如果只有两头牛不需要进行下面的过程,一头放在第一个槽中,另一头放在第二个槽中即可
{
printf("%d\n",r);
return 0;
}
while(l<=r)
{
mid=(l+r)/2;
if(check(mid)==1) //以mid为距离可以放当前牛数及以上的牛,记录距离,左边界右移,加大距离
{
dis=mid; //可能当前距离即为最后距离(假设check函数结果为sum==c,而且已经为最大距离,但是l和r还符合while循环的条件,程序还会继续执行,所以要先记录),先记录,方便最后输出
l=mid+1;
}
else r=mid-1;
}
printf("%d\n",dis);
return 0;
}
注意:sum==c时不可以直接输出当前距离,因为要求的是最大距离,可能再次加大距离时也可以放下这么多牛。
taobao,jd优惠券