二分贪心练习--E(牛的距离)

题目描述:

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.
题目大意:给定每一个摊位的位置,放C只牛,求两只牛之间最小距离的最大值。

解题思路:

经典的二分算法。首先将每一个摊位的位置进行排序(stable_sort),然后用二分法求该最值。

源代码:

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
using namespace std;
int length[100005];
int main()
{
    int N,C,i;
    int max=0,mid;
    int lp,rp;
    scanf("%d",&N);
    scanf("%d",&C);
    length[0]=0;
    for (i=1;i<=N;i++)
        scanf("%d" , &length[i]);
    stable_sort(length,length+N+1);//对摊位的位置进行排序
    lp=length[1]; //二分法,lp为最小值,rp为最大值。
    rp=length[N];
    while (lp<rp)
    {
        int cnt=1; //一头牛放在第一个位置
        int j=1;
        mid=(lp+rp)/2;
        for (i=2;i<=N;i++)
        {
            if (length[i]-length[j]>=mid) //如果第i个位置减去第j个位置≥mid,可放置牛,然后从该位置再往后找
            {
                cnt++;
                j=i;
            }
        }
        if (cnt>=C) //如果mid的距离能放的牛数cnt≥给定的牛的数目,用max存该最值。
        {
            if (max<mid)
                max=mid;
            lp=mid+1;  //下界变为中间值
        }
        else
            rp=mid;
    }
    printf("%d\n",max);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值