zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    iOS APP上线流程
    iOS开发:cocoapods的使用
    Swift:函数和闭包
    OC中单例的各种写法及基本讲解
    iOS:死锁
    iOS传值方式:属性,代理,block,单例,通知
    iOS支付
    Binary Tree Preorder Traversal——经典算法的迭代求解(前序,中序,后序都在这里了)
    Largest Number——STL的深层理解
    const、volatile、mutable的用法
  • 原文地址:https://www.cnblogs.com/dybala21/p/9679984.html
Copyright © 2011-2022 走看看