poj2456 Aggressive cows

#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_N = 1e5 + 10;
const int INF = 0x3f3f3f3f;

int N, M;
int x[MAX_N];

bool C (int d)
{
	int last = 0;
	for (int i = 1; i < M; i++)
	{
		int crt = last + 1;
		
		while (crt < N && x[crt] - x[last] < d) crt++;
		
		if (crt == N) return false;
		last = crt;
	}
	return true;
}

void solve()
{
	// 最开始时对x数组排序
	sort(x, x + N);
	
	// 初始化解的存在范围
	int lb = 0, ub = INF; // [lb, ub)
	
	while (ub - lb > 1) 
	{
		int mid = (lb + ub) / 2;
		if (C(mid)) lb = mid;
		else ub = mid;  
	}
	cout << lb << endl;
}

int main()
{
	cin >> N >> M;
	
	for (int i = 0; i < N; i++)
	cin >> x[i];
	
	solve();
	
	return 0;
}

原文地址:https://www.cnblogs.com/mofushaohua/p/7789517.html