POJ 2456 Aggressive cows 二分搜素

对两头牛之间的最大间距进行二分,在judge函数里不断的用lower_bound去寻找当前牛的下一头牛放置的最近位置,最后判断能否放下c头牛,可以的话left=mid,否则right=mid,最终输出left

#include 
#include 
using namespace std;
typedef long long ll;
ll arr[100007], inf = 0x3f3f3f3f3f3f3f3f;
int n, c;
void input()
{
    scanf("%d%d", &n, &c);
    for (int i = 0; i < n; i++)
    {
        scanf("%lld", &arr[i]);
    }
    sort(arr, arr + n);
    arr[n] = inf;
}
bool judge(ll mid)
{
    int count = 1;
    int next = 0;
    while (next < n && count < c)
    {
        next = lower_bound(arr, arr + n + 1, arr[next] + mid) - arr;
        if (next != n)
        {
            count++;
        }
    }
    return count >= c;
}
void binarySearch()
{
    ll left = -1, right = arr[n - 1] - arr[0] + 1;
    while (left + 1 < right)
    {
        ll mid = (left + right) / 2;
        if (judge(mid))
        {
            left = mid;
        }
        else
        {
            right = mid;
        }
    }
    printf("%lld\n", left);
}
int main()
{
    input();
    binarySearch();
    return 0;
}

你可能感兴趣的:(算法)