对两头牛之间的最大间距进行二分,在judge函数里不断的用lower_bound去寻找当前牛的下一头牛放置的最近位置,最后判断能否放下c头牛,可以的话left=mid,否则right=mid,最终输出left文章来源地址https://www.toymoban.com/news/detail-688403.html
#include <iostream>
#include <algorithm>
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;
}
文章来源:https://www.toymoban.com/news/detail-688403.html
到了这里,关于POJ 2456 Aggressive cows 二分搜素的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!