Best Cow Fences_二分&&DP

Description

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. 

Input

* 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. 

Output

* 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. 

Sample Input

10 6
6 
4
2
10
3
8
5
9
4
1

Sample Output

6500

【题意】给出n个数,在这n个数里面找到一些连续的数,这些数的数量大于等于m,并且他们的平均值在这n个数里面最大

【思路】先把n个数的最大最小值确定,然后二分枚举平均值,对于每一个连续数,只要他们减去平均值大于0,就调制上限制,不然调整下限制,.......

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int N=100005;
double a[N],sum[N];
int n,m;
int check(double k)
{
    double tmp=sum[m-1]-(m-1)*k;
    for(int i=m;i<=n;i++)
    {
        tmp+=a[i]-k;
        tmp=max(tmp,sum[i]-sum[i-m]-m*k);//新选m个数和前面的数比较,取最大值
        if(tmp>-1e-6)
             return 1;
    }
    return  0;
}
int main()
{

    while(~scanf("%d%d",&n,&m))
    {
        sum[0]=0;
        double maxn=0,minx=inf;
        for(int i=1;i<=n;i++)
        {
            scanf("%lf",&a[i]);
            if(a[i]>maxn)
                maxn=a[i];
            if(a[i]<minx)
                minx=a[i];
            sum[i]=sum[i-1]+a[i];
        }
        while(maxn-minx>=1e-6)
        {
            double mid=(maxn+minx)/2;
            if(check(mid))
                minx=mid;
            else maxn=mid;
        }
        int ans=1000*maxn;
        printf("%d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/iwantstrong/p/5919594.html