Aggressive cows(分牛入舍)

前言:这群牛事真多,弄得我肝肠寸断

题面:

Aggressive cows

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 20277 Accepted: 9614

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.

Source

USACO 2005 February Gold

中文翻译

农夫 John  建造了一座很长的畜栏,它包括N (2≤N≤100,000)个隔间,这 个隔间,这些小隔间的位置为x 0 ,...,x N-1  (0≤x i ≤1,000,000,000, 均为整数, 各不相同).John的 的C (2≤C≤N)头牛每头分到一个隔间。牛都希望互相离得远点省得互相打扰。怎样才能使任意两头牛之间的最小距离尽可能的大,这个最大的最小距离是多少呢?

先贴代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[100000];
int n,c;
bool check(int d){
    int p = 0;
    int cow = 1;
    for(int i = 1;i < n;i++){
        if(a[i] >= a[p] + d){
            cow++;
            p = i;
        }
    }
    if(cow >= c)
        return true;
    else
        return false;
}

int main(){
    scanf("%d %d",&n,&c);
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    sort(a,a+n);
     int mid=-1;
    int l=1,r=(a[n-1]-a[0])/(c-1);
    while(l<=r){
        mid=(r+l)/2;
        if(check(mid))
            l=mid+1;
        else
            r=mid-1;
    }
    printf("%d\n",l-1);
    return 0;
}

理解:这个进牛舍是怎么进的呢:

        首先,进去一个牛,定义为p,占据第一个牛舍。然后我们就以此牛为标志,进行判断;在找下一头牛的时候,如果和上一头牛的距离<=d,放进去的牛的个数cow就要自增1,然后这个牛就变成新的标志,再继续往下找。

         如果说,放进去的牛的个数>=牛的个数,就说明能放下的都放下了;否则就会出现该有的牛舍都“逛”完了,而牛还没安排完那么就会出现错误。

          上面说的是check函数,然后在main函数当中,还要进行二分算法的套用。

           1--8         中点4

            1-3         中点2

            3-3         中点3

            4-3        越界错误  

          这就是最大值最小化的二分算法操作,按照我的理解就是找离某个数最能接近的数字。

         二分算法,真的真的不是缩小缩小范围那么简单啊!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值