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

来源:互联网 发布:网易养猪场 知乎 编辑:程序博客网 时间:2024/05/22 09:46

题目描述:

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 312849

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


0 0