HDU2993——MAX Average Problem(斜率优化DP)

MAX Average Problem

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

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
2009 Multi-University Training Contest 19 - Host by BNU
 
Recommend
chenrui

解析:

          斜率优化入门题,也是个人第一道斜率优化。。。

          题有点坑,一是必须要写读入优化。。。还有那个转double时的精度问题。Debug了好久。。。

代码:

#include<cstdio>
#include<algorithm>
using namespace std;
#define N 100005

int n,d,a;
struct node
{
    int x,y;
}q[N];
int sum[N];

double check(node p1,node p2,node p3)
{
    return (double)(p2.x-p1.x)*(p3.y-p2.y)-(double)(p2.y-p1.y)*(p3.x-p2.x);
}

void work()
{
    int ed=0,st=0;
    double best=-1;
	for(int i=d;i<=n;i++)
	{
		node tmp;
		tmp.x=i-d;
		tmp.y=sum[i-d];
		while(st<ed && check(q[ed-1],q[ed],tmp)<=0)ed--;//检查队尾。遇到上凸曲线,就弹出队尾
		q[++ed]=tmp;
		node now;
		now.x=i;now.y=sum[i];
		while(st<ed && check(q[st],q[st+1],now)>=0)st++;//检查队首。利用斜率的递增性质找最优点
        double ans=(double)(q[st].y-now.y)/(q[st].x-now.x);
        best=max(best,ans);
        //for(int i=st+1;i<=ed;i++)printf("%d ",(q[i].y-q[i-1].y)/(q[i].x-q[i-1].x));
	}
	printf("%.2lf\n",best);
}

int scan()
{
    int e;
    char c;
    while(c=getchar(),c<'0'||c>'9');
    e=c-'0';
    while(c=getchar(),c>='0'&&c<='9')
    e=10*e+c-'0';
    return e;
}

void read()
{
	freopen("hdu2993.in","r",stdin);
	freopen("hdu2993.out","w",stdout);
	while(scanf("%d%d",&n,&d)!=EOF)
	{
        sum[0]=0;
	    for(int i=1;i<=n;i++)
	    {
            sum[i]=scan();
		    sum[i]+=sum[i-1];
	    }
	    work();

    }
}

int main()
{
	read();
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值