我们把方差公式展开
所以只需要维护一个区间平方和和区间和
当我们更新一个区间加时
#include <cstdio>
#include <iostream>
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
#define Maxn 300010
using namespace std;
double tree1[Maxn],tree2[Maxn],a[Maxn],lazy[Maxn];
void pushup(int x)
{
tree1[x]=tree1[x<<1]+tree1[x<<1|1];
tree2[x]=tree2[x<<1]+tree2[x<<1|1];
}
void pushdown(int rt,int x)
{
if (lazy[rt])
{
tree2[rt<<1]+=2*lazy[rt]*tree1[rt<<1]+(x-x>>1)*lazy[rt]*lazy[rt];
tree2[rt<<1|1]+=2*lazy[rt]*tree1[rt<<1|1]+(x>>1)*lazy[rt]*lazy[rt];
tree1[rt<<1]+=(x-x>>1)*lazy[rt];
tree1[rt<<1|1]+=(x>>1)*lazy[rt];
lazy[rt<<1]+=lazy[rt];
lazy[rt<<1|1]+=lazy[rt];
lazy[rt]=0;
}
}
void build(int rt,int l,int r)
{
if (l==r)
tree1[rt]=a[l],tree2[rt]=tree1[rt]*tree1[rt];
else
{
int mid=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
}
}
double query_a(int rt,int l,int r,int L,int R)
{
if (l>=L && r<=R)
return tree1[rt];
else
{
pushdown(rt,r-l+1);
int mid=(r+l)>>1;
double ret=0;
if (mid>=L)
ret+=query_a(lson,L,R);
if (mid<R)
ret+=query_a(rson,L,R);
return ret;
}
}
double query_b(int rt,int l,int r,int L,int R)
{
if (l>=L && r<=R)
return tree2[rt];
else
{
pushdown(rt,r-l+1);
int mid=(r+l)>>1;
double ret=0;
if (mid>=L)
ret+=query_b(lson,L,R);
if (mid<R)
ret+=query_b(rson,L,R);
return ret;
}
}
void update(int rt,int l,int r,int L,int R,double x)
{
if (l>=L && r<=R)
lazy[rt]+=x,tree2[rt]+=2*x*tree1[rt]+x*x*(r-l+1),tree1[rt]+=(r-l+1)*x;
else
{
pushdown(rt,r-l+1);
int mid=(r+l)>>1;
if (mid>=L)
update(lson,L,R,x);
if (mid<R)
update(rson,L,R,x);
pushup(rt);
}
}
main()
{
int n,m,x,y,c;
double z;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%lf",&a[i]);
build(1,1,n);
for (int i=1;i<=m;i++)
{
scanf("%d",&c);
if (c==2)
scanf("%d%d",&x,&y),printf("%.4lf\n",query_a(1,1,n,x,y)/(y-x+1));
if (c==1)
scanf("%d%d",&x,&y),cin>>z,update(1,1,n,x,y,z);
if (c==3)
{
scanf("%d%d",&x,&y);
double sum1=query_b(1,1,n,x,y)/(y-x+1),sum2=query_a(1,1,n,x,y)/(y-x+1);
double ans=sum1-sum2*sum2;
printf("%.4lf\n",ans);
}
}
}