一本通 1433:【例题1】愤怒的牛

愤怒的牛

二分答案模板题

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
//Mystery_Sky
//二分查找(模板) 
#define M 1000010
#define ll long long
#define Mid (l+r+1)/2
int l, r, mid;
int n, c;
int a[M];
inline bool check(int m) 
{
	int sum = a[1] + m;
	int cnt = 1;
	for(int i = 2; i <= n; i++) {
		if(a[i] >= sum) cnt++, sum = a[i] + m;
	}
	return cnt >= c;
}
int main() {
	scanf("%d%d", &n, &c);
	for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
	r = 10000000, l = 0;
	sort(a+1, a+n+1);
	while(l < r) {//二分答案
		mid = Mid;
		if(check(mid)) l = mid;
		else r = mid - 1;
	}
	printf("%d\n", l);
	return 0;
}
posted @ 2019-05-16 19:55  Mystery_Sky  阅读(226)  评论(0编辑  收藏  举报