• 二分


    题目描述

    总时间限制: 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
    ", l);
        }
    }
    
  • 相关阅读:
    类方法代码重构寻找坏味道
    迭代二分查找二分查找
    系统牛逼[置顶] 使用RAMP理解内在动机 Understanding Intrinsic Motivation with RAMP
    对象服务器Webservices获取天气
    手机服务器Android消息推送(二)基于MQTT协议实现的推送功能
    概率小数2013年阿里巴巴暑期实习招聘笔试题目(不完整,笔试时间:2013.5.5)
    像素颜色JavaFX示例简易图片处理工具
    算法队列SPFA算法详解
    选择文件Eclipse制作jar包
    nullnull推箱子
  • 原文地址:https://www.cnblogs.com/zhangyue123/p/12747712.html
Copyright © 2020-2023  润新知