Best Cow Fences
Time Limit: 1000MS | Memory Limit: 30000K | |
---|---|---|
Total Submissions: 15498 | Accepted: 4979 |
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
题目链接:
http://poj.org/problem?id=2018
题意:
给你一个正整数数列a,求一个平均数最大的,长度不超过L的子段。
思路:
二分答案+前缀和
1、二分答案,判断“是否存在一个长度不小于L的子段,平均数不小于二分的值”。
2、前缀和,因为我们要找的mid是这个平均值,所以我们可以算a[i]-mid的前缀和,并且子段和非负。
s[i] = s[i-1] + a[i] - mid;假设我们要算[3,5]这个子段和,那么我们只需要输出s[5]-s[2]即可。
还有一个问题怎么在有限时间内保证子段长度不小于L。现在我们要找的这个满足题意的最优解[l,r]。那么也就是说a[l-1]要尽量地小,然后a[r]要尽量地大,所以我们可以枚举l,但是这样时间肯定是不可以的。我们发现,每一次r变大后,l的取值范围从[1,l]变成了[1,l+1],所以我们只需记录一个变量,存储当前的最小值即可。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000+10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-5;
double a[maxn];
double b[maxn];
double sum[maxn];
int main()
{
ios::sync_with_stdio(false);
int n, f;
cin >> n >> f;
double maxx = -1.0*INF;
double minn = 1.0*INF;
for(int i = 1; i <= n; i++) {
cin >> a[i];
if(a[i] > maxx)
maxx = a[i];
if(a[i] < minn)
minn = a[i];
}
double l = minn;
double r = maxx;
while((r - l) > eps) {
double mid = (l+r) / 2.0;
for(int i = 1; i <= n; i++) {
b[i] = a[i] - mid;
}
for(int i = 1; i <= n; i++) {
sum[i] = sum[i-1] + b[i];
}
double ans = -1e10;
double min_val = 1e10;
for(int i = f; i <= n; i++) {
min_val = min(min_val, sum[i-f]);
ans = max(ans, sum[i] - min_val);
}
if(ans >= 0)
l = mid;
else
r = mid;
}
cout << (int)(r*1000) << endl;
return 0;
}