vjudge Aggressive cows 二分

175 阅读2分钟

思路:

  1. 最简单的,肯定是遍历,从1-N,找出第一个满足的i,但是这样太耗时了,对于N<=100,000,xN<=1,000,000,000的这题来说,遍历无异于自杀

  2. 使用二分,每次查找一个数,看是否满足,如果满足,那就说明空间可以更小一点,如果不满足,那就说明需要更大的空间

    int l=0,r=maxn,mid;// r可以直接取最大的边界n,也可以在读入数据的时候记录一个最大的n
    while(l<r){
        mid = (l+r)/2;
        if(check(mid))// mid是否可行
            r = mid;
       	else
            l = mid+1;
    }
    // 最后的l-1就是所求答案
    
  3. 而二分,最重要的就是编写check函数,毕竟二分是个模板,check才是重点,这题的check是:

    第一个牛圈必须放,然后循环遍历牛圈,当下一个牛圈和这个牛圈的距离>=mid的时候,那么放一头牛,如果<mid的话则继续查找下一个牛圈,这样如果最后所有的牛都能放入牛圈,那么这个mid就是可以用的,return true,否则return false

注水代码

#include<iostream>
#include<algorithm>
#include<cstdio>

using namespace std;
long long arr[100000+10],n,c;

// 当距离为dis的时候,这些牛是否能全部放进去
bool check(long long dis){
    long long t = c-1,pre=0; // 第一个圈必须放
    for(int i=1;i<n;i++){
        if(arr[i]-arr[pre]>=dis){
            t--;
            pre = i;
            if(t==0)return true;
        }
    }
    return t<=0;
}

/*
    可以,我怀疑是看着我做过的题来出题
    每次二分,看dis= x时是否能成立,最后得出结论
    (0 <= xi <= 1,000,000,000).这么大???
*/
int main(){
    // freopen("data.in","r",stdin);
    cin>>n>>c;
    for(int i=0;i<n;i++)
        scanf("%lld",&arr[i]);
    sort(arr,arr+n);
    long long l=0,r=1000000000,mid;
    bool can;
    while(l+1<r){
        mid = (l+r)/2;
        if(!check(mid))
            r = mid;
        else
            l = mid;
    }
    cout<<l;
    return 0;
}

最后放题面:

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