Description
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,…,xN (0 <= xi <= 1,000,000,000).
His C (2 <= 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 1: Two space-separated integers: N and C
-
Lines 2…N+1: Line i+1 contains an integer stall location, xi
Output
- Line 1: One integer: the largest minimum distance
Sample Input
5 3
1
2
8
4
9
Sample Output
3
Hint
OUTPUT DETAILS:
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
大致意思为:
一共有n个牛棚,每个牛棚的的位置为arr[i],有m头牛,牛棚之间的位置是线性的,要想让这m头牛之间的最小的距离最大化,求这个最大的最小距离。第一行输入牛棚的个数和牛的数目,随后的几行每一行输入一个牛棚的位置。
代码:
/*
问题描述:一共有n个牛棚,每个牛棚的的位置为arr[i],有m头牛,牛棚之间的位置是线性的,
要想让这m头牛之间的最小的距离最大化,求这个最大的最小距离
算法思路:把这个问题转换成为二分问题,判断m个牛棚,n头牛,dis的距离是否可行,如果可行,
则将dis的位置再二分增加,如果不行,则将dis的位置再二分减少。
*/
#include <iostream>
#include<algorithm>
const int MAXN=100;//根据自己需求改
using namespace std;
int arr[MAXN];
bool judge(int n,int m,int dis){//判断m个牛棚,n头牛,dis的距离是否可行
int current;
current=arr[0];
int sum=1;
for(int i=1;i<n;i++){
if((arr[i]-current)>=dis){
sum++;
current=arr[i];
}
if(sum>=m){
return true;
}
}
return false;
}
int main()
{int m,n;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){//输入每个牛棚的位置
scanf("%d",&arr[i]);
}
sort(arr,arr+n);//先对牛棚的位置排序
int left=1;
int right=arr[n-1]-arr[0];
while(left<=right){//二分查找位置
int middle=left+(right-left)/2;
if(judge(n,m,middle)){
left=middle+1;
}
else{
right=middle-1;
}
}
printf("%d\n",right);
return 0;
}