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;
    }
    

      

  • 相关阅读:
    mysql 语法
    mycat 配置简介
    redis sentinel 配置
    Spark SQL 读到的记录数与 hive 读到的不一致
    HDP3.1 中 YRAN 和 MR2 的内存大小配置的计算方式
    在 windows 下搭建 IDEA + Spark 连接 Hive 的环境
    HDP3.1 中配置 YARN 的 timeline server 使用外部的 HBase
    大规模使用 Apache Kafka 的20个最佳实践
    卸载mac版本的GlobalProtect
    js解决约瑟夫问题
  • 原文地址:https://www.cnblogs.com/dybala21/p/9679984.html
Copyright © 2011-2022 走看看