洛谷P1824 进击的奶牛【二分答案】

题目链接:P1824 进击的奶牛
洛谷P1824 进击的奶牛【二分答案】_第1张图片

程序说明:

最大值最小化问题。明显能看出答案是在一个单调区间内的,因此用二分法来解。二分的难度主要是check函数的构造。

代码如下:

#include 
#include 
#include 
using namespace std;
const int N = 100010;
int a[N], n, c;

bool check(int x) {
	//num记录最多能放多少只奶牛 
	int num = 1, k = a[0];
	for(int i = 0; i < n; i++) {
		if(a[i] - k >= x) {
			num++;
			k = a[i]; //更新位置 
		}
	}
	if(num >= c)
		return true;
	else
		return false;
}
int main() {
	scanf("%d%d", &n, &c);
	for(int i = 0; i < n; i++)
		scanf("%d", &a[i]);
	sort(a, a + n);
	int l = a[0], r = a[n - 1];
	
	while(l < r) {
		int mid = (l + r + 1) / 2;
		if(check(mid) == true) l = mid;
		else r = mid - 1;
	}	
	printf("%d\n", l);
	return 0;
} 

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