poj2456 Aggressive cows

Aggressive cows

 POJ - 2456 

题目大意:

农夫约翰搭了一间有N间牛舍的小屋。牛舍排在一条线上,第i号牛舍在第xi的位置。但是他的M头牛对小屋很不满意,因此经常互相攻击。约翰为防止牛之间互相伤害,因此决定把每头牛都放在离其他牛尽可能远的牛舍。也就是要最大化最近的两头牛之间的距离。

二分答案:

和跳石头差不多

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define maxn 100010
int n,m,a[maxn],b[maxn];
bool check(int x){
    int cnt=1,len=0;
    for(int i=2;i<=n;i++){
        len+=a[i]-a[i-1];
        if(len>=x)cnt++,len=0;
    }
    if(cnt>=m)return 1;
    else return 0;
}
int main(){
    //freopen("cola.txt","r",stdin);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    int l=0,r=a[n]-a[1];
    while(l<=r){
        int mid=(l+r)>>1;
        if(check(mid))l=mid+1;
        else r=mid-1;
    }
    printf("%d",r);
}
原文地址:https://www.cnblogs.com/thmyl/p/7044449.html