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): 5855    Accepted Submission(s): 1456


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
 

题意:
即求一段长度大于等于K且平均值最大的子串的平均值。

思路:
斜率优化入门题,推荐04年国家集训队周源的论文(这题为例题讲解),子串s+1到t的平均值为(sum[t]-sum[s])/(t-s);这个可以看做直线的斜率,根据它具有的性质来优化,具体见论文。
注意算斜率尽量用乘法算。

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 100005
#define MAXN 200005
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
typedef long long ll;
using namespace std;

int n,m,ans,cnt,tot,flag;
int a[maxn],sum[maxn];
int q[maxn];
double res;

void solve()
{
    int i,j,t,cur;
    int head=0,tail=-1;
    double pre,dx1,dy1,dx2,dy2;
    res=0;
    for(i=m; i<=n; i++)
    {
        cur=i-m;
        while(head<tail)
        {
            dy1=sum[cur]-sum[q[tail]]; dx1=cur-q[tail];
            dy2=sum[q[tail]]-sum[q[tail-1]]; dx2=q[tail]-q[tail-1];
            if(dy1*dx2<=dx1*dy2) tail--;
            else break ;
        }
        q[++tail]=cur;
        while(head<tail)
        {
            dy1=sum[i]-sum[q[head]];  dx1=i-q[head];
            dy2=sum[i]-sum[q[head+1]]; dx2=i-q[head+1];
            if(dy1*dx2<=dx1*dy2) head++;
            else break ;
        }
        res=max(res,(sum[i]-sum[q[head]]+0.0)/(i-q[head]+0.0)); // 不能写dy1/dx1 上一个循环可能不进入
    }
    printf("%.2f\n",res);
}
int main()
{
    int i,j,t;
    while(~scanf("%d%d",&n,&m))
    {
        sum[0]=0;
        for(i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            sum[i]=sum[i-1]+a[i];
        }
        solve();
    }
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值