POJ 2018 Best Cow Fences

本文介绍了一个算法问题,即寻找一个长度不小于给定值的子数组,使得该子数组内的元素平均值最大,并提供了一种使用二分查找结合前缀和的方法来解决此问题。

                                   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

题意:给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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值