2010年(122)
分类: C/C++
2010-03-23 14:24:32
一、问题描述
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
二、解题思路
问题等同于给一个数组,求数组中连续K(K>=F)个元素最大的平均值。设b[i]为以第i个元素结束的子段(长度>=F)的最大平均值,c[i]表示这个子段的元素个数。n[i]为以i结束的长度为F的子段的平均值。该问题的解就是b[i]中的最大值。
得到一个递推式:
b[i]=Max( b[i-1]*c[i-1]+a[i]/(c[i-1]+1),n[i]/F);
三、代码
|
优化后的代码
参考了这位哥们的代码:http://blog.csdn.net/x_chaos/archive/2010/03/15/5381454.aspx
|
四、结果分析
只需要遍历一次整个数组即可计算出结果,帮时间复杂度为O(n),空间复杂度为O(n)。
chinaunix网友2011-07-02 10:04:57
哥们 你这DP压根是错的 O(N)的算法我还没看到过正确的 你试试这个数据 6 4 2 4 1 1 1 10 正确答案是2到6个加起来 3400吧 还是老老实实凸单调再二分吧