POJ 2018 Best Cow Fences

版权声明:本文为博主原创文章,记录蒟蒻的成长之路,欢迎吐槽~ https://blog.csdn.net/PegasiTIO/article/details/89344240

Description

Farmer John’s farm consists of a long row of N (1 <= N <= 100,000)fields. Each field contains a certain number of cows, 1 <= ncows <= 2000.

FJ wants to build a fence around a contiguous group of these fields in order to maximize the average number of cows per field within that block. The block must contain at least F (1 <= F <= N) fields, where F given as input.

Calculate the fence placement that maximizes the average, given the constraint.

Input

* Line 1: Two space-separated integers, N and F.

* Lines 2…N+1: Each line contains a single integer, the number of cows in a field. Line 2 gives the number of cows in field 1,line 3 gives the number in field 2, and so on.

Output

* Line 1: A single integer that is 1000 times the maximal average. Do not perform rounding, just print the integer that is 1000*ncows/nfields.

Sample Input

10 6
6 
4
2
10
3
8
5
9
4
1

Sample Output

6500

二分+前缀和

题意:给定正整数数列A,求一个平均数最大、长度不小于L的连续子段和

二分平均数,查找有没有一个长度为T的区间满足平均数为mid,如果有那么查找右边更大的区间,否则查找左边

在查找长度不小于L的子段,平均值不小于mid时,可以转化为让数组中的数先减去平均数,然后判断子段和是否非负

其中判断长度不小于L的最大子段和时,只需要保存0-(i-L)的中的最小值,转化为前缀和差就可以了

书上的代码最后输出的强制转换为int的结果,在l初始化为-1e6时后有一个测试点得不到正确答案,解决方法可以使用c++setprecision+fixed或者初始化l=0

#include <vector>
#include <iomanip>
#include <iostream>
using namespace std;
static const auto io_sync_off = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

const int maxn = 1e5 + 5;
double nums[maxn], sum[maxn];
int N, L;

bool check(double ave)
{
    for (int i = 1; i <= N; ++i)
        sum[i] = sum[i - 1] + (nums[i] - ave); //减去平均数并求前缀和
    double minn = 1e10, ans = -1e10;
    for (int i = L; i <= N; ++i)
    {
        minn = min(minn, sum[i - L]);//每次更新在长度大于等于L区间的最小值
        ans = max(ans, sum[i] - minn);//最大字段和
    }
    return ans >= 0;//非负代表平均数不小于二分值
}

int main()
{
    cin >> N >> L;
    for (int i = 1; i <= N; ++i)
        cin >> nums[i];

    double eps = 1e-5;
    double l = -1e6, r = 1e6;
    // for (int k = 0; k < 500; ++k)
    while (r - l > eps)
    {
        double mid = (l + r) / 2;
        if (check(mid))
            l = mid;//可以满足,查找更大的
        else
            r = mid;//不满足查找小的
    }
    cout << setprecision(0) << fixed << r * 1000 << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PegasiTIO/article/details/89344240