zoukankan      html  css  js  c++  java
  • 一道简单而经典的二分,借用一点挑战上的方法

    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

    Simple Input:

    5     3
    1
    2
    8
    4
    9

    Simple Output:

     3

    题目大意:

                约翰新建了一座谷仓,谷仓的N个摊位的位置分别为x1,...,xN (0 <= xi <= 1,000,000,000)。

                他的C头牛对于谷仓的布局不满意,经常在进入摊位后相互侵略。为了防止它们继续发生冲突,约翰要将这些牛放进摊位中使得每两头牛之间的最小距离尽可能大,请设计一个程序将其计算出来。

    代码如下:

     1 #include <cstdio>
     2 #include <algorithm>
     3 using namespace std;
     4 
     5 int N,C,l,u,mid;
     6 const int Max=1e9+15;
     7 const int maxn=1e5+100;
     8 int X[maxn];    //摊位的位置;
     9 
    10 bool OK(int d){
    11     int crt=1,last=0;
    12     for(int i=1;i<N;i++){
    13         if(X[i]-X[last]>=d){
    14             last=i;
    15             crt++;
    16         }
    17     }
    18     if(crt>=C) return true;
    19     else  return false;       //通过计算最后满足所选中间值的摊位数量与牛的数量进行比较来将摊位间的距离缩小;
    20 }
    21 
    22 int main(){
    23     while(~scanf("%d%d",&N,&C)){
    24         for(int i=0;i<N;i++){
    25             scanf("%d",&X[i]);
    26         }
    27         sort(X,X+N);    //将摊位的位置进行排序,方便后面的二分时遍历;
    28         u=Max;
    29         l=0;            //定义初始上下限;
    30         while(u-l>1){
    31             mid=(u+l)/2;
    32             if(OK(mid)) l=mid;
    33             else u=mid;  //逐渐缩小范围,直到无法继续缩小时结束二分,取最后一次的下限作为最终取值;
    34         }
    35         printf("%d
    ",l);
    36     }
    37 }

                                                                                                                                                         

     

     

     

     

     

     

    版权声明:本文允许转载,转载时请注明原博客链接,谢谢~
  • 相关阅读:
    java代码水仙花
    java代码求奖金。要求从键盘输入利润
    java中输入3个数,从大到小的输出。。。。
    java代码从键盘输入n的值,计算1+1/2+1/3+...+1/n的值,,
    java求1+1/2+1/3+1/4+......+1/n的值
    求分数1+1/2+1/3+.....+1/n的值
    论程序员成长:如何像游戏一样打怪?新手值得重视!
    网曝某大厂员工下班健身后去领公司夜宵,被罚终身禁止领夜宵并冻结涨薪降考评!
    每个程序员都该学习的5种编程开发语言!最后一门大部分人没听过~
    C语言编程初学者基础知识学习:文件的读写操作!
  • 原文地址:https://www.cnblogs.com/Dillonh/p/8490009.html
Copyright © 2011-2022 走看看