poj 2456 Aggressive cows 贪心+二分

Aggressive cows

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25944   Accepted: 11982

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.
 
题意:有n个位置,m头奶牛,将m头奶牛放到n个位置中,在每一种放置方法中,都有一个两头奶牛之间间隔的最小距离,求在所有放置方法中,这个最小距离的最大值
 
题解:先确定最小距离的范围是在[ 0 , a[n-1]-a[0] ]之间,用二分查找不断逼近可以放下所有奶牛的最大值
 
#include<iostream>
#include<algorithm>
#include<math.h>
#define ll long long
using namespace std;
ll a[100005];
ll n,m;//n是位置数量,m是奶牛数量

int check(ll x)//判断在所有奶牛之中,两两之间的最小距离为x时能否放下所有奶牛
{
    ll cnt=1,mn=a[0];//初始值
    for(int i=1;i<n;i++)
    {
        if(a[i]-mn>=x)
        {
            cnt++;
            mn=a[i];//更新
            if(cnt==m)
                return 1;
        }
    }
    return 0;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
    sort(a,a+n);

    ll l=0,r=a[n-1]-a[0],mid;//最小距离x一定在[l,r]之间,采用二分查找方法确定x
    while(l<=r)
    {
        mid=l+(r-l)/2;
        if(check(mid))//当以mid为最小距离能放下所有奶牛时,再增大mid判断能否放下
            l=mid+1;
        else
            r=mid-1;
    }
    printf("%d\n",l-1 );//因为当l>r时退出while循环,所以结果l-1
}

 

posted @ 2019-07-15 21:08  知道了呀~  阅读(371)  评论(0编辑  收藏  举报