$\mathcal O\left(n^2\right)\ \text{70pts}$ 做法
暴力枚举左右边界。
参考代码
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
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
constexpr const int N=100000;
int n,m,a[N+1],sum[N+1];
int main(){
// freopen("test.in","r",stdin);
// freopen("test.out","w",stdout);
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",a+i);
sum[i]=sum[i-1]+a[i];
}
int Max=-10001;
for(int l=1;l+m-1<=n;l++){
for(int r=l+m-1;r<=n;r++){
Max=max(Max,(int)(1000ll*(sum[r]-sum[l-1])/(r-l+1)));
}
}printf("%d\n",Max);
// fclose(stdin);
// fclose(stdout);
return 0;
}
$\mathcal O\left(n\log n\right)\ \text{100pts}$ 做法
二分答案之一
二分平均值的上限。
定义 $sum_i=a_1+a_2+a_3+\cdots+a_i$。
那么对于一个可能达到的平均值 $mid$,其检查函数 $check(mid)$ 需要判断的就是对于 $i\in[1,n]$ 是否存在满足 $j\leq i$ 的一对 $(i,j)$ 使得:
\[\dfrac{sum_i-sum_{j-1}}{i-j+1}\geq mid\]移项: \(sum_i-sum_{j-1}\geq mid\times (i-j+1)\) 展开: \(sum_i-sum_{j-1}\geq mid\times i-mid\times j+mid\) 再次移项: \(sum_i-mid\times i-mid\geq sum_{j-1}-mid\times j\) 对于一个确定的 $i$,左边显然可以 $\mathcal O(1)$ 得到。而右边对于每一个 $j$,也可以 $\mathcal O(1)$ 得到。
但是这样,$check(mid)$ 的时间复杂度就变为了 $\mathcal O(n^2)$,总体时间复杂度变为了 $\mathcal O(n^2\log n)$。
因此我们可以优化。
容易发现,这其实是在取前缀最小值,因此我们 $\mathcal O(n)$ 预处理后求前缀最小值,然后与前缀最小值比较即可。
记得开 long long。
AC 代码
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
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
#define int long long
using namespace std;
constexpr const int N=100000;
int n,m,a[N+1],sum[N+1];
int b[N+1];
bool check(int mid){
b[0]=2147483647;
for(int i=1;i<=n;i++){
b[i]=sum[i-1]-mid*i;
b[i]=min(b[i],b[i-1]);
}
for(int i=m;i<=n;i++){
int pl=sum[i]-mid*i-mid;
if(pl>=b[i-m+1]){
return true;
}
}return false;
}
main(){
/*freopen("test.in","r",stdin);
freopen("test.out","w",stdout);*/
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",a+i);
a[i]*=1000;
sum[i]=sum[i-1]+a[i];
}
int l=0,r=1e7,ans=0;
while(l<=r){
int mid=l+r>>1;
if(check(mid)) ans=mid,l=mid+1;
else r=mid-1;
}
printf("%d\n",ans);
/*fclose(stdin);
fclose(stdout);*/
return 0;
}