zoukankan      html  css  js  c++  java
  • Best Cow Fences(二分)

    Farmer John's farm consists of a long row of N (1 <= N <= 100,000)fields. Each field contains a certain number of cows, 1 <= ncows <= 2000. 

    FJ wants to build a fence around a contiguous group of these fields in order to maximize the average number of cows per field within that block. The block must contain at least F (1 <= F <= N) fields, where F given as input. 

    Calculate the fence placement that maximizes the average, given the constraint. 

    输入

    * Line 1: Two space-separated integers, N and F. 

    * Lines 2..N+1: Each line contains a single integer, the number of cows in a field. Line 2 gives the number of cows in field 1,line 3 gives the number in field 2, and so on.

    输出

    * Line 1: A single integer that is 1000 times the maximal average.Do not perform rounding, just print the integer that is 1000*ncows/nfields.

     

    解题思路:  题目意思找长度大于等于的F的连续的平均值最大      我是从1e-6~1e6 开始二分的 二分一直是每个数减去平均值求前缀和  从长度为L的地方开始判断 减去i-L之前的最小值看是不是大于0即可

     

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <algorithm>
     5 #define eps 1e-6
     6 using namespace std;
     7 const double INF=0x3f3f3f3f*1.0;
     8 int n,m;
     9 double arr[100005];
    10 double sum[100005];
    11 
    12 bool check(double num){
    13     double minn=INF;
    14     for(int i=1;i<=n;i++){
    15         sum[i]=sum[i-1]+arr[i]-num;
    16     }
    17     double ans;
    18     for(int i=m;i<=n;i++){  ///看长度大于等于m的有没有大于等于0的
    19         minn=min(minn,sum[i-m]);  //i-m 之前的最小值
    20         ans=sum[i]-m;   //
    21         if(ans>=0) return true;   //这个平均值是可以达到的
    22     }
    23     return false;
    24 }
    25 
    26 void Calculation(){
    27     double left=1e-6;
    28     double right=1e6;
    29     while(left+eps<right){
    30         double mid=(left+right)/2;
    31         if(check(mid)) left=mid;
    32         else right=mid;
    33     }
    34     printf("%d
    ",(int)(right*1000));
    35 }
    36 
    37 
    38 int main(){
    39     scanf("%d%d",&n,&m);
    40     for(int i=1;i<=n;i++) scanf("%lf",&arr[i]);
    41     Calculation();
    42     return 0;
    43 }
    View Code
  • 相关阅读:
    ant脚本打jar包 自动获取时间以及项目svn版本号
    15分钟学会git基本的操作命令
    java后端模拟表单提交
    优秀js插件收藏
    javascript操作
    javascript常用方法整理--数组篇
    javascript exec方法
    javascript 拷贝
    自执行函数简单应用
    jsonp跨域原理解析
  • 原文地址:https://www.cnblogs.com/qq-1585047819/p/11256543.html
Copyright © 2011-2022 走看看