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
     
     
  • 相关阅读:
    体验js之美第八课-面向对象创建和继承终结篇
    从零到一:用Phaser.js写意地开发小游戏(Chapter 3
    HTML5 进阶系列:拖放 API 实现拖放排序
    五款轻量型bug管理工具横向测评
    用原生js写一个"多动症"的简历
    HTML5中新增Javascript特性
    Angular2入门系列(五)———— 路由参数设置
    移动端真机调试实战经验
    Java经典习题44
    Java经典习题43
  • 原文地址:https://www.cnblogs.com/l999q/p/9363125.html
Copyright © 2011-2022 走看看