P1824 进击的奶牛
进击的奶牛
题目描述
Farmer John 建造了一个有
N
N
N(
2
2
2
≤
\le
≤
N
N
N
≤
\le
≤
100000
100000
100000) 个隔间的牛棚,这些隔间分布在一条直线上,坐标是
x
1
x_1
x1 ,…,
x
N
x_N
xN
(0
≤
\le
≤
x
i
x_i
xi
≤
\le
≤
1000000000
1000000000
1000000000)。
他的 C C C( 2 2 2 ≤ \le ≤ C C C ≤ \le ≤ N N N) 头牛不满于隔间的位置分布,它们为牛棚里其他的牛的存在而愤怒。为了防止牛之间的互相打斗,Farmer John 想把这些牛安置在指定的隔间,所有牛中相邻两头的最近距离越大越好。那么,这个最大的最近距离是多少呢?
输入格式
第 1 1 1 行:两个用空格隔开的数字 N N N 和 C C C。
第 2 2 2 ~ N + 1 N+1 N+1 行:每行一个整数,表示每个隔间的坐标。
输出格式
输出只有一行,即相邻两头牛最大的最近距离。
样例 #1
样例输入 #1
5 3
1
2
8
4
9
样例输出 #1
3
import java.io.*;
import java.util.Arrays;
public class Main{
static int N = 100010;
static int h[] = new int[N];
static int n, c;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String t[] = br.readLine().split(" ");
n = Integer.parseInt(t[0]);
c = Integer.parseInt(t[1]);
for(int i = 1; i <= n; i++){
h[i] = Integer.parseInt(br.readLine());
}
Arrays.sort(h, 1, n+1);
int l = 0, r = h[n] - h[1];
while(l < r){
int mid = l + r + 1 >> 1;
if(check(mid)) l = mid;
else r = mid - 1;
}
System.out.println(r);
br.close();
}
// 查看是否存在以m为最小距离的方案,
// 如果存在,说明该最近距离可能取小了,
// 如果不存在,说明该最近距离一定取大了
public static boolean check(int m){
// 从h[1]开始放奶牛有最大可能使得当前最近距离存在
int x = h[1], cnt = 1;
for(int i = 2; i <= n; i++){
if(m <= h[i] - x){
x = h[i];
cnt++;
if(cnt == c) return true;
}
}
return false;
}
}