POJ 2456 Aggressive cows 题解

题目

题目链接

POJ 2456 Aggressive cows

题目大意

约翰有\(N\)个牛舍,每个牛舍位置是\(X_i\)。他有\(C\)个暴躁的牛,需要把这些牛尽可能远的放在不同的牛舍里。求这些牛直接最大的距离。

题解

二分 分出个未来

假设牛之间的距离为mid,然后判断能否放下每个牛。

\(lb=0,\, ub=max(x_i),\, mid=\frac{(lb+ub)}{2}\)

然后,根据能否放下,来更新mid的值。

Then show the code.

#include <cstdio>
#include <algorithm>

using namespace std;

int n, c, x[(int)1e5+5];

bool check(int d){
    int last = 0;   // 上个牛放在了第last个位置
    for(int i=1; i<c; i++){
        int crt = last + 1;
        while(crt < n && x[crt] - x[last] < d)
            crt++;
        if(crt == n) return false;
        last = crt;
    }
    return true;
}

int main(){
    scanf("%d%d", &n, &c);
    for(int i=0; i<n; i++)
        scanf("%d", &x[i]);
    sort(x, x+n);
    int lb=0, ub=(int)(1e9+5);
    while(lb+1<ub){
        int mid = lb+(ub-lb)/2; //同 (lb+ub)/2 防止溢出
        if(check(mid)) lb = mid;
        else ub = mid;
    }
    printf("%d\n", lb);
    return 0;
}
posted @ 2021-02-23 11:08  1v7w  阅读(67)  评论(0编辑  收藏  举报