XTU 1249 Rolling Variance

来源:互联网 发布:mac怎么qq远程控制 编辑:程序博客网 时间:2024/06/06 02:37

Rolling Variance

 Accepted : 77 Submit : 212Time Limit : 3000 MS Memory Limit : 65536 KB Special Judge

Rolling Variance

Bobo learnt that the variance of a sequence a1,a2,,an is

ni=1(aia¯)2n1
where
a¯=ni=1ain.

Bobo has a sequence a1,a2,,an,and he would like to find the variance of each consecutive subsequences of lengthm.Formally, the i-th (1inm+1) rolling variance ri is the variance of sequence {ai,ai+1,,ai+m1}.

Input

The input contains at most 30 sets. For each set:

The first line contains 2 integers n,m(2mn105).

The second line contains n integers a1,a2,,an (|ai|100).

Output

For each set, (nm+1) lines with floating numbers r1,r2,,rnm+1.

Your answer will be considered correct if its absolute or relative error does not exceed104.

Sample Input

3 21 3 25 31 3 2 4 5

Sample Output

1.414213560.707106781.000000001.000000001.52752523


解题思路:先求出m个连续的数的平均值a,然后求(ai-a)^2

求和:(a0+a)^2+(a1+a)^2+(a2+a)^2+(a3+a)^2+···

           =a0^2+2*a*a0+a^2+a1^2+2*a*a1+a^2+a2^2+2*a*a2+a^2+·····

           =(a0^2+a1^2+····)+a2^2+2*a*(a0+a1+a2+····)+(a^2+a^2+a^2+·····)

代码如下:

#include <stdio.h>#include <math.h>#include <string.h>#define maxn 100001int a[maxn],b[maxn];int main(){    int n,m,c;    while(scanf("%d %d",&n,&m)!=EOF)    {        int i;        for(i=1; i<=n; i++)        {            scanf("%d",&c);            a[i]=a[i-1]+c;///前i个数的和            b[i]=b[i-1]+c*c;///前i个数的平方和        }        for(i=m; i<=n;i++)        {            double s=0;            s=1.0*(a[i]-a[i-m])/(1.0*m);///求出平均数            s=b[i]-b[i-m]+s*s*m-2.0*s*(a[i]-a[i-m]);            printf("%0.8lf\n",(double)sqrt(s/(m-1)));        }    }    return 0;}



aa¯

0 0
原创粉丝点击