SDNU_ACM_ICPC_2020_Winter_Practice_2nd K 二分,平均值,前缀和

题目

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
    大意
    给你 n 个田地的牛数,找出连续的几块田地且田地数量 >= F,使这几块田地内的每个田地的平均牛数最大。
    输出最大的平均牛数∗1000 下取整 的值。

思路

二分平均值,再去检查是否存在长度 >= F 且平均值 > = mid 的子串.

平均值小技巧:
判断( a1+a2+...+an)/n >= mid
等价于  ( a1+a2+...+an) >= mid*n
等价于 (a1-mid)+(a2-mid)+(a3-mid)+...+(an-mid)>=0
  1. 每个数都减去 mid,问题就转化成了 看是否存在长度 >= F 且这些数的和 >= 0 的子段

  2. 对这个序列进行前缀和操作,sum [ i ]

    某个点编号为 j ,以这个点结尾的子序列,左端点编号为i,那么子序列的和就是 sum [ j ] - sum [ i ]

    判断 sum [ j ] - sum [ i ] >=0
    即判断是否存在序列满足sum [ j ] >= sum [ i ]
    i 的范围是 1 ~( j - F )

    扫描二维码关注公众号,回复: 9483942 查看本文章
  3. 我们是要判断在 i 的范围里,是否存在 sum [ i ] ,使得sum [ j ] >= sum [ i ] 成立

    既然是存在,那么只要看看在这个范围里,sum[ i ] 的最小值 是不是满足这个等式

4.二分平均值
l=0,r=2000 为平均值的初始上下限

二分来逐渐缩小最大平均值的范围

每次判断时

假若存在区间 > mid,那么mid的最大值就在 mid ~ r 中
所以 l = mid

假若不存在区间 > mid ,那么mid的最大值就在 l ~ mid 中
所以 r = mid

AC代码

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<cmath>
#include <queue>
using namespace std;
typedef long long ll;
const int N= (int)1e5;
const int inf = 0x3f3f3f3f;
int n,f;
int cows[N+10];
double sum[N+10];
bool check(double ave)
{
    for(int i=1;i<=n;i++)sum[i]=sum[i-1]+cows[i]-ave;
    ///前缀和
    double minv=inf*1.0;///sum[i]最小
    for(int j=f;j<=n;j++)
    {
        minv=min(minv,sum[j-f]);
        if(sum[j]>minv)
            return 1;///存在
    }
    return 0;
}
int main()
{
    cin>>n>>f;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&cows[i]);
    }
    double l=0,r=2000;///平均值上下限
    while(r-l>1e-5)
    {
        double mid=(l+r)/2.0;
        if(check(mid))l=mid;
        else r=mid;
    }
    printf("%d\n",int(r*1000));
    return 0;
}

发布了46 篇原创文章 · 获赞 0 · 访问量 1143

猜你喜欢

转载自blog.csdn.net/weixin_45719073/article/details/104287408