ACM集训队作业----poj 2018

                                                                                      Best Cow Fences

Time Limit: 1000MS Memory Limit: 30000K
Total Submissions: 13960 Accepted: 4507

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个数字,让你求着n个数字中长度大于m的字段的最大平均值。

做这题时,是二分专题训练,所以本题要采用二分法,就是要二分答案,判断答案是否满足条件

这题当时并没有思路,然后看了其他人的博客后才知道如何写出来,二分是很好写的,主要写的是

如何判断这个值是否满足需要的条件。首先求一下数组的前缀和,把数组中的每一个元素先减去二分

出来的那个值,然后求取前缀和,在进行判断。如何判断是关键,要用两个变量minn,maxx,

    double minn=INF;
	double maxx=-INF;
	for(int j=m;j<=n;j++)
	{
		if(sum[j-m]<minn)	minn=sum[j-m];
		if(sum[j]-minn>maxx)	maxx=sum[j]-minn;	
	}

我进行判断二分的条件是,只关注有没有一段区间的和大于0。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
#define INF 1e10
double field[1000010];
int n,m;
double sum[1000010];
bool Is_ok(double x)
{
	for(int i=1;i<=n;i++)
	{
		sum[i]=sum[i-1]+(field[i]-x);
	}
	double minn=INF;
	double maxx=-INF;
	for(int j=m;j<=n;j++)
	{
		if(sum[j-m]<minn)	minn=sum[j-m];
		if(sum[j]-minn>maxx)	maxx=sum[j]-minn;	
	}
	if(maxx>=0)	return true;
	else return false;
}
int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	{
		scanf("%lf",&field[i]);
	}
	double l=0,r=1e6;
	double mid;
	double exp=1e-5;
	while(r-l>exp){
		mid=(l+r)/2;
		if(Is_ok(mid))	l=mid;
		else r=mid;
	}
	cout<<int(r*1000)<<endl;
	return 0;
}

注意倒数第三行代码,强制类型转换我不知道为什么printf过不去!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值