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;
}