Best Cow Fences(POJ-2018)

Problem 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

4
2
10
3
8
5
9
4
1

Sample Output

6500

题意:给出 n 个数,和一个长度 F,现在要找一个平均数最大的长度不小于 F 的子段,并将这个最大值乘以 1000 然后输出

思路:

问题实质是让找出一个长度不小于 F 的子段,使得平均数不小于二分结果的值

将数列中的每一个数都减去二分结果的值,那么问题判定就转换成:找一个长度不下小于 F 的子段,使得字段和非负

对于字段和非负问题,如果没有长度 F 的限制,那么可以借助队列,不断将新数据加入队列,一旦队列和变为负数,即将队列清空,扫描过程中出现的最大队列和即为所求

然而此问题要求子段长度不小于 F,那么可以将子序列和转成前缀和相减的形式,即用 sum[i] 来表示 a[1]~a[i] 的和,每次与新的取值 sum[i]-sum[F] 取最小即可

Source Program

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
#define Pair pair<int,int>
const double EPS = 1E6;
const int MOD = 1E9+7;
const int N = 1000000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;

int n,f;
double a[N];
double sub[N];
double sum[N];
int main() {
    scanf("%d%d",&n,&f);
    for(int i=1;i<=n;i++)
        scanf("%lf",&a[i]);

    double left=-1E6,right=1E6;
    while(right-left>1E-5){
        double mid=(left+right)/2.0;
        for(int i=1;i<=n;i++){
            sub[i]=a[i]-mid;//作差
            sum[i]=sum[i-1]+sub[i];//前缀和
        }

        double ans=-1E10;
        double minn=1E10;
        for(int i=f;i<=n;i++){
            minn=min(minn,sum[i-f]);
            ans=max(ans,sum[i]-minn);
        }

        if(ans>=0)
            left=mid;
        else
            right=mid;
    }
    int res=right*1000;
    printf("%d\n",res);

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值