POJ 2018 Best Cow Fences(二分最大区间平均数)题解
题意:给出长度>=f的最大连续区间平均数
思路:二分这个平均数,然后O(n)判断是否可行,再调整l,r。判断方法是,先求出每个数对这个平均数的贡献,再求出长度>=f的最大贡献的区间,如果这个最大贡献大于0说明这个二分出来的数可行。
代码:
#include<set> #include<map> #include<stack> #include<cmath> #include<queue> #include<vector> #include<string> #include<cstdio> #include<cstring> #include<sstream> #include<iostream> #include<algorithm> typedef long long ll; using namespace std; const int maxn = 1e5 + 10; const int MOD = 1e9 + 7; const int INF = 0x3f3f3f3f; double a[maxn], dis[maxn], sum[maxn]; int main(){ int n, f; while(~scanf("%d%d", &n, &f)){ for(int i = 1; i <= n; i++){ scanf("%lf", &a[i]); } sum[0] = 0; double l = -2001, r = 2001, ans = -1; while(r - l > 1e-6){ double m = (l + r) / 2.0; for(int i = 1; i <= n; i++){ dis[i] = a[i] - m; sum[i] = sum[i - 1] + dis[i]; } double tmp = -INF, left = INF; for(int i = f, j = 0; i <= n; i++, j++){ left = min(left, sum[j]); tmp = max(tmp, sum[i] - left); } if(tmp > 0){ l = m; } else{ r = m; } ans = m; } printf("%d\n", (int)(1000 * ans)); } return 0; }