题目描述
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.
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.
输入
* 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.
* 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.
输出
* 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.
样例输入
10 6
6
4
2
10
3
8
5
9
4
1
样例输出
6500
分析:据说可以斜率DP,看别人题解的时候觉得很有道理,但是就是WA可还行。后来被逼无奈二分答案+DP了。
#include <iostream> #include <string> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <vector> #include <queue> #include <deque> #include <map> #define range(i,a,b) for(int i=a;i<=b;++i) #define LL long long #define rerange(i,a,b) for(int i=a;i>=b;--i) #define fill(arr,tmp) memset(arr,tmp,sizeof(arr)) using namespace std; int n,f; double ss[100005],aa[100005],Left=0x7fffffff,Right; void init(){ cin>>n>>f; range(i,1,n){ cin>>aa[i]; ss[i]+=ss[i-1]+aa[i]; Left=min(Left,aa[i]); Right=max(Right,aa[i]); } } bool judge(double val){ double tmp,pre=ss[f-1]-(f-1)*val; range(i,f,n){ tmp=(ss[i]-ss[i-f])-f*val; pre+=aa[i]-val; pre=max(tmp,pre); if(pre>-1e-5)return true; } return false; } void solve(){ while(Right-Left>1e-5){ double mid=(Right+Left)/2; if(judge(mid))Left=mid; else Right=mid; } cout<<(int)(Right*1000)<<endl; } int main() { init(); solve(); return 0; }