【Loj #10012. 「一本通 1.2 例 2」Best Cow Fences】题解

题目链接

题目

给定一个长度为 nnn 的非负整数序列 AAA ,求一个平均数最大的,长度不小于 LLL 的子段。

思路

先二分平均值。

然后是判断。

如何判断一段数中是否存在长度大于等于 \(L\) 且平均值大于某个数的子段呢?

我们可以先让序列中的数都减去二分中的值,然后就转化为:

序列中是否存在长度大于等于 \(L\) 的字段和为正。

我们可以先构造一个前缀和。

假设我们当前算到序列中的第 \(i\) 项,我们只需要在前 \(i-L\) 项中找最小前缀和,再用 \(S_i\) 去减即可。如果为正,说明符合条件。

Code

// Problem: #10012. 「一本通 1.2 例 2」Best Cow Fences
// Contest: LibreOJ
// URL: https://loj.ac/p/10012
// Memory Limit: 512 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
//#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define M
//#define mo
#define N 100010
int n, m, i, j, k; 
int len; 
double l, r, mid, mn; 
double sum[N], a[N]; 

int check(double d)
{
	sum[0]=mn=99999999999999; 
	for(i=1; i<=n; ++i)
	{
		sum[i]=(i==1? double(0) : sum[i-1])+a[i]-d; 
		mn=min(mn, sum[max(0, i-len)]); 
		if(sum[i]-mn>0) return 1; 
	}
	if(sum[n]>0) return 1; 
	return 0; 
}

signed main()
{
//	freopen("tiaoshi.in", "r", stdin); 
//	freopen("tiaoshi.out", "w", stdout); 
	n=read(); len=read(); 
	for(i=1; i<=n; ++i) a[i]=double(read()); 
	l=-1, r=2001; 
	while(r-l>0.000000001)
	{
		// printf("%lf %lf\n", l, r); 
		mid=(l+r)/double(2); 
		if(check(mid)) l=mid; 
		else r=mid; 
	}
	printf("%d", int(r*1000)); 
	return 0; 
}

posted @ 2021-12-09 22:37  zhangtingxi  阅读(190)  评论(0编辑  收藏  举报