POJ 2456

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.


以样例为例,有5间牛舍,坐标分别为1、2、4、8、9,有3头牛,每间牛舍只能住一头牛,每头牛之间距离保持的越大越好,在满足每头牛之间距离至少为d时所有牛都住得下的情况下,寻找最大的d。

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 int stall[100000+5],n,c;
 5 bool check(int d)
 6 {
 7     int cnt=1,ed=1,i;
 8     do{
 9         for(i=ed+1;i<=n;i++){
10             if(stall[i]-stall[ed] >= d) break; //从当前牛舍的后一个开始遍历牛舍,遇到第一个符合的牛舍跳出 
11         }
12         if(i<=n) //如果确实找到了那个牛舍
13         {
14             cnt++; 
15             ed=i; //更新当前牛舍位置 
16         } 
17         if(cnt>=c) return 1; //如果已经让所有牛可以住下了,就返回true 
18     }while(i<n);
19     return 0;
20 }
21 int main()
22 {
23     while(scanf("%d %d",&n,&c)!=EOF)
24     {
25         for(int i=1;i<=n;i++) scanf("%d",&stall[i]);
26         sort(stall+1,stall+n+1);
27         int st=0,ed=1000000,mid;
28         while(ed-st>1)
29         {
30             int mid=st+(ed-st)/2;
31             if(check(mid)) st=mid; //如果两头牛间至少保持mid距离的情况下,可以让所有牛都住得下,就去找更大的 
32             else ed=mid; //如果两头牛间至少保持mid距离的情况下,不能让所有牛都住得下,就去找更小的
33         }
34         /*
35         例如当ed-st==2时,mid=st+1,
36         如果check(mid)==true,st=mid(即st+=1),此时再去判定 ed-st>1 == false,此时st是可以符合的
37         如果check(mid)==false,ed=mid(即ed-=1),此时再去判定 ed-st>1 == false,此时显然ed和mid都是不符合的,只能选择st 
38         */
39         printf("%d
",st);
40     }
41 }



原文地址:https://www.cnblogs.com/dilthey/p/6804171.html