本文搬运自本人初中博客园博客,若图片加载不出来,可到原文查看:https://www.cnblogs.com/zhangtingxi/p/15669626.html

题目链接

题目

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

思路

先二分平均值。

然后是判断。

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

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

序列中是否存在长度大于等于 LL 的字段和为正。

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

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

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 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;
}