hdu2993 斜率最佳化

來源:互聯網
上載者:User
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 DescriptionConsider 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. 


InputThere 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]. 


OutputFor 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
 


Sample Output

6.50非要自已寫getint(),非常坑,這一題主要是,轉化成斜率就好作了,用一個單調隊列儲存當前的最優解就可以了!
#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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.