Aggressive cows

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.
比较简单的二分问题
AC代码:
 1 #include
 2 #include
 3 #include
 4 #include
 5 #include
 6 #include
 7 #include<string>
 8 #include
 9 #include
10 #include
11 #include<set>
12 #define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
13 #define CLE(a,b) memset(a,b,sizeof(a))
14 #define MEC(a,b) memcpy(a,b,sizeof(a))
15 #define ll long long
16 #define inff 0x7fffffff
17 //const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
18 //const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
19 //const int dx[9] = { 0,0,1,-1 };
20 //const int dy[9] = { 1,-1,0,0 };
21 //struct {
22 
23 //};
24 const int inf = 1e9 + 5;
25 ll book[100005];
26 int c, n;
27 int judge(int d)
28 {
29     int cur, lef = 0;
30     for (int i = 1;i < c;i++)
31     {
32         cur = lef + 1;
33         while (cur < n && book[cur] - book[lef] < d)
34         {
35             cur++;
36         }
37         if (cur == n)
38             return 0;
39         lef = cur;
40     }
41     return 1;
42 }
43 using namespace std;
44 int main()
45 {
46     cin >> n >> c;
47     for (int i = 0;i < n;i++)
48     {
49         cin >> book[i];
50     }
51     sort(book, book + n);
52     int l = 0, r = inf;
53     int ans = 0;
54     while (r >= l)
55     {
56         int mid = (l + r) >> 1;
57         if (judge(mid))
58         {
59             ans = mid;
60             l = mid + 1;
61         }
62         else r = mid - 1;
63     }
64     cout << ans << endl;
65     return 0;
66 }

 

 

你可能感兴趣的:(Aggressive cows)