poj 2456 Aggressive cows(二分搜索之最大化最小值)

时间:2023-03-09 16:02:56
poj 2456 Aggressive cows(二分搜索之最大化最小值)

Description

Farmer John has built a new long barn, with N ( <= N <= ,) stalls. The stalls are located along a straight line at positions x1,...,xN ( <= xi <= ,,,). 

His C ( <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?

Input

* Line : Two space-separated integers: N and C 

* Lines ..N+: Line i+ contains an integer stall location, xi

Output

* Line : One integer: the largest minimum distance

Sample Input


Sample Output


Hint

OUTPUT DETAILS: 

FJ can put his  cows in the stalls at positions ,  and , resulting in a minimum distance of . 

Huge input data,scanf is recommended.

Source

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
using namespace std;
#define N 100006
#define inf 1<<32
int x[N];
int n,m;
bool solve(int d){
int cnt=;
int last=;
for(int i=;i<n;i++){
if(x[i]-x[last]>=d) {
cnt++;
last=i;
}
}
if(cnt>=m) return false;
return true;
}
int main()
{ while(scanf("%d%d",&n,&m)==){
for(int i=;i<n;i++){
scanf("%d",&x[i]);
}
sort(x,x+n);
int low=;
int high=x[n-]-x[];
while(low<high){
int mid=(low+high)>>;
if(solve(mid)){
high=mid;
}
else{
low=mid+;
}
}
printf("%d\n",low-);
}
return ;
}