【算法竞赛进阶指南】最佳牛围栏 POJ 2018 Best Cow Fences

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

二分平均值
用前缀和O(1)找cows[i]…cows[j]的和

check函数要找到是否存在区间[l,r]满足区间平均值大于二分找的平均值avg
枚举全部的[l,r]区间会超时,枚举的过程是枚举每一个sum[r],再枚举每一个sum[l],判断是否存在一个sum[l]使sum[r] - sum[l] >= 0
优化:因为每一次r增加1后,l的取值范围也只会增加1,我们只需要一个最小的sum[l]即可

#include 
#include 
using namespace std;

const int maxn = 100010;
int n, f;
int cows[maxn];
double sum[maxn];

bool check(double avg)
{
    for (int i = 1; i <= n; i ++) sum[i] = sum[i-1] + cows[i] - avg;
    double minl = 0;
    for (int r = f, l = 0; r <= n; r ++, l ++ )
    {
        minl = min(minl, sum[l]);
        if (sum[r] - minl >= 0) return true;
    }
    // for (int r = f; r <= n; r ++)
    // {
    //     for (int l = 0; l + f <= r; l ++)
    //     {
    //         if (sum[r] - sum[l] >= 0) return true;
    //     }
    // } 
    return false;
}

int main()
{
    cin >> n >> f;
    for (int i = 1; i <= n; i ++) cin >> cows[i];
    double l = 0, r = 2000;
    while (r - l > 1e-5)
    {
        double mid = (l + r) / 2;
        if (check(mid)) l = mid;
        else r = mid;
    }
    cout << int(r * 1000) << endl;
    return 0;
}

你可能感兴趣的:(前缀和与差分,二分,算法竞赛进阶指南,算法竞赛进阶指南题解,C++版)