一道简单而经典的二分,借用一点挑战上的方法

Aggressive cows

题目: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

Simple Input:

5     3
1
2
8
4
9

Simple Output:

 3

题目大意:

            约翰新建了一座谷仓,谷仓的N个摊位的位置分别为x1,...,xN (0 <= xi <= 1,000,000,000)。

            他的C头牛对于谷仓的布局不满意,经常在进入摊位后相互侵略。为了防止它们继续发生冲突,约翰要将这些牛放进摊位中使得每两头牛之间的最小距离尽可能大,请设计一个程序将其计算出来。

代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;

int N,C,l,u,mid;
const int Max=1e9+15;
const int maxn=1e5+100;
int X[maxn];    //摊位的位置;

bool OK(int d){
    int crt=1,last=0;
    for(int i=1;i<N;i++){
        if(X[i]-X[last]>=d){
            last=i;
            crt++;
        }
    }
    if(crt>=C) return true;
    else  return false;       //通过计算最后满足所选中间值的摊位数量与牛的数量进行比较来将摊位间的距离缩小;
}

int main(){
    while(~scanf("%d%d",&N,&C)){
        for(int i=0;i<N;i++){
            scanf("%d",&X[i]);
        }
        sort(X,X+N);    //将摊位的位置进行排序,方便后面的二分时遍历;
        u=Max;
        l=0;            //定义初始上下限;
        while(u-l>1){
            mid=(u+l)/2;
            if(OK(mid)) l=mid;
            else u=mid;  //逐渐缩小范围,直到无法继续缩小时结束二分,取最后一次的下限作为最终取值;
        }
        printf("%d\n",l);
    }
}
个人觉得这个题目是一个极其经典的二分,可以作为一个模板。

                                                                                                                                                     







  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值