HDU 2993 MAX Average Problem

斜率优化DP。

这题是论文《用》http://wenku.baidu.com/view/b97cd22d0066f5335a8121a3.html中的例二,具体解题思路可以去论文中看看,

说说这题坑的地方,输出时如果用getchar()自己写输入的话要快大概500ms左右,存数的时候要用double,如果用int的话,就算算答案的时候乘以1.0再算也是wrong,这里贴个直接输入的代码吧。用C++AC时间大概是800ms。用G++超时。

 

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef __int64 int64;
typedef long long ll;
#define M 100005
#define N 1000005
#define max_inf 0x7f7f7f7f
#define min_inf 0x80808080
#define mod 1000000007

int n , k , q[M] , arr[M];
double sum[M];

void Solve()
{
	int i , front , rear;
	double ans = -1;
	front = 0;
	rear = 1;
	q[0] = 0;

	for (i = k ; i <= n ; i++)
	{
		int t = i-k;
		while (rear > front+1)
		{
			
			double y1 = sum[t]-sum[q[rear-1]];
			double x1 = t-q[rear-1];
			double y2 = sum[q[rear-1]]-sum[q[rear-2]];
			double x2 = q[rear-1]-q[rear-2];
			if (y1*x2 <= y2*x1)rear--;
			else break;
		}
		q[rear++] = t;

		while (front+1 < rear)
		{
			double y1 = sum[i]-sum[q[front]];
			double x1 = i-q[front];
			double y2 = sum[i]-sum[q[front+1]];
			double x2 = i-q[front+1];
			if (y2*x1 >= y1*x2)front++;
			else break;
		}
		double temp = (sum[i]-sum[q[front]])*1.0/(i-q[front]);
		if (ans < temp)ans = temp;
	}
	printf("%.2lf\n",ans);
}

int main()
{
	while (~scanf("%d%d",&n,&k))
	{
		int i;
		for (arr[0] = sum[0] = 0 , i = 1 ; i <= n ; i++)
		{
			scanf("%d",arr+i);
			sum[i] = sum[i-1]+arr[i];
		}
		Solve();
	}
	return 0;
}


 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值