zoukankan      html  css  js  c++  java
  • POJ 2456 Aggressive cows (二分)

    题目传送门 POJ 2456 

    Description

    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个隔间和C头牛 , 给出n个隔间的位置 ,把每头牛分到一个隔间 ,问怎么分才能使任意两头牛之间的最小距离尽可能的大,求这个最大的 最小距离。
     
    解题思路:
      显然,这是一个最小值最大的问题 ,先考虑二分是否可行 ,如果可行首选二分。
      隔间的位置是无序的 ,我们先把隔间按位置从小到大进行排序,显然任意两头牛之间距离最小为0,最大为a[n-1]-a[0],我们在这个区间内二分求值。枚举每个mid,通过判断以这个值为最小距离是否能放下C头牛,然后不断缩小区间范围求得最优解。
     
    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    const int N = 100010;
    int a[N],n,m;
    int _is(int x)
    {
        int cnt=0,y=a[0];
        for (int i=1; i<n; i++)
            if (a[i]-y>=x)
            {
                cnt++;
                y=a[i];
                if (cnt+1==m)
                    return 1;
            }
        return 0;
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        for (int i=0; i<n; i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        int l=0,r=a[n-1]-a[0];
        while(l<=r)
        {
            int mid =l+(r-l)/2;
            if ( _is(mid) )
                l=mid+1;
            else r=mid-1;
        }
        if (!_is(l)) l--;
        printf("%d
    ",l);
        return 0;
    }
    View Code
     
     
  • 相关阅读:
    openpyxl(python操作Excel)
    python爬虫之数据加密解密
    python爬虫之字体反爬
    识别缩略图加载
    Windows文件共享自动失效解决办法
    pygame
    获取文件路径、文件名、后缀名
    Oracle EBS INV 挑库发放物料搬运单
    Oracle EBS INV 删除保留
    Oracle EBS INV 创建货位
  • 原文地址:https://www.cnblogs.com/l999q/p/9363125.html
Copyright © 2011-2022 走看看