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