前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >POJ-2018 Best Cow Fences(二分加DP)

POJ-2018 Best Cow Fences(二分加DP)

作者头像
ShenduCC
发布2018-04-26 10:35:37
5930
发布2018-04-26 10:35:37
举报
文章被收录于专栏:算法修养算法修养

Best Cow Fences Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 10174 Accepted: 3294 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

二分加DP的题目前面也做到过一道题目。选取序列的最大值和最小值,平均值在二者之间。然后二分。判断这个值是比答案的大还是小,就要用到dp。把数列的每个值都减去这个平均值,如果存在区间和大于等于0,说明这个数列存在平均在比这个还大的。用dp的思想来求这个序列最大区间和,注意区间长度要大于等于f的情况下。

代码语言:javascript
复制
#include <iostream>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <stdlib.h>

using namespace std;
#define MAX 100000
double a[MAX+5];
double s[MAX+5];
int n,f;
int fun(double ave)
{

     double num1=s[f-1]-(f-1)*ave;
    for(int i=f;i<=n;i++)
    {
        double num2=s[i]-s[i-f]-f*ave;
        num1=num1+a[i]-ave;
        num1=max(num1,num2);
        if(num1>-1e-6)
            return 1;
    }
    return 0;
}
int main()
{
    double l,r;
    while(scanf("%d%d",&n,&f)!=EOF)
    {
        l=2000;
        r=-1;

        memset(s,0,sizeof(s));

        for(int i=1;i<=n;i++)
        {
            scanf("%lf",&a[i]);
            s[i]=s[i-1]+a[i];
            r=max(r,a[i]);
            l=min(l,a[i]);
        }
        double mid;
        while(r-l>=1e-6)
        {
             mid=(l+r)/2;
            if(fun(mid))
            {
                l=mid;
            }
            else
                r=mid;
        }
        printf("%d\n",(int)(r*1000));
    }
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-01-07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档