POJ-2018 Best Cow Fences 二分
题意:找到一个连续区间,区间的长度至少大于f,现在要求这个区间的平均值最大。
题解:
二分找答案。
每次对于2分的mid值, 都把原来的区间减去mid, 然后找到一长度至少为f的区间, 他们的区间和>=0。
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<algorithm> 3 #include<vector> 4 #include<queue> 5 #include<map> 6 #include<iostream> 7 #include<cstring> 8 using namespace std; 9 #define Fopen freopen("_in.txt","r",stdin); freopen("_out.txt","w",stdout); 10 #define LL long long 11 #define ULL unsigned LL 12 #define fi first 13 #define se second 14 #define pb push_back 15 #define lson l,m,rt<<1 16 #define rson m+1,r,rt<<1|1 17 #define lch(x) tr[x].son[0] 18 #define rch(x) tr[x].son[1] 19 #define max3(a,b,c) max(a,max(b,c)) 20 #define min3(a,b,c) min(a,min(b,c)) 21 typedef pair<int,int> pll; 22 const int inf = 0x3f3f3f3f; 23 const LL INF = 0x3f3f3f3f3f3f3f3f; 24 const LL mod = (int)1e9+7; 25 const int N = 1e5 + 100; 26 int n, f; 27 int a[N]; 28 LL suf[N]; 29 bool check(int mid){ 30 for(int i = 1; i <= n; ++i) 31 suf[i] = suf[i-1] + a[i] - mid; 32 LL minval = 0; 33 for(int i = f; i <= n; ++i){ 34 minval = min(minval, suf[i-f]); 35 if(suf[i] - minval >= 0) return true; 36 } 37 return false; 38 } 39 int main(){ 40 scanf("%d%d", &n, &f); 41 for(int i = 1; i <= n; ++i) 42 scanf("%d", &a[i]), a[i] *= 1000; 43 int l = 0, r = inf; 44 while(l <= r){ 45 int m = l+r >> 1; 46 if(check(m)) l = m + 1; 47 else r = m - 1; 48 } 49 printf("%d\n", l-1); 50 return 0; 51 }