http://codeforces.com/contest/1003/problem/C
Input
The first line contains two integers nn and kk (1≤k≤n≤50001≤k≤n≤5000) — the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively.
The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤50001≤ai≤5000) — the temperature measures during given nn days.
Output
Print one real number — the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than kkconsecutive days.
Your answer will be considered correct if the following condition holds: |res−res0|<10−6|res−res0|<10−6, where resres is your answer, and res0res0 is the answer given by the jury's solution.
大意即:在有n个数的数列中,求max(所含元素不少于k个的连续区间的平均值)
TLE:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int k,n;
int a[5005];
double sum(int p,int q)
{
double t=0;
for(int i=p;i<q+1;i++)
{
t+=a[i];
}
return t;
}
int main()
{
cin>>n>>k;
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
double ans=0;
for(int j=0; j<n-k+1; j++)
{
for(int i=0; i<n-k+1; i++)
{
double ave=sum(i,i+k+j-1)/(k+j);
if(ave>ans)ans=ave;
}
}
printf("%.15f",ans);
}
AC:
for(int j=0; j<n-k+1; j++)
{
double sum=Sum(j,j+k-1);
ans=max(sum/k,ans);
for(int i=j+k; i<n; i++)
{
sum+=a[i];
ans=max(sum/((k+1)+(i-j-k)),ans);
}
}
思路:每一个 j 搞定max(下标从j到j+k-1的平均值,从j到j+k的平均值,从j到j+k+1的平均值,···,从j到n的平均值)。
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int k,n;
int a[5005];
double Sum(int p,int q)
{
double t=0;
for(int i=p;i<q+1;i++)
{
t+=a[i];
}
return t;
}
int main()
{
cin>>n>>k;
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
double ans=0;
for(int j=0; j<n-k+1; j++)
{
double sum=Sum(j,j+k-1);
ans=max(sum/k,ans);
for(int i=j+k;i<n;i++)
{
sum+=a[i];
ans=max(sum/((k+1)+(i-j-k)),ans);
}
}
printf("%.15f",ans);
}