102. 最佳牛围栏

题目链接

102. 最佳牛围栏

给定正整数数列 \(A\), 求一个平均数最大的、长度不小于 \(L\) 的 (连续的) 子段。

解题思路

二分

二分答案,先将数组中的每一个数减去二分值,则判定条件为数组中是否存在一段连续且长度不小于 \(f\) 的区间和不小于 \(0\),如果存在,则说明答案可能小了,否则答案可能大了,现预处理前缀和,关键在于求出 \(s_r-s_{l-1}\) 的最大值,其中 \(r-l+1\geq f\),可以先固定 \(r\),即求 \(b[l-1]\) 的最小值,\(O(n)\) 即可求解

  • 时间复杂度:\(O(nlogn)\)

代码

// Problem: 最佳牛围栏
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/104/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
#define eps 1e-5
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=1e5+5;
int n,f;
double l,r,a[N],b[N];
bool ck(double x)
{
	b[0]=0;
	for(int i=1;i<=n;i++)b[i]-=x,b[i]=b[i-1]+b[i];
	double res=-1e16,mn=1e16;
	for(int i=1,j=0;i<=n;i++)
	{
		if(i>=f)
			mn=min(mn,b[j++]),res=max(res,b[i]-mn);
	}
	for(int i=1;i<=n;i++)b[i]=a[i];
	return res>=0;
}
int main()
{
    scanf("%d%d",&n,&f);
    for(int i=1;i<=n;i++)scanf("%lf",&a[i]),b[i]=a[i],r=max(r,a[i]);
    while(r-l>eps)
    {
    	double mid=(l+r)/2;
    	if(ck(mid))l=mid;
    	else
    		r=mid;
    }
    printf("%d",(int)(1000*r));
    return 0;
}
posted @ 2022-04-03 11:13  zyy2001  阅读(45)  评论(0编辑  收藏  举报