题目描述
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.
题目大意
给定一个正整数数列A,求平均数最大的,长度不小于L的连续子段。
分析
二分答案,判定是否存在一个长度为不小于L的子段,且平均数不小于二分值。
如果没有长度L这个限制,那么就是一个简单的最大子段和。
但是如果加上这个限制,那么就只需要在子段和上加以修改就可以了,每次记录当前已经计算到的最小值和之前的答案比较就可以了。
ac代码
#include<cstdio>
#include<algorithm>
#define dd double
#define N 100005
using namespace std;
int n,F;
dd a[N],b[N],sum[N];
int main(){
scanf("%d%d",&n,&F);
for(int i=1;i<=n;i++) scanf("%lf",&a[i]);
dd l=-1e6,r=1e6;
while(r-l>1e-5){
dd mid=(l+r)/2;
for(int i=1;i<=n;i++) b[i]=a[i]-mid;
for(int i=1;i<=n;i++) sum[i]=sum[i-1]+b[i];
double ans=-1e10,cnt=1e10;
for(int i=F;i<=n;i++) cnt=min(cnt,sum[i-F]),ans=max(ans,sum[i]-cnt);
if(ans>=0) l=mid;
else r=mid;
}
printf("%d",(int)(r*1000));
return 0;
}