hdu2993 斜率优化

来源:互联网 发布:tensorflow syntaxnet 编辑:程序博客网 时间:2024/06/11 05:31

MAX Average Problem

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


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 66 4 2 10 3 8 5 9 4 1
 
   
非要自已写getint(),非常坑,这一题主要是,转化成斜率就好作了,用一个单调队列保存当前的最优解就可以了!
我们可以发现,ans = min((sum[i] - sum[j])/(i-j));
(sum[i] - sum[j])/(i-j)可以抽象看成斜率,那么每个数字可以看成一个点。如图
如果,当前队列中有i,j,那么现在加入一个k,我们可以得出j是无效的,为什么呢? kij,表i,j的斜率1:kik > kjk,所以这种情况下,j是无效的。2:如果以后会出现一个t点,t在jk线的上方,那么2号线不如3号线,j是无效的,如果t 在jk线的下方,那么5号线不如6号线,j也是无效的。所以综合以上情况j是无效的,直接从单调队列中除去。所以要统护如图样的一个向下凸的线。如图二,目前,队列中有i,j,k这样三点成向下凸的线,目前出现了t点, 由于ktk > ktj > kti,所以把队头的i,j直接除去了,这样,会不会对以后的结果造成影响呢,其实,i,j不会有影响。1,如果,以后的点有个t2在jk的上方,必然是kt2k更大,i,j无用,如果t2在j,k的下方,虽然kjt2 >kkt2,但由于,kjt2 < kjk < kkt,所以直接可以忽略i,j,对以后,不会有任何影响。
通过这个图,我们也可以发现,点的横坐标是要递增,纵坐标也是要递增的,这也是能用斜率优化的前题,以后,这点,也是很有必要注意的。

Sample Output
6.50
#include <stdio.h>#include <iostream>#include <string.h>using namespace std;#define MAXN 100005struct node {    double  x,y;}q[MAXN];int prime[MAXN],sum[MAXN];double maxx;int getint(){    char c;    int sum;    while(c=getchar())    {        if(c>='0'&&c<='9')        {            sum=c-'0';            break;        }    }    while(c=getchar())    {        if(c<'0'||c>'9')        {            break;        }        sum=sum*10+c-'0';    }    return sum;}double fmax(double a,double b){    if(a>b)        return a;    return b;}bool afterm(node a,node b,node c)/*后面的大返回真*/{    if((c.y-b.y)*(b.x-a.x)-(b.y-a.y)*(c.x-b.x)>0)        return true;    return false;}int main(){    int n,k,i,s,e;    node temp,current;    while(scanf("%d%d",&n,&k)!=EOF)    {        memset(sum,0,sizeof(sum));        sum[0]=0;        for(i=1;i<=n;i++)        {            prime[i]=getint();            sum[i]=sum[i-1]+prime[i];        }        s=e=0;maxx=-1;        for(i=k;i<=n;i++)        {            temp.y=sum[i-k];            temp.x=i-k;            current.x=i;            current.y=sum[i];            while(s<e&&!afterm(q[e-1],q[e],temp))/*保持斜率单调递增*/            {                e--;            }            q[++e]=temp;            while(s<e&&afterm(q[s],q[s+1],current))/*新加的斜率比头要大,去掉头*/            {                s++;            }            maxx=fmax(maxx,(double )(current.y-q[s].y)*1.0/(current.x-q[s].x));        }        printf("%.2f\n",maxx);    }    return 0;}