您的位置:首页 > Web前端

POJ 2018 Best Cow Fences

2018-03-24 23:25 501 查看
                                   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 Input10 6
6
4
2
10
3
8
5
9
4
1
Sample Output6500题意:给N个数,求一个平均数最大的,长度不小于K的子段。
题解:二分答案,判断是否存在一个长度不小于K的子段的平均值大于二分答案,那么可以转化为将数组中的每个值减去二分值,看看是否存在子段和大于0的段;求一个子段和大于0且长度大于K,那么记录前缀和,然后将i从K-N的前缀和减去前面的最小的前缀和,在这里可以维护当前的最小前缀和,每往后走一次就判断新加进来的前缀和是否更小即可。然后判断是否存在一个子段和大于0的即可。(必须用scanf,用cin会T掉)
AC代码:#include <cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100007;
#define _for(i,a,b) for(int i=a;i<=b;i++)
int n,k;
double sum[maxn],a[maxn],b[maxn];
int main(int argc, char const *argv[])
{
scanf("%d%d",&n,&k);
_for(i,1,n)
{
scanf("%lf",&a[i]);
}
double l = -1e6;
double r = 1e6;
double eps = 1e-5;
while(r-l>eps)
{
double mid = (l+r)/2;
_for(i,1,n)b[i]=a[i]-mid;
_for(i,1,n)sum[i]=b[i]+sum[i-1];
double now = 1e10;
double ans = -1e10;
_for(i,k,n)
{
now = min(now,sum[i-k]);
ans = max(ans,sum[i]-now);
}
if(ans>=0)l = mid;
else r = mid;
}
int now = r*1000;
printf("%d\n",now);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: