Best Cow Fences(二分)

发布于 2020-06-29  0 次阅读


题面:

Best Cow Fences

题目大意:

正整数序列,找出一个区间使得平均值最大,要求该区间的长度大于等于F。

思路:

使用二分枚举平均值,使用前缀和(更快求得区间平均值)对每个位置对平均值的贡献(a[i] - mid)

AC Code:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int n, f;
double a[100009], qzh[100009];
double l = 0, r = 1e6, mid, qzhl, qzhr;

int main()
{
    scanf("%d%d", &n, &f);
    for (int i = 1; i <= n; i++)
        scanf("%lf", &a[i]);
    while (r - l > 1e-5)
    {
        mid = (l + r) / 2.0;
        for (int i = 1; i <= n; i++)
            qzh[i] = qzh[i - 1] + a[i] - mid;
        qzhl = 1e10, qzhr = -1e10;
        for (int i = f; i <= n; i++)
        {
            qzhl = min(qzhl, qzh[i - f]);
            qzhr = max(qzhr, qzh[i] - qzhl);
        }
        if (qzhr >= 0)
            l = mid;
        else
            r = mid;
    }
    printf("%d", (int)(r * 1000));
    return 0;
}

平平无奇的在校大学生