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;
}

猜你喜欢

转载自blog.csdn.net/xiao_you_you/article/details/80458915