Language:Default
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 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;
}