POJ-2018 Best Cow Fences(二分加DP)

时间:2022-05-09 20:48:20

Best Cow Fences

Time Limit: 1000MS Memory Limit: 30000K

Total Submissions: 10174 Accepted: 3294

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

二分加DP的题目前面也做到过一道题目。选取序列的最大值和最小值,平均值在二者之间。然后二分。判断这个值是比答案的大还是小,就要用到dp。把数列的每个值都减去这个平均值,如果存在区间和大于等于0,说明这个数列存在平均在比这个还大的。用dp的思想来求这个序列最大区间和,注意区间长度要大于等于f的情况下。

#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h> using namespace std;
#define MAX 100000
double a[MAX+5];
double s[MAX+5];
int n,f;
int fun(double ave)
{ double num1=s[f-1]-(f-1)*ave;
for(int i=f;i<=n;i++)
{
double num2=s[i]-s[i-f]-f*ave;
num1=num1+a[i]-ave;
num1=max(num1,num2);
if(num1>-1e-6)
return 1;
}
return 0;
}
int main()
{
double l,r;
while(scanf("%d%d",&n,&f)!=EOF)
{
l=2000;
r=-1; memset(s,0,sizeof(s)); for(int i=1;i<=n;i++)
{
scanf("%lf",&a[i]);
s[i]=s[i-1]+a[i];
r=max(r,a[i]);
l=min(l,a[i]);
}
double mid;
while(r-l>=1e-6)
{
mid=(l+r)/2;
if(fun(mid))
{
l=mid;
}
else
r=mid;
}
printf("%d\n",(int)(r*1000));
}
return 0;
}