【OJ】POJ2018 (二分,均值比较)

本文介绍了一种通过二分查找优化连续字段围栏布局的算法,旨在最大化平均牛群密度。利用二分法的单调性,将问题转化为寻找最优围栏放置方案,以满足特定条件下的最大平均值。算法巧妙地运用了平均值比较技巧,将问题简化为求解差值之和的最大化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Language:Default
Best Cow Fences
Time Limit: 1000MSMemory Limit: 30000K
Total Submissions: 13399Accepted: 4336

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

Source

题解

这题的思路是二分转判定(因为满足限制,且均值大于当前mid的字段数量,随着mid的增加而非严格递减,是典型的单调搜索问题)。但是问题在于如何判定。这就涉及到均值比较的技巧:平均值大小的比较,可以转换为每对对应元素差值之和与0的比较

由此题可以看出,二分所要求的单调性可以是非严格的,甚至连单位阶跃函数这种只有两个值的非严格单调函数下都可以使用二分。不过具体还得看题目。

代码

#include <iostream>
#include <algorithm>
#include <vector>
//这题精度要求不高
//EPS小了会超时,EPS大了会错
#define EPS 1e-4
#define N 100010

using namespace std;

int main()
{
    int n, L;//L:lower_bound
    double v[N] = {0}, sum_d[N] = {0}, d[N] = {0};
    double l = 1e9, r = 0;
    cin >> n >> L;
    for(int i = 1; i <= n; i++)
    {
        cin >> v[i];
        r = max(r, v[i]);
        l = min(l, v[i]);
    }
    while(r - l > EPS)
    {
        double mid = (l + r) / 2;
        double max_sub_sum_d = -1e9, min_sum_d = 1e9;
        //d为difference,表示v[i]与mid差值
        //这样做的好处是,能只使用加法,根据sum_d的计算结果得出当前mid是否合适
        //这是个技巧:平均值大小的比较,可以转换为每对对应元素差值之和与0的比较
        //如果不使用差值,而直接求和,最后要和nx*mid比较,这样还要维护nx,麻烦
        for(int i = 1; i <= n; i++)
            d[i] = v[i] - mid;
        for(int i = 1; i <= n; i++)
            sum_d[i] = sum_d[i - 1] + d[i];
        //这里是求到i处,为止,最大子串均值
        //思路当然是前缀和,但最佳子串长度不一定是lower_bound
        //因此要维护子串开始位置,易得是[1,i-lower_bound]区间d前缀和最小处
        for(int i = L; i <= n; i++)
        {
            min_sum_d = min(min_sum_d, sum_d[i - L]);
            max_sub_sum_d = max(max_sub_sum_d, sum_d[i] - min_sum_d);
        }
        if(max_sub_sum_d >= 0)l = mid;
        else r = mid;
    }
    cout << int(r * 1000) << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值