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

来源:互联网 发布:编程一小时网站登录 编辑:程序博客网 时间:2024/06/07 01:56

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

个人觉得这个题目是一个极其经典的二分,可以作为一个模板。