Best Cow Fences(求長度不小於f的連續子串的平均值的最大值)
Best Cow Fences
時間限制: 1 Sec 記憶體限制: 128 MB
題目描述
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.
輸入
* 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.
輸出
* 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
/**/ #include <cstdio> #include <cstring> #include <cmath> #include <cctype> #include <iostream> #include <algorithm> #include <map> #include <set> #include <vector> #include <string> #include <stack> #include <queue> typedef long long LL; using namespace std; const double eps = 1e-6; int n, f; double a[100005], sum[100005], maxx[100005], b[100005]; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); scanf("%d %d", &n, &f); double l = 2005.0, r = 0; for (int i = 1; i <= n; i++){ scanf("%lf", &a[i]); l = min(l, a[i]); r = max(r, a[i]); } while(r - l > eps){ double mid = (r + l) / 2;//二分平均值 sum[0] = 0, maxx[0] = 0; for (int i = 1; i <= n; i++){ b[i] = a[i] - mid;//b[i]表示減去平均值後的a[i] sum[i] = sum[i - 1] + b[i];//字首和 maxx[i] = max(b[i], maxx[i - 1] + b[i]);//到第i項時,前面的最大連續和 } double t = sum[f];//t用來判斷是否存在有大於等於f的連續子串可以平均分mid for (int i = f + 1; i <= n; i++){ if(maxx[i - f + 1] + sum[i] - sum[i - f + 1] > t){//判斷長度為(f+(i-f+1)前面的最大可選長度)的最大值 t = maxx[i - f + 1] + sum[i] - sum[i - f + 1]; } } if(t < 0) r = mid;//如果<0說明平均值過大 else l = mid; } int ans = r * 1000; printf("%d\n", ans); return 0; } /**/