二分 - bailian 2456:Aggressive cows

题目描述

总时间限制: 1000ms 内存限制: 65536kB
描述
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?
输入

  • Line 1: Two space-separated integers: N and C

  • Lines 2..N+1: Line i+1 contains an integer stall location, xi
    输出

  • Line 1: One integer: the largest minimum distance
    样例输入
    5 3
    1
    2
    8
    4
    9
    样例输出
    3
    提示
    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.
来源
USACO 2005 February Gold

解题分析

这道题是一个最小值最大化的问题,可以尝试将最小值问题转换为判定性问题,在这道题里,转化为判断最小距离为x时是否能将c头牛装下。然后对x从小到大进行尝试,将第一头牛放在最左边的围栏里,依次放下,如果能放下c头牛,然后再对x+1进行尝试,由于进行的是有序尝试,可以用二分查找来加快查找速度。
二分查找有两个注意点:1.满足循环终止条件。2.如果查找对象在原始序列中,每次减少后的查找区间要包含查找对象。

解题代码

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

int N, stalls[100005], cows;

int check(int x){ //如果设置牛们最小的距离为x,能不能放下所有牛
    int cnt = 1;
    int temp = stalls[0];
    for(int i = 1; i < N; i++){
        if(stalls[i] - temp >= x){
            temp = stalls[i];
            cnt++;
        }
    }
    if(cnt >= cows)
        return 1;
    else
        return 0;
}

int main(){
    while(scanf("%d%d", &N, &cows) != EOF){
        for(int i = 0; i < N; i++){
            scanf("%d", &stalls[i]);
        }
        sort(stalls, stalls + N);
        
        int l = 0, r = stalls[N-1] - stalls[0];
        int mid = l;
        while(l <r){
            mid = l + (r - l) / 2 + 1;
            if(check(mid)){ // mid距离可以满足放完所有牛
                l = mid;
            }
            else
                r = mid - 1;
        }
        printf("%d\n", l);
    }
}
posted @ 2020-04-21 20:51  zhangyue_lala  阅读(238)  评论(0编辑  收藏  举报