• POJ_2456 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

    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.
    题意分析:
    对于在一维坐标系上的N个点,你要在这N个点上安排C头牛,让这C头牛中相邻两头牛的最小距离尽可能的大。抓住两个最值
    最小值指的是C头牛中任意相邻两头牛距离的最小距离。
    最大值指的是这个最小距离的最大值。
    那么我们需要做的就是用二分找出让这个最小距离满足条件的临界情况。
    然后输出的时候输出的左值,因为你的最终判断的是左值和右值的中值,当跳出循环的时候,因为你的中值已经不满足了,那么你的右值肯定也是不满足的,所以输出左值就是正解!
    代码:
    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    using namespace std;
    const int MAXN = 1e5+5;
    int N, C;
    int Pt[MAXN];
    
    bool fun(int x)
    {
        int pre = 0, next = 1, cnt = 1;
        while(next < N)
        {
            if(Pt[next] - Pt[pre] < x)
            {
                next++;
            }
            else
            {
                pre = next;
                next++;
                cnt++;
            }
        }
        return cnt >= C;
    }
    
    void solve()
    {
        sort(Pt, Pt+N);
        int left = Pt[0], right = Pt[N-1], mid;
        while(right - left > 1)
        {
            mid = (left+right)>>1;
            if(fun(mid))   left = mid;
            else right = mid;
        }
        printf("%d
    ", left);
    }
    
    int main()
    {
        while(~scanf("%d%d", &N, &C))
        {
            for(int i = 0; i < N; i++)
            {
                scanf("%d", &Pt[i]);
            }
            solve();
        }
        return 0;
    }
    

      

  • 相关阅读:
    精通android体系架构、mvc、常见的设计模式、控制反转(ioc)
    android UI 开发汇总
    Android 即时通讯 XMPP
    jquery $.ajax运行不正常我的调试
    [开发知识点] 使用JQuery 将DataTable 转化成JSON数据,前端无法处理JSON数据的注意事项
    [CSS]如何查看每个元素的盒子
    使用ip策略关闭不用的端口
    [小问题]?和@区别
    [修改远程桌面连接端口]
    [开发笔记]sql server中在单引号中包含单引号怎么办
  • 原文地址:https://www.cnblogs.com/dybala21/p/9679984.html
Copyright © 2020-2023  润新知