Aggressive cows
Description
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
Hint
OUTPUT DETAILS: FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3. Huge input data,scanf is recommended.
#include<stdio.h>
#include<iostream>//sort函数需要用到c++
#include<algorithm>
using namespace std;
int n,c,a[1000001];
void solve();
int judge(int k);
int main()
{
scanf("%d %d",&n,&c);
int i;
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
solve();
return 0;
}
void solve()
{
int l=1,r=a[n-1]-a[0];
while(l<=r){//mid就是寻找的间距的指标
int mid=(l+r)/2;
if(judge(mid))//能容纳的话,就将精度上升,直到l>r为止
l=mid+1;
else//如果不能容纳,继续缩小mid值
r=mid-1;
}
printf("%d\n",r);
}
int judge(int k)//判断当距离为k时是否能容纳下c头牛
{
int cnt=a[0],num=1;
for(int i=1;i<n;i++){
if(a[i]-cnt>=k){
cnt=a[i];
num++;
}
if(num>=c){
return 1;
}
}
return 0;
}

本文介绍了一种解决Aggressive Cows问题的算法,该问题要求在给定的牛棚位置中找到最大最小距离,以防止牛彼此过于接近而变得具有攻击性。通过使用二分查找和贪心算法,我们能够有效地找到最优解。
980

被折叠的 条评论
为什么被折叠?



