1. 程式人生 > >B - Aggressive cows POJ - 2456(最大值最小化)

B - Aggressive cows POJ - 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?

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.

題目大意:

FJ有一個有n間牛棚的小屋,牛棚在一條直線上,座標為分別為x[i],但是他的c頭牛對牛棚不滿,因此會經常相互攻擊,FJ為了防止牛之間相互攻擊,決定把每頭牛都放在離其他牛儘可能遠的牛棚中,也就是要最大化最近兩頭牛之間的距離。

思路: 安排牛的位置使得最近兩頭牛的距離為d。那麼問題就變為了求C(d)的最大值的d。另外,最近兩頭牛的距離不小於d,就是說C(d)=可以安排牛的位置使得任意兩頭牛的距離都不小於d。 本題的結果d一定是個固定的數值且題目中給定了一個答案範圍,則根據條件進行判斷對該範圍不斷進行二分找到答案。
下面給出程式碼
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
const int MAX = 100010;
int a[MAX],n,m;

bool ok(int d)
{
    int t = a[0],count = 1;
    for(int i = 1;i < n;i ++)//判斷d是否滿足,若有m個滿足間距d的返回true
    {
        if(a[i] - t >= d)
        {
            count ++;
            t=a[i];
            if(count >= m)
                return true;
        }
    }
    return false;
}


int solve()//二分查詢
{
    int x = 0,y = a[n-1] - a[0];//x和y表示d範圍的上下界限
    while(x <= y)
    {
        int mid=(x+y)/2;
        if(ok(mid))
            x=mid + 1;
        else
            y=mid - 1;
    }
    return x - 1;
}


int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        for(int i = 0;i < n;i ++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        printf("%d\n",solve());
    }
    return 0;
}