使用二分和贪心方法解决 POJ -2456
#include <iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int n, c;
int a[100100];
bool can(int x) { //贪心的存放,第一头牛放第一个位置,以此类推
int cow = 1, p = 1;
for (int i = 2; i <= n; i++) {
if (a[i] - a[p] >= x) { //看是否满足条件
p = i;
cow++;
}
}
//cout <<"cow: "<<cow << endl;
return cow >= c;
}
int find(int maxs) {
int l = 1, r = maxs, m; //假设答案区间 从 1 到 maxs(最大坐标) ,开始解决
int ans=-1;
while (l <= r) {
m = (l + r) / 2;
//cout <<"m: "<< m << endl;
if (can(m)) { ans = m, l = m + 1; }//当满足条件时,应该去寻找更大的
else r = m-1;
}
return ans;
}
int main() //最小值最大问题
{
while (~scanf("%d %d", &n, &c)) {
memset(a, 0, sizeof(a));
int maxs = 0;
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
maxs = max(maxs, a[i]);
}
sort(a + 1, a + n + 1);
int x = find(maxs);
cout << x << endl;
}
return 0;
}