forked from nanwan03/poj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2456 Aggressive cows.java
48 lines (47 loc) · 1.1 KB
/
2456 Aggressive cows.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.*;
public class Main {
private static List<Long> stalls = new ArrayList<Long>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int stallNum = in.nextInt();
int cowNum = in.nextInt();
for (int i = 0; i < stallNum; ++i) {
stalls.add(in.nextLong());
}
Collections.sort(stalls);
long prev = stalls.get(0);
long right = stalls.get(stalls.size() - 1) - prev;
long left = 1;
for (int i = 1; i < stallNum; ++i) {
long dif = stalls.get(i) - prev;
left = Math.min(left, dif);
}
if (cowNum == stallNum) {
System.out.println(left);
}
while (left + 1 < right) {
long mid = left + (right - left) / 2;
if (check(mid, cowNum)) {
left = mid;
} else {
right = mid - 1;
}
}
if (check(right, cowNum)) {
System.out.println(right);
} else {
System.out.println(left);
}
}
private static boolean check(long dist, int cowNum) {
long cur = stalls.get(0);
int num = 1;
for (int i = 1 ; i < stalls.size(); ++i) {
if (stalls.get(i) - cur >= dist) {
cur = stalls.get(i);
num++;
}
}
return num >= cowNum;
}
}