HDU 2993 MAX Average Problem(斜率优化DP)

时间:2023-03-09 02:14:10
HDU 2993 MAX Average Problem(斜率优化DP)

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

题目大意:给定一个长度为n(最长为10^5)的正整数序列,求出连续的最短为k的子序列平均值的最大值。

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

分析:斜率优化DP,要认真看

代码如下:

 # include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm> using namespace std; const int maxn = ;
double a[maxn], sum[maxn];
int n,k;
int q[maxn],head,tail; //读入优化,否则超时
int GetInt()
{
char ch=getchar();
while(ch<'' || ch>'')
ch = getchar();
int num = ;
while(ch >= '' && ch<='')
{
num = num* + ch - '';
ch = getchar();
}
return num;
} void DP()
{
head = tail =;
double ans = -;
for(int i=k; i<=n; i++)
{
int j = i-k;
//维护下凸
while(tail - head >=)
{
double x1 = j - q[tail-];
double y1 = sum[j] - sum[q[tail-]];
double x2 = q[tail-] - q[tail-];
double y2 = sum[q[tail-]] - sum[q[tail-]];
if(x1 * y2 - y1 *x2 >= )
tail--;
else
break;
}
q[tail++] = j;
//寻找最优解并删除无用元素
while(tail - head >=)
{
double x1 = i - q[head];
double y1 = sum[i] - sum[q[head]];
double x2 = i - q[head+];
double y2 = sum[i] - sum[q[head+]];
if(x1*y2 - y1*x2 >= )
head ++;
else
break;
}
double tmp = (sum[i] - sum[q[head]])/(i-q[head]);
ans = max(ans, tmp);
}
printf("%.2lf\n",ans);
} int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d%d",&n,&k)!=EOF)
{
sum[] = ;
for(int i=; i<=n; i++)
{
a[i] = GetInt();
sum[i] = sum[i-] + a[i];
}
DP();
}
return ;
}