原题:http://bailian.openjudge.cn/practice/2456/
描述
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?
中文简洁易懂型描述
输入
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
输出
* Line 1: One integer: the largest minimum distance
样例输入
5 3 1 2 8 4 9
样例输出
3
提示
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.
解法
思路:如果直接枚举,复杂度一定会超。所以一定要给区间排序。
依次尝试要求的最大最近距离能否放下所有的牛,尝试范围是MAXN/C到1,如果直接倒着尝试,复杂度为O(MAXN/C*N),超时。
二分尝试,
若D可行,看右边;若D不可行,看左边。
代码如下:
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <algorithm> 6 #define MAXP 1000000000 7 using namespace std; 8 int positions[100005] = {}; 9 int main() 10 { 11 int N, C; 12 scanf("%d %d", &N, &C); 13 for (int i = 0; i < N; i++) 14 scanf("%d", &positions[i]); 15 sort(positions, positions + N); 16 int L = 1, R = MAXP / C; 17 int result = 0; 18 while (L <= R) { 19 int D = (L + R) / 2; 20 int cowpos = 0, cownum = 1;//第一头牛放在x0 21 bool canplace = true; 22 while (cownum < C) { 23 int nextpos; 24 for (nextpos = cowpos + 1; nextpos < N; nextpos++) { 25 if (positions[nextpos] - positions[cowpos] >= D) 26 break; 27 } 28 if (nextpos < N) { 29 cownum++; 30 cowpos = nextpos; 31 continue; 32 } 33 else { 34 canplace = false; 35 break; 36 } 37 } 38 if (canplace) { 39 result = max(result, D); 40 L = D + 1; 41 } 42 else 43 R = D - 1; 44 } 45 printf("%d\n", result); 46 return 0; 47 }