hdu 2993 MAX Average Problem(DP+斜率优化入门题)

MAX Average Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3800    Accepted Submission(s): 980


Problem Description
Consider a simple sequence which only contains positive integers as a1, a2 ... an, and a number k. Define ave(i,j) as the average value of the sub sequence ai ... aj, i<=j. Let’s calculate max(ave(i,j)), 1<=i<=j-k+1<=n.
 

Input
There multiple test cases in the input, each test case contains two lines.
The first line has two integers, N and k (k<=N<=10^5).
The second line has N integers, a1, a2 ... an. All numbers are ranged in [1, 2000].
 

Output
For every test case, output one single line contains a real number, which is mentioned in the description, accurate to 0.01.
 

Sample Input
  
  
10 6 6 4 2 10 3 8 5 9 4 1
 

Sample Output
  
  
6.50
 

Source
 

Recommend
chenrui
 

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2993

题意:给你一个数列,求大于给定长度的区间的最大平均值

分析:这题看可以想到一个简单的DP,就是枚举两个可行的边界,然后取最值就行,复杂度是O(n^2)的,肯定是超时的,那么有什么好的办法,说实话,我也是没想出来的,只能去看看周源大神的《浅谈数形结合思想在信息学竞赛中的应用》,里面还是讲得很清楚的,不过寻找切线那块貌似没讲,我一开始想错了,然后一直wa,找不到原因,后来看看别人的代码才明白,方法很简单,直接枚举队列前的几个元素与当前节点构成的斜率,小的直接退队,直到找到最大值,就是当前的最大值了,这样的话,总的均摊时间复杂度是O(n)的,完美的解决了这个问题。。。至于前面斜率小的退队为什么是正确的?简单的反证下,假设后面有个点的切线在那些低的点上,那么构成的斜率肯定比之前的小。。。懒得画图了= =

第一题斜率优化,大家轻喷

代码:

#include<cstdio>
#include<iostream>
using namespace std;
const int mm=111111;
int s[mm],q[mm];
int i,l,r,n,k;
double ans;
double slope(int a,int b)
{
    return 1.0*(s[a]-s[b])/(a-b);
}
int main()
{
    while(~scanf("%d%d",&n,&k))
    {
        ans=s[0]=l=0,r=-1;
        for(i=1;i<=n;++i)
            scanf("%d",&s[i]),s[i]+=s[i-1];
        for(i=0;i+k<=n;++i)
        {
            while(l<r&&slope(i,q[r])<=slope(q[r],q[r-1]))--r;
            q[++r]=i;
            while(l<r&&slope(i+k,q[l])<=slope(i+k,q[l+1]))++l;
            ans=max(ans,slope(i+k,q[l]));
        }
        printf("%.2lf\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值