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]maxx) maxx=sum[j]-minn;
}
我进行判断二分的条件是,只关注有没有一段区间的和大于0。
#include
#include
#include
#include
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]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<
注意倒数第三行代码,强制类型转换我不知道为什么printf过不去!!!!